5
5
import org .junit .jupiter .api .BeforeAll ;
6
6
import org .junit .jupiter .api .Test ;
7
7
8
+ import java .io .File ;
9
+ import java .io .IOException ;
8
10
import java .lang .foreign .Arena ;
9
11
import java .lang .foreign .MemorySegment ;
12
+ import java .net .URL ;
10
13
import java .nio .ByteBuffer ;
11
14
import java .nio .charset .StandardCharsets ;
15
+ import java .nio .file .Files ;
12
16
13
17
import static com .virustotal .yara .yara_h .C_POINTER ;
14
18
import static com .virustotal .yara .yara_h .ERROR_SUCCESS ;
17
21
18
22
public class YaraJavaTests {
19
23
public static final int NULL_CHAR = 1 ;
24
+ public static final int ZERO_ERRORS = 0 ;
20
25
21
26
@ BeforeAll
22
- public static void init (){
23
- yr_initialize ();
27
+ public static void init () {
28
+ int initialized = yr_initialize ();
29
+ Assertions .assertEquals (ERROR_SUCCESS (), initialized );
24
30
}
25
31
26
32
@ Test
27
- public void testYaraVersion (){
33
+ public void testYaraVersion () {
28
34
ByteBuffer versionBuffer = YR_VERSION ().asByteBuffer ();
29
35
byte [] versionBytes = new byte [versionBuffer .remaining () - NULL_CHAR ];
30
36
versionBuffer .get (versionBytes );
@@ -49,8 +55,44 @@ public void testYaraCompilerCreateAndDestroy() {
49
55
}
50
56
}
51
57
58
+ @ Test
59
+ public void testYaraCompilerAddString () {
60
+ try (Arena arena = Arena .openConfined ()) {
61
+ MemorySegment compilerAddress = arena .allocate (C_POINTER ); // YR_COMPILER**
62
+ int created = yr_compiler_create (compilerAddress );
63
+ Assertions .assertEquals (ERROR_SUCCESS (), created );
64
+ MemorySegment compiler = compilerAddress .get (C_POINTER , 0 ); // YR_COMPILER*
65
+
66
+ URL path = this .getClass ().getResource ("/yara/rules/doc" );
67
+ Assertions .assertNotNull (path );
68
+
69
+ File yaraDocRulesDir = new File (path .getPath ());
70
+ File [] rules = yaraDocRulesDir .listFiles ((dir , name ) -> name .endsWith (".yara" ));
71
+
72
+ Assertions .assertNotNull (rules );
73
+ Assertions .assertTrue (rules .length > 0 );
74
+
75
+ MemorySegment namespaceSegment = arena .allocateUtf8String ("doc" ); // char*
76
+
77
+ for (File rule : rules ) {
78
+ try {
79
+ String ruleString = Files .readString (rule .toPath ());
80
+ MemorySegment ruleStringSegment = arena .allocateUtf8String (ruleString ); // char*
81
+
82
+ int compilationErrors = yr_compiler_add_string (compiler , ruleStringSegment , namespaceSegment );
83
+ Assertions .assertEquals (ZERO_ERRORS , compilationErrors );
84
+ } catch (IOException e ) {
85
+ throw new RuntimeException (e );
86
+ }
87
+ }
88
+
89
+ yr_compiler_destroy (compiler );
90
+ }
91
+ }
92
+
52
93
@ AfterAll
53
- public static void finish (){
54
- yr_finalize ();
94
+ public static void finish () {
95
+ int finalized = yr_finalize ();
96
+ Assertions .assertEquals (ERROR_SUCCESS (), finalized );
55
97
}
56
98
}
0 commit comments