-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFuzzTests.cpp
1248 lines (1025 loc) · 43.6 KB
/
FuzzTests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*=====================================================================
FuzzTests.cpp
-------------
Copyright Glare Technologies Limited 2019 -
=====================================================================*/
#include "wnt_TupleLiteral.h"
#include "VMState.h"
#include "VirtualMachine.h"
#include "wnt_ArrayLiteral.h"
#include "wnt_VectorLiteral.h"
#include "wnt_TupleLiteral.h"
#include "wnt_IfExpression.h"
#include "wnt_FunctionExpression.h"
#include "wnt_Lexer.h"
#include "wnt_LangParser.h"
#include "wnt_LetASTNode.h"
#include "wnt_LetBlock.h"
#include <maths/PCG32.h>
#include <utils/Timer.h>
#include <utils/Task.h>
#include <utils/TaskManager.h>
#include <utils/MemMappedFile.h>
#include <utils/FileUtils.h>
#include <utils/StringUtils.h>
#include <utils/PlatformUtils.h>
#include <utils/ConPrint.h>
#include <utils/IncludeXXHash.h>
#include <StandardPrintOutput.h>
#include <Mutex.h>
#include <Lock.h>
#include <Exception.h>
#include <Vector.h>
#include <unordered_set>
#include <fstream>
#if FUZZING_USE_OPENCL
#include <opencl/OpenCL.h>
#include <opencl/OpenCLBuffer.h>
#endif
#if BUILD_TESTS
namespace Winter
{
// Returns true if valid program, false otherwise.
bool testFuzzProgram(const std::string& src)
{
try
{
//TestEnv test_env;
//test_env.val = 10;
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
//vm_args.env = &test_env;
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Remove non-printable chars so console doesn't make bell sounds while printing.
//std::cout << ("\nCompiled OK:\n" + StringUtils::removeNonPrintableChars(src) + "\n");
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
float(WINTER_JIT_CALLING_CONV*f)(float, void*) = (float(WINTER_JIT_CALLING_CONV*)(float, void*))vm.getJittedFunction(mainsig);
// Check it has return type float
if(maindef->returnType()->getType() != Type::FloatType)
throw Winter::BaseException("main did not have return type float.");
// Call the JIT'd function
const float argument = 1.0f;
const float jitted_result = f(argument, NULL);//&test_env);
VMState vmstate;
vmstate.func_args_start.push_back(0);
vmstate.argument_stack.push_back(new FloatValue(argument));
//vmstate.argument_stack.push_back(new VoidPtrValue(&test_env));
ValueRef retval = maindef->invoke(vmstate);
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Float)
{
stdErrPrint("main() Return value was of unexpected type.");
assert(0);
exit(1);
}
FloatValue* val = static_cast<FloatValue*>(retval.getPointer());
if(isNAN(val->value) && isNAN(jitted_result))
{
conPrint("both values are NaN");
}
else if(val->value == jitted_result)
{
}
else
{
if(!epsEqual(val->value, jitted_result))
{
stdErrPrint("Test failed: main returned " + toString(val->value) + ", jitted_result was " + toString(jitted_result));
assert(0);
exit(1);
}
}
//============================= New: test with OpenCL ==============================
const bool TEST_OPENCL = true;
if(TEST_OPENCL)
{
#if FUZZING_USE_OPENCL
OpenCL* opencl = getGlobalOpenCL();
const int device_index = 0;
cl_context context;
cl_command_queue command_queue;
opencl->deviceInit(
opencl->getDeviceInfo()[device_index],
/*enable_profiling=*/false,
context,
command_queue
);
Winter::VirtualMachine::BuildOpenCLCodeArgs opencl_args;
std::string opencl_code = vm.buildOpenCLCodeCombined(opencl_args);
// OpenCL keeps complaining about 'main must return type int', so rename main to main_.
//opencl_code = StringUtils::replaceAll(opencl_code, "main", "main_"); // NOTE: slightly dodgy string-based renaming.
const std::string extended_source = opencl_code + "\n" + "__kernel void main_kernel(float x, __global float * const restrict output_buffer) { \n" +
" output_buffer[0] = main_float_(x); \n" +
" }";
std::cout << extended_source << std::endl;
OpenCLBuffer output_buffer(context, sizeof(float), CL_MEM_READ_WRITE);
std::string options = "-cl-opt-disable";//"-save-temps";
// Compile and build program.
cl_program program = opencl->buildProgram(
extended_source,
context,
opencl->getDeviceInfo()[device_index].opencl_device,
options
);
opencl->dumpBuildLog(program, opencl->getDeviceInfo()[device_index].opencl_device);
// Create kernel
cl_int result;
cl_kernel kernel = opencl->clCreateKernel(program, "main_kernel", &result);
if(!kernel)
throw glare::Exception("clCreateKernel failed");
if(opencl->clSetKernelArg(kernel, 0, sizeof(cl_float), &argument) != CL_SUCCESS) throw glare::Exception("clSetKernelArg failed 0");
if(opencl->clSetKernelArg(kernel, 1, sizeof(cl_mem), &output_buffer.getDevicePtr()) != CL_SUCCESS) throw glare::Exception("clSetKernelArg failed 1");
// Launch the kernel
const size_t block_size = 1;
const size_t global_work_size = 1;
result = opencl->clEnqueueNDRangeKernel(
command_queue,
kernel,
1, // dimension
NULL, // global_work_offset
&global_work_size, // global_work_size
&block_size, // local_work_size
0, // num_events_in_wait_list
NULL, // event_wait_list
NULL // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueNDRangeKernel failed: " + OpenCL::errorString(result));
SSE_ALIGN float host_output_buffer[1];
// Read back result
result = opencl->clEnqueueReadBuffer(
command_queue,
output_buffer.getDevicePtr(), // buffer
CL_TRUE, // blocking read
0, // offset
sizeof(float), // size in bytes
host_output_buffer, // host buffer pointer
0, // num events in wait list
NULL, // wait list
NULL //&readback_event // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueReadBuffer failed: " + OpenCL::errorString(result));
// Free the context and command queue for this device.
opencl->deviceFree(context, command_queue);
const float opencl_result = host_output_buffer[0];
if(!((opencl_result == jitted_result) || epsEqual(opencl_result, jitted_result))) // opencl_result == jitted_result handles Inf == Inf case.
{
std::cerr << "Test failed: OpenCL returned " << opencl_result << ", jitted_result was " << jitted_result << std::endl;
assert(0);
exit(1);
}
#endif // #if FUZZING_USE_OPENCL
}
}
catch(Winter::BaseException& e)
{
if(e.what() == "Module verification errors.")
{
stdErrPrint("Module verification errors while compiling " + src);
assert(0);
exit(1);
}
// Compile failure when fuzzing is alright.
//std::cerr << e.what() << std::endl;
return false;
}
catch(glare::Exception& )
{
//std::cerr << e.what() << std::endl;
return false;
}
return true;
}
// Returns true if valid program, false otherwise.
static bool testFuzzASTProgram(Reference<BufferRoot>& root)//const std::vector<FunctionDefinitionRef>& funcs)
{
try
{
VMConstructionArgs vm_args;
vm_args.comments_in_opencl_output = false;
for(size_t i=0; i<root->top_level_defs.size(); ++i)
if(root->top_level_defs[i]->nodeType() == ASTNode::FunctionDefinitionType)
vm_args.preconstructed_func_defs.push_back(root->top_level_defs[i].downcast<FunctionDefinition>());
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Remove non-printable chars so console doesn't make bell sounds while printing.
//std::cout << ("\nCompiled OK:\n" + StringUtils::removeNonPrintableChars(src) + "\n");
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
float(WINTER_JIT_CALLING_CONV*f)(float) = (float(WINTER_JIT_CALLING_CONV*)(float))vm.getJittedFunction(mainsig);
// Check it has return type float
if(maindef->returnType()->getType() != Type::FloatType)
throw Winter::BaseException("main did not have return type float.");
// Call the JIT'd function
const float argument = 1.0f;
const float jitted_result = f(argument);
VMState vmstate;
vmstate.func_args_start.push_back(0);
vmstate.argument_stack.push_back(new FloatValue(argument));
ValueRef retval = maindef->invoke(vmstate);
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Float)
{
stdErrPrint("main() Return value was of unexpected type.");
assert(0);
exit(1);
}
FloatValue* val = static_cast<FloatValue*>(retval.getPointer());
if(!((val->value == jitted_result) || epsEqual(val->value, jitted_result))) // val->value == jitted_result handles Inf == Inf case.
{
stdErrPrint("Test failed: main returned " + toString(val->value) + ", jitted_result was " + toString(jitted_result));
assert(0);
exit(1);
}
//============================= New: test with OpenCL ==============================
const bool TEST_OPENCL = false;
if(TEST_OPENCL)
{
#if FUZZING_USE_OPENCL
conPrint("Program was valid, testing in OpenCL.");
//std::cout << "testing opencl prog: " + src_string << std::endl;
OpenCL* opencl = getGlobalOpenCL();
cl_context context;
cl_command_queue command_queue;
opencl->deviceInit(
opencl->getDeviceInfo()[0],
/*enable_profiling=*/false,
context,
command_queue
);
Winter::VirtualMachine::BuildOpenCLCodeArgs opencl_args;
std::string opencl_code = vm.buildOpenCLCodeCombined(opencl_args);
// OpenCL keeps complaining about 'main must return type int', so rename main to main_.
//opencl_code = StringUtils::replaceAll(opencl_code, "main", "main_"); // NOTE: slightly dodgy string-based renaming.
const std::string extended_source = opencl_code + "\n" + "__kernel void main_kernel(float x, __global float * const restrict output_buffer) { \n" +
" output_buffer[0] = main_float_(x); \n" +
" }";
//std::cout << "---------------------\n" << extended_source << "\n-------------------" << std::endl;
OpenCLBuffer output_buffer(context, sizeof(float), CL_MEM_READ_WRITE);
std::string options = "";//"-save-temps";
StandardPrintOutput print_output;
// Compile and build program.
cl_program program = opencl->buildProgram(
extended_source,
context,
opencl->getDeviceInfo()[0].opencl_device,
options
);
//opencl->dumpBuildLog(program, opencl->getDeviceInfo()[0].opencl_device);
// Create kernel
cl_int result;
cl_kernel kernel = opencl->clCreateKernel(program, "main_kernel", &result);
if(!kernel)
throw glare::Exception("clCreateKernel failed");
if(opencl->clSetKernelArg(kernel, 0, sizeof(cl_float), &argument) != CL_SUCCESS) throw glare::Exception("clSetKernelArg failed 0");
if(opencl->clSetKernelArg(kernel, 1, sizeof(cl_mem), &output_buffer.getDevicePtr()) != CL_SUCCESS) throw glare::Exception("clSetKernelArg failed 1");
// Launch the kernel
const size_t block_size = 1;
const size_t global_work_size = 1;
result = opencl->clEnqueueNDRangeKernel(
command_queue,
kernel,
1, // dimension
NULL, // global_work_offset
&global_work_size, // global_work_size
&block_size, // local_work_size
0, // num_events_in_wait_list
NULL, // event_wait_list
NULL // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueNDRangeKernel failed: " + OpenCL::errorString(result));
SSE_ALIGN float host_output_buffer[1];
// Read back result
result = opencl->clEnqueueReadBuffer(
command_queue,
output_buffer.getDevicePtr(), // buffer
CL_TRUE, // blocking read
0, // offset
sizeof(float), // size in bytes
host_output_buffer, // host buffer pointer
0, // num events in wait list
NULL, // wait list
NULL //&readback_event // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueReadBuffer failed: " + OpenCL::errorString(result));
// Free the context and command queue for this device.
opencl->deviceFree(context, command_queue);
const float opencl_result = host_output_buffer[0];
if(!((opencl_result == jitted_result) || epsEqual(opencl_result, jitted_result))) // opencl_result == jitted_result handles Inf == Inf case.
{
std::cerr << "Test failed: OpenCL returned " << val->value << ", jitted_result was " << jitted_result << std::endl;
assert(0);
exit(1);
}
#endif // #if FUZZING_USE_OPENCL
}
}
catch(Winter::BaseException& e)
{
if(e.what() == "Module verification errors.")
{
stdErrPrint("Module verification errors while compiling AST program.");
assert(0);
exit(1);
}
// Compile failure when fuzzing is alright.
stdErrPrint(e.what());
return false;
}
catch(glare::Exception& )
{
//std::cerr << e.what() << std::endl;
return false;
}
return true;
}
// Fuzz testing choice
struct Choice
{
enum Action
{
Action_Break,
Action_Insert,
Action_InsertRandomChar,
Action_Copy,
Action_CopyFromOtherProgram,
Action_Remove,
Action_AddASTNode,
Action_AddStructConstructorCall
};
Choice() {}
Choice(Action action_, float probability_) : action(action_), probability(probability_) {}
Choice(Action action_, std::string left_, float probability_) : action(action_), probability(probability_), left(left_) {}
Choice(Action action_, std::string left_, std::string right_, float probability_) : action(action_), probability(probability_), left(left_), right(right_) {}
Choice(Action action_, ASTNode::ASTNodeType ast_node_type_, float probability_) : action(action_), probability(probability_), ast_node_type(ast_node_type_) {}
Action action;
float probability;
std::string left;
std::string right;
ASTNode::ASTNodeType ast_node_type;
};
static std::string readRandomProgramFromFuzzerInput(const std::vector<std::string>* fuzzer_input, PCG32& rng)
{
// Pick a random input line to get started
std::string start_string;
while(start_string.empty())
{
// Pick a line to start at
size_t linenum = rng.nextUInt((uint32)fuzzer_input->size());
// If we are in whitespace, pick another line.
if(::isAllWhitespace((*fuzzer_input)[linenum]))
continue;
// Go up until we are below a whitespace line
while(linenum >= 1 && !::isAllWhitespace((*fuzzer_input)[linenum - 1]))
linenum--;
start_string = (*fuzzer_input)[linenum]; // Get line
linenum++;
// While there are more lines below that aren't just whitespace, then the program continues, so append.
for(; linenum<fuzzer_input->size() && !::isAllWhitespace((*fuzzer_input)[linenum]); ++linenum)
start_string += " " + (*fuzzer_input)[linenum];
}
return start_string;
}
struct BuildRandomSubTreeArgs
{
bool allow_func_calls;
};
// Build random abstract-syntax sub-tree
static ASTNodeRef buildRandomASSubTree(BuildRandomSubTreeArgs& args, PCG32& rng, const std::vector<Choice>& choices, int depth)
{
const float r = rng.unitRandom();
if(depth > 3)
{
if(rng.unitRandom() < 0.3f)
return new Variable("x", SrcLocation::invalidLocation());
else
return new FloatLiteral(rng.unitRandom() < 0.25f ? 0.f : (int)(-10.f + rng.unitRandom() * 20.f), SrcLocation::invalidLocation());
//return new FloatLiteral(1.0f, SrcLocation::invalidLocation());
/*if(r < 0.33f)
return new FloatLiteral(1.0f, SrcLocation::invalidLocation());
else if(r < 0.66f)
return new IntLiteral(1, 32, SrcLocation::invalidLocation());
else
return new BoolLiteral(rng.unitRandom() < 0.5f, SrcLocation::invalidLocation());*/
}
float probability_sum = 0;
for(size_t z=0; z<choices.size(); ++z)
{
probability_sum += choices[z].probability;
if(r < probability_sum)
{
if(choices[z].action == Choice::Action_AddASTNode)
{
const ASTNode::ASTNodeType node_type = choices[z].ast_node_type;
switch(node_type)
{
case ASTNode::VariableASTNodeType:
return new Variable("x", SrcLocation::invalidLocation());
case ASTNode::FunctionExpressionType:
{
if(args.allow_func_calls)
return new FunctionExpression(SrcLocation::invalidLocation(), "f", buildRandomASSubTree(args, rng, choices, depth + 1));
else
return new FloatLiteral(1.f, SrcLocation::invalidLocation());
}
case ASTNode::FloatLiteralType:
{
return new FloatLiteral(rng.unitRandom() < 0.25f ? 0.f : (int)(-10.f + rng.unitRandom() * 20.f), SrcLocation::invalidLocation());
//return new FloatLiteral(2.0f, SrcLocation::invalidLocation());//rng.unitRandom() < 0.25f ? 0.f : (-10.f + rng.unitRandom() * 20.f), SrcLocation::invalidLocation());
}
case ASTNode::IntLiteralType:
return new IntLiteral(-2 + (int)(rng.unitRandom() * 4.0f), 32, /*is_signed=*/(rng.unitRandom() < 0.5f), SrcLocation::invalidLocation());
case ASTNode::BoolLiteralType:
return new BoolLiteral(rng.unitRandom() < 0.5f, SrcLocation::invalidLocation());
case ASTNode::ArrayLiteralType:
{
std::vector<ASTNodeRef> elems;
do
{
elems.push_back(buildRandomASSubTree(args, rng, choices, depth + 1));
}
while(rng.unitRandom() < 0.5f);
return new ArrayLiteral(elems, SrcLocation::invalidLocation(), false, 0);
}
case ASTNode::VectorLiteralType:
{
std::vector<ASTNodeRef> elems;
do
{
elems.push_back(buildRandomASSubTree(args, rng, choices, depth + 1));
}
while(rng.unitRandom() < 0.5f);
return new VectorLiteral(elems, SrcLocation::invalidLocation(), false, 0);
}
case ASTNode::TupleLiteralType:
{
std::vector<ASTNodeRef> elems;
do
{
elems.push_back(buildRandomASSubTree(args, rng, choices, depth + 1));
}
while(rng.unitRandom() < 0.5f);
return new TupleLiteral(elems, SrcLocation::invalidLocation());
}
case ASTNode::AdditionExpressionType:
return new AdditionExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::SubtractionExpressionType:
return new SubtractionExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::MulExpressionType:
return new MulExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::DivExpressionType:
return new DivExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::BinaryBooleanType:
return new BinaryBooleanExpr(rng.unitRandom() < 0.5f ? BinaryBooleanExpr::AND : BinaryBooleanExpr::OR, buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1), SrcLocation::invalidLocation());
case ASTNode::UnaryMinusExpressionType:
return new UnaryMinusExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::ComparisonExpressionType:
{
Reference<TokenBase> token;
const float q = rng.unitRandom();
if(q < 1.f/6)
token = new LEFT_ANGLE_BRACKET_Token(0);
else if(q < 2.f/6)
token = new RIGHT_ANGLE_BRACKET_Token(0);
else if(q < 3.f/6)
token = new DOUBLE_EQUALS_Token(0);
else if(q < 4.f/6)
token = new NOT_EQUALS_Token(0);
else if(q < 5.f/6)
token = new LESS_EQUAL_Token(0);
else
token = new GREATER_EQUAL_Token(0);
return new ComparisonExpression(token, buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1), SrcLocation::invalidLocation());
}
case ASTNode::ArraySubscriptType:
{
//return new ArrayS(token, buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1), SrcLocation::invalidLocation());
return new FunctionExpression(SrcLocation::invalidLocation(), "elem", buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
}
case ASTNode::IfExpressionType:
return new IfExpression(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1), buildRandomASSubTree(args, rng, choices, depth + 1));
case ASTNode::LogicalNegationExprType:
return new LogicalNegationExpr(SrcLocation::invalidLocation(), buildRandomASSubTree(args, rng, choices, depth + 1));
default:
assert(0);
return NULL;
}
}
else if(choices[z].action == Choice::Action_AddStructConstructorCall)
{
// returns some code like, for struct s { float x, float y }
/*
let
s_1 = s(EXPR, EXPR)
in
s_1.x
*/
//return new FunctionExpression(SrcLocation::invalidLocation(), "s", buildRandomASSubTree(rng, choices, depth + 1), buildRandomASSubTree(rng, choices, depth + 1));
/*ASTNodeRef constructor_call = new FunctionExpression(SrcLocation::invalidLocation(), "s", buildRandomASSubTree(rng, choices, depth + 1), buildRandomASSubTree(rng, choices, depth + 1));
ASTNodeRef member_access = new FunctionExpression(SrcLocation::invalidLocation(), "x", new Variable("s_1", SrcLocation::invalidLocation()));
Reference<LetASTNode> let_node = new LetASTNode(std::vector<LetNodeVar>(1, LetNodeVar("s_1")), constructor_call, SrcLocation::invalidLocation());
ASTNodeRef let_block = new LetBlock(
member_access, // expr
std::vector<Reference<LetASTNode> >(1, let_node), // lets
SrcLocation::invalidLocation()
);*/
/*
let
t = [EXPR, EXPR]t
in
elem(t, 0)
*/
const int tuple_size = 1 + (int)(rng.unitRandom() * 4.0);
std::vector<ASTNodeRef> tuple_elems;
for(int i=0; i<tuple_size; ++i)
tuple_elems.push_back(buildRandomASSubTree(args, rng, choices, depth + 1));
ASTNodeRef tuple_literal = new TupleLiteral(tuple_elems, SrcLocation::invalidLocation());
ASTNodeRef field_access = new FunctionExpression(SrcLocation::invalidLocation(), "elem",
new Variable("t", SrcLocation::invalidLocation()),
new IntLiteral(myClamp((int)(rng.unitRandom() * tuple_size), 0, tuple_size-1), 32, true, SrcLocation::invalidLocation()));
Reference<LetASTNode> let_node = new LetASTNode(std::vector<LetNodeVar>(1, LetNodeVar("t")), tuple_literal, SrcLocation::invalidLocation());
ASTNodeRef let_block = new LetBlock(
field_access, // expr
std::vector<Reference<LetASTNode> >(1, let_node), // lets
SrcLocation::invalidLocation()
);
return let_block;
}
}
}
return new FloatLiteral(1.0f, SrcLocation::invalidLocation());
}
class ASTFuzzTask : public glare::Task
{
public:
void run(size_t thread_index)
{
Timer timer;
Timer print_timer;
PCG32 rng(rng_seed);
std::ofstream outfile(fuzzer_output_dir + "/fuzz_thread_" + toString(thread_index) + ".txt");
// See comment in FuzzTask below about this number.
const int N = 134217728;
int num_valid_programs = 0;
for(int i=0; i<N; ++i)
{
// Pick a random program to get started
SourceBufferRef source_buffer;
FunctionDefinitionRef main_def;
Reference<BufferRoot> root;// = new BufferRoot(SrcLocation::invalidLocation());
if(true)
{
try
{
const std::string start_string = readRandomProgramFromFuzzerInput(fuzzer_input, rng);
source_buffer = new SourceBuffer("source", start_string);
std::vector<Reference<TokenBase> > tokens;
Lexer::process(source_buffer, tokens);
LangParser lang_parser(
false, // floating_point_literals_default_to_double
false // real_is_double
);
std::map<std::string, TypeVRef> named_types;
std::vector<TypeVRef> named_types_ordered;
int function_order_num = 0;
root = lang_parser.parseBuffer(tokens,
source_buffer,
rng.unitRandom() < 0.2, // check structure types
named_types,
named_types_ordered,
function_order_num
);
// Try and find function 'main'
for(size_t z=0; z<root->top_level_defs.size(); ++z)
{
if(root->top_level_defs[z]->nodeType() == ASTNode::FunctionDefinitionType)
{
if(root->top_level_defs[z].downcastToPtr<FunctionDefinition>()->sig.name == "main")
main_def = root->top_level_defs[z].downcast<FunctionDefinition>();
}
}
}
catch(BaseException& )
{
}
}
//TEMP
BuildRandomSubTreeArgs args;
args.allow_func_calls = false;
buildRandomASSubTree(args, rng, choices, 0);// body ast node
//Reference<BufferRoot> root = new BufferRoot(SrcLocation::invalidLocation());
/*{
BuildRandomSubTreeArgs args;
args.allow_func_calls = false;
// Define function 'f'
FunctionDefinitionRef def = new FunctionDefinition(SrcLocation::invalidLocation(), 0, "f",
std::vector<FunctionDefinition::FunctionArg>(1, FunctionDefinition::FunctionArg(new Float(), "x")),
buildRandomASSubTree(args, rng, choices, 0),// body ast node
new Float(), // declared ret type
NULL // built in func-impl
);
root->top_level_defs.push_back(def);
}
{
BuildRandomSubTreeArgs args;
args.allow_func_calls = true;
FunctionDefinitionRef def = new FunctionDefinition(SrcLocation::invalidLocation(), 1, "main",
std::vector<FunctionDefinition::FunctionArg>(1, FunctionDefinition::FunctionArg(new Float(), "x")),
buildRandomASSubTree(args, rng, choices, 0),// body ast node
new Float(), // declared ret type
NULL // built in func-impl
);
root->top_level_defs.push_back(def);
}*/
const std::string src = root.nonNull() ? root->sourceString(0) : "";
//conPrint("-------------------------------\n" + src + "\n-------------------------------");//TEMP
const uint64 src_hash = XXH64(src.data(), src.size(), 0);
bool already_tested;
size_t num_tested;
{
Lock lock(*tested_programs_mutex);
already_tested = tested_program_hashes->find(src_hash) != tested_program_hashes->end();
if(!already_tested)
tested_program_hashes->insert(src_hash);
num_tested = tested_program_hashes->size();
}
if(!already_tested)
{
// Write program source to disk, so if testFuzzProgram crashes we will have a record of the program.
//def->print(0, outfile);
outfile << src << std::endl;
//TEMP
//def->print(0, std::cout);
//std::cout << src << std::endl;
const bool valid_program = root.nonNull() ? testFuzzASTProgram(root) : false;
if(valid_program) num_valid_programs++;
}
if(print_timer.elapsed() > 2.0)
{
const double tests_per_sec = i / timer.elapsed();
conPrint(std::string("Iterations: ") + toString(i) + ", num_tested: " + toString(num_tested) + ", num valid: " + toString(num_valid_programs) + ", Test speed: " + doubleToStringNDecimalPlaces(tests_per_sec, 1) + " tests/s\n");
print_timer.reset();
}
}
}
int rng_seed;
std::vector<Choice> choices;
Mutex* tested_programs_mutex;
std::unordered_set<uint64>* tested_program_hashes;
std::vector<std::string>* fuzzer_input;
std::string fuzzer_output_dir;
};
class FuzzTask : public glare::Task
{
public:
void run(size_t thread_index)
{
Timer timer;
Timer print_timer;
PCG32 rng(rng_seed);
const std::string fuzz_output_path = fuzzer_output_dir + "/fuzz_thread_" + toString(thread_index) + ".txt"; // TEMP HACK HARD CODED PATH
std::ofstream outfile(fuzz_output_path);
// We want to N to be quite large, but not so large that the tested_program_hashes set uses up all our RAM.
// Lets say each of T threads generates N strings, and they happen to be disjoint.
// Then we have N * T * sizeof(uint64) direct item mem usage in tested_program_hashes.
// Lets say we want to use 4 GB for this with 4 threads.
// This gives N * 4 * 8 = 4 GB, so N = 134217728.
const int N = 134217728;
for(int i=0; i<N; ++i)
{
// Pick a random program to get started
const std::string start_string = readRandomProgramFromFuzzerInput(fuzzer_input, rng);
std::string s = start_string;
// Insert tokens
while(1)
{
const float r = rng.unitRandom();
float probability_sum = 0;
for(size_t z=0; z<choices.size(); ++z)
{
probability_sum += choices[z].probability;
if(r < probability_sum)
{
if(choices[z].action == Choice::Action_Break) // If this is the 'stop-appending tokens' token:
goto done;
else if(choices[z].action == Choice::Action_Insert)
{
// Insert choices[z].left randomly in the existing string
const size_t startpos = 0; // start_string.size();
const size_t insert_pos = myMin((size_t)(startpos + rng.unitRandom() * (s.size()-startpos)), s.size() - 1);
s.insert(insert_pos, choices[z].left);
// Insert choice right
if(!choices[z].right.empty() && rng.unitRandom() < 0.8f)
{
const size_t right_insert_pos = myMin((size_t)(startpos + rng.unitRandom() * (s.size()-startpos)), s.size() - 1);
s.insert(right_insert_pos, choices[z].right);
}
}
else if(choices[z].action == Choice::Action_InsertRandomChar)
{
const size_t insert_pos = myMin((size_t)(rng.unitRandom() * s.size()), s.size() - 1);
s.insert(insert_pos, 1, (char)(rng.unitRandom() * 128));
}
else if(choices[z].action == Choice::Action_Remove)
{
// Remove random chunk of string
if(!s.empty())
{
const size_t pos = myMin((size_t)(rng.unitRandom() * s.size()), s.size() - 1);
const size_t chunk_len = 1 + (size_t)(20.f * rng.unitRandom() * rng.unitRandom());
s.erase(pos, chunk_len);
}
}
else if(choices[z].action == Choice::Action_Copy)
{
// Copy random chunk of text and insert somewhere else in string.
if(!s.empty())
{
const size_t src_pos = myMin((size_t)(rng.unitRandom() * s.size()), s.size() - 1);
const size_t chunk_len = 1 + (size_t)(20.f * rng.unitRandom() * rng.unitRandom());
const std::string chunk = s.substr(src_pos, chunk_len);
const size_t insert_pos = myMin((size_t)(rng.unitRandom() * s.size()), s.size());
s.insert(insert_pos, chunk);
}
}
else if(choices[z].action == Choice::Action_CopyFromOtherProgram)
{
// Copy random chunk of text from some other program and insert somewhere in string.
const std::string src_string = readRandomProgramFromFuzzerInput(fuzzer_input, rng);
const size_t src_pos = myMin((size_t)(rng.unitRandom() * src_string.size()), src_string.size() - 1);
const size_t chunk_len = 1 + (size_t)(src_string.size() * 2 * rng.unitRandom() * rng.unitRandom());
const std::string chunk = src_string.substr(src_pos, chunk_len);
const size_t insert_pos = myMin((size_t)(rng.unitRandom() * s.size()), s.size());
s.insert(insert_pos, chunk);
}
break;
}
}
}
done:
//std::cout << "\n------------------------------------------------------\n" << s <<
// "\n------------------------------------------------------\n" << std::endl;
//s = "def main(float x) float : x + 1.0";
const uint64 src_hash = XXH64(s.data(), s.size(), 0);
bool already_tested;
size_t num_tested;
{
Lock lock(*tested_programs_mutex);
num_tested = tested_program_hashes->size();
already_tested = tested_program_hashes->find(src_hash) != tested_program_hashes->end();
if(!already_tested)
tested_program_hashes->insert(src_hash);
}
if(!already_tested)
{
// Write program source to disk, so if testFuzzProgram crashes we will have a record of the program.
outfile << "-------------------------------\n" << s << std::endl;
if(!outfile)
{
stdErrPrint("Writing to fuzz output failed!");
exit(1);
}
try
{
const int64 MAX_FUZZ_OUTPUT_FILE_SIZE = 20000000;
if(outfile.tellp() > MAX_FUZZ_OUTPUT_FILE_SIZE)
{
// Close, then re-open with truncation to clear the file.
outfile.close();
outfile.open(fuzz_output_path, std::ios_base::out | std::ios_base::trunc);
if(!outfile)
{
stdErrPrint("Failed to re-open fuzz output.");
exit(1);
}
}
}
catch(FileUtils::FileUtilsExcep& e)
{
stdErrPrint("FileUtilsExcep: " + e.what());
exit(1);
}
testFuzzProgram(s);
}
if(print_timer.elapsed() > 2.0)
{
const double tests_per_sec = i / timer.elapsed();
conPrint(std::string("Thread iters: ") + toString(i) + ", Total num tested: " + toString(num_tested) + ", Test speed: " + doubleToStringNDecimalPlaces(tests_per_sec, 1) + " tests/s\n");
print_timer.reset();
// Disabled PlatformUtils::getMemoryUsage() for now, since it requires linking to Psapi.lib, which is tricky to do with CMake and the SDK Lib.
/*conPrint("Working set size: " + getNiceByteSize(PlatformUtils::getMemoryUsage()));