forked from HexHive/FuzzGen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose.cpp
3045 lines (2290 loc) · 107 KB
/
compose.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
// ------------------------------------------------------------------------------------------------
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* ___ ___ ___ ___ ___ ___ ___
* /\__\ /\ \ /\__\ /\__\ /\__\ /\__\ /\ \
* /:/ _/_ \:\ \ /::| | /::| | /:/ _/_ /:/ _/_ \:\ \
* /:/ /\__\ \:\ \ /:/:| | /:/:| | /:/ /\ \ /:/ /\__\ \:\ \
* /:/ /:/ / ___ \:\ \ /:/|:| |__ /:/|:| |__ /:/ /::\ \ /:/ /:/ _/_ _____\:\ \
* /:/_/:/ / /\ \ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__\/\:\__\ /:/_/:/ /\__\ /::::::::\__\
* \:\/:/ / \:\ \ /:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ /:/ / \:\/:/ /:/ / \:\~~\~~\/__/
* \::/__/ \:\ /:/ / |:/:/ / |:/:/ / \:\ /:/ / \::/_/:/ / \:\ \
* \:\ \ \:\/:/ / |::/ / |::/ / \:\/:/ / \:\/:/ / \:\ \
* \:\__\ \::/ / |:/ / |:/ / \::/ / \::/ / \:\__\
* \/__/ \/__/ |/__/ |/__/ \/__/ \/__/ \/__/
*
* FuzzGen - Automatic Fuzzer Generation
*
*
*
* compose.cpp
*
* TODO: Write a small description.
*
*/
// ------------------------------------------------------------------------------------------------
#include "compose.h"
#include <unistd.h>
#include <errno.h>
using namespace std;
using namespace interwork;
/* calculate the number of bytes needed to hold a factorial */
#define NBYTES_FOR_FACTORIAL(n) ((((uint64_t)ceil( log2(FACTORIAL[n]) ) + 7) & (uint64_t)~7) >> 3)
/* The first 20 factorials (to avoid calculations) */
const uint64_t FACTORIAL[] = {
1, // 0!
1, // 1!
2, // 2!
6, // 3!
24, // 4!
120, // 5!
720, // 6!
5040, // 7!
40320, // 8!
362880, // 9!
3628800, // 10!
39916800, // 11!
479001600, // 12!
6227020800, // 13!
87178291200, // 14!
1307674368000, // 15!
20922789888000, // 16!
355687428096000, // 17!
6402373705728000, // 18!
121645100408832000, // 19!
2432902008176640000 // 20!
};
// ------------------------------------------------------------------------------------------------
// Code templates contain proper C++ code mixed with some special variables. Variables are in the
// form: $[var]$. There's a simple pattern matching engine that replaces these variables with the
// appropriate values, before template gets written to the file.
//
const string banner = R"(/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* ___ ___ ___ ___ ___ ___ ___
* /\__\ /\ \ /\__\ /\__\ /\__\ /\__\ /\ \
* /:/ _/_ \:\ \ /::| | /::| | /:/ _/_ /:/ _/_ \:\ \
* /:/ /\__\ \:\ \ /:/:| | /:/:| | /:/ /\ \ /:/ /\__\ \:\ \
* /:/ /:/ / ___ \:\ \ /:/|:| |__ /:/|:| |__ /:/ /::\ \ /:/ /:/ _/_ _____\:\ \
* /:/_/:/ / /\ \ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__\/\:\__\ /:/_/:/ /\__\ /::::::::\__\
* \:\/:/ / \:\ \ /:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ /:/ / \:\/:/ /:/ / \:\~~\~~\/__/
* \::/__/ \:\ /:/ / |:/:/ / |:/:/ / \:\ /:/ / \::/_/:/ / \:\ \
* \:\ \ \:\/:/ / |::/ / |::/ / \:\/:/ / \:\/:/ / \:\ \
* \:\__\ \::/ / |:/ / |:/ / \::/ / \::/ / \:\__\
* \/__/ \/__/ |/__/ |/__/ \/__/ \/__/ \/__/
*
* FuzzGen - Automatic Fuzzer Generation
* Version: $[ver]$
*
* Target Library: $[lib]$
* Build Options: $[opt1]$
* $[opt2]$
* $[opt3]$
*
* Issues: $[issue]$
*
* ~~~ THIS FILE HAS BEEN GENERATED AUTOMATICALLY BY *FUZZGEN* AT: $[date]$ ~~~
*
*/)";
// ------------------------------------------------------------------------------------------------
#ifndef USE_STRICT_C_PROTOYPE
const string headers = R"(#include <cstdint>
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <math.h>
/* headers for library includes */
$[incl]$
using namespace std;
)";
#else
const string headers = R"(#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
/* headers for library includes */
extern "C" {
$[incl]$}
)";
#endif
// ------------------------------------------------------------------------------------------------
const string globals = R"(/* calculate the number of bytes needed to hold a factorial */
#define NBYTES_FOR_FACTORIAL(n) ((((uint64_t)ceil( log2(FACTORIAL[n]) ) + 7) & (uint64_t)~7) >> 3)
/* The first 20 factorials (to avoid calculations) */
const uint64_t FACTORIAL[] = {
1, // 0!
1, // 1!
2, // 2!
6, // 3!
24, // 4!
120, // 5!
720, // 6!
5040, // 7!
40320, // 8!
362880, // 9!
3628800, // 10!
39916800, // 11!
479001600, // 12!
6227020800, // 13!
87178291200, // 14!
1307674368000, // 15!
20922789888000, // 16!
355687428096000, // 17!
6402373705728000, // 18!
121645100408832000, // 19!
2432902008176640000 // 20!
};
/* predefined sets */
$[pred]$
/* global variables */
uint8_t *perm;
$[glo]$
/* function declarations (used by function pointers), if any */
$[funcs]$
)";
// ------------------------------------------------------------------------------------------------
const string kperm = R"(//
// Find the k-th permutation (in lexicographic order) in a sequence of n numbers,
// without calculating the k-1 permutations first. This is done in O(n^2) time.
//
// Function returns an array[n] that contains the indices of the k-th permutation.
//
static uint8_t *kperm(uint8_t n, uint64_t k) {
uint64_t d = 0, factorial = FACTORIAL[n];
uint8_t c = 0, i, pool[32];
uint8_t *perm = new uint8_t[32];
/* Because we're using 64-bit numbers, the larger factorial that can fit in, is 20! */
assert( n <= 20 );
for (i=0; i<n; ++i) pool[i] = i; // initialize pool
k = (k % factorial) + 1; // to get the correct results, 1 <= k <= n!
factorial /= n; // start from (n-1)!
for (i=0; i<n-1; factorial/=(n-1 - i++)) { // for all (but last) elements
/* find d, r such that: k = d(n!) + r, subject to: d >= 0 and 0 < r <= n! */
/* (classic division doesn't work here, so we use iterative subtractions) */
for (d=0; k>(d+1)*factorial; ++d); // k < n! so loop runs in O(n)
k -= d * factorial; // calculate r
perm[c++] = pool[d];
for (uint8_t j=d; j<n-1; ++j) { // remove d-th element from pool
pool[j] = pool[j+1];
}
pool[n-1] = 0; // optional
}
perm[c++] = pool[0]; // last element is trivial
return perm;
})";
// ------------------------------------------------------------------------------------------------
const string eatdata = R"(//
// The interface for "eating" bytes from the random input.
//
// When a corpus is used and codec libraries are fuzzed, eating from the input needs special
// care. The beginning of the random input it's very likely to a valid frame or a buffer that
// can achieve a deep coverage. By using the first bytes for path selection and for variable
// fuzzing, we essentially destroy the frame.
//
// To fix this problem we split the input in two parts. When a buffer is being fuzzed, we eat
// bytes from the beginning of the input. Otherwise we eat from the end. Hence, we preserve the
// corpus and the frames that they may contain.
//
class EatData {
public:
/* class constructor (no need for destructor) */
EatData(const uint8_t *data, size_t size, size_t ninp) :
data(data), size(size), delimiter(size-1 > ninp ? size-1 - ninp : 0),
bwctr(size-1), fwctr(0) { }
/* eat (backwards) an integer between 1 and 8 bytes (for other input) */
uint64_t eatIntBw(uint8_t k) {
uint64_t num = 0;
assert(k > 0 && k < 9); // make sure that size is valid
if (bwctr - k < delimiter) { // ensure that there're enough data
)"
#ifdef USE_STRICT_C_PROTOYPE
R"(
printf("eatIntBw(): All input has been eaten. This is a FuzzGen bug!\n");
printf("size = %zu, delimiter = %zu, bwctr = %u, k = %u", size, delimiter, bwctr, k);
)"
#else
R"(
cout << "eatIntBw(): All input has been eaten. This is a FuzzGen bug!\n";
cout << "size = " << size << ", delimiter = " << delimiter
<< ", bwctr = " << bwctr << ", k = " << (int)k << "\n";
)"
#endif
R"(
exit(-1); // abort
}
for (uint8_t i=0; i<k; ++i) { // build the number (in big endian)
num |= (uint64_t)data[bwctr - i] << (i << 3);
}
bwctr -= k; // update counter
return num;
}
/* eat (forward) an integer between 1 and 8 bytes (for buffers) */
uint64_t eatIntFw(uint8_t k) {
uint64_t num = 0;
assert(k > 0 && k < 9); // make sure that size is valid
if (fwctr + k > delimiter) { // ensure that there're enough data
)"
#ifdef USE_STRICT_C_PROTOYPE
R"(
printf("eatIntFw(): All input has been eaten. This is a FuzzGen bug!\n");
printf("size = %zu, delimiter = %zu, fwctr = %u, k = %u", size, delimiter, fwctr, k);
)"
#else
R"(
cout << "eatIntFw(): All input has been eaten. This is a FuzzGen bug!\n";
cout << "size = " << size << ", delimiter = " << delimiter
<< ", fwctr = " << fwctr << ", k = " << (int)k << "\n";
)"
#endif
R"(
exit(-1); // abort
}
for (uint8_t i=0; i<k; ++i) { // build the number (in big endian)
num |= (uint64_t)data[fwctr + i] << (i << 3);
}
fwctr += k; // update counter
return num;
}
/* abbervations for common sizes */
inline uint8_t eat1() { return (uint8_t) eatIntBw(1); }
inline uint16_t eat2() { return (uint16_t)eatIntBw(2); }
inline uint32_t eat4() { return (uint32_t)eatIntBw(4); }
inline uint64_t eat8() { return eatIntBw(8); }
/* abbervations for common sizes */
inline uint8_t buf_eat1() { return (uint8_t) eatIntFw(1); }
inline uint16_t buf_eat2() { return (uint16_t)eatIntFw(2); }
inline uint32_t buf_eat4() { return (uint32_t)eatIntFw(4); }
inline uint64_t buf_eat8() { return eatIntFw(8); }
/* eat a buffer of arbitrary size (DEPRECATED) */
inline const uint8_t *eatBuf(uint32_t k) {
const uint8_t *buf = &data[bwctr];
if (bwctr - k < delimiter) { // ensure that there're enough data
)"
#ifdef USE_STRICT_C_PROTOYPE
R"(
printf("eatBuf(): All input has been eaten. This is a FuzzGen bug!\n");
)"
#else
R"(
cout << "eatBuf(): All input has been eaten. This is a FuzzGen bug!\n";
)"
#endif
R"(
exit(-1); // abort
}
bwctr -= k; // update counter
return buf;
}
private:
const uint8_t *data; // random data
size_t size; // and its size
size_t delimiter; // delimiter (between buffer and other data)
uint32_t bwctr, fwctr; // backward and forward counters
};)";
// ------------------------------------------------------------------------------------------------
const string mainDecl = R"(//
// LibFuzzer's initialization routine.
//
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
(void) argc;
(void) argv;
)"
#ifdef USE_STRICT_C_PROTOYPE
R"(
printf("[*] This fuzzer has been created by *FuzzGen*\n");
)"
#else
R"(
cout << "[*] This fuzzer has been created by *FuzzGen*\n";
)"
#endif
R"(
return 0;
}
// ------------------------------------------------------------------------------------------------
//
// LibFuzzer's main processing routine.
//
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* min size needed for Eat() to work properly */
if (size < $[min_total]$ || size > $[max_total]$) return 0;
/* all variables contain 3 random letters, so E cannot redefined */
EatData E(data, size, ninp);
buflen = (size - ninp) / nbufs - 1; // find length of each buffer
$[body]$
return 0;
})";
// ------------------------------------------------------------------------------------------------
// We comment out the brackets to prevent UAF, as local variables may define dependencies that
// are used in subsequent pools.
//
const string singlePool = R"(/* * * function pool #$[id]$ * * */
//{
$[func]$
//}
)";
// ------------------------------------------------------------------------------------------------
const string multiPool = R"(/* * * function pool #$[id]$ * * */
//{
/* don't mess with bits. Keep it simple ;) */
perm = kperm($[n]$, E.eatIntBw( NBYTES_FOR_FACTORIAL($[n]$) ));
$[decl]$
for (int i=0; i<$[n]$; ++i) {
if (0) { } /* this dummy statement is used to avoid corner cases */
$[func]$
}
//}
)";
// ------------------------------------------------------------------------------------------------
const string multiPoolCall = R"(
else if (perm[i] == $[i]$) {
$[call]$
}
)";
// ------------------------------------------------------------------------------------------------
const string makeFile = R"(#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# ~~~ THIS MAKEFILE HAS BEEN GENERATED AUTOMATICALLY BY *FUZZGEN* AT: $[date]$ ~~~
#
#
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_CERTIFICATE := platform
LOCAL_C_INCLUDES += bionic/libc/include $[incl]$
LOCAL_SRC_FILES := $[fuzzsrc]$
LOCAL_CFLAGS += -Wno-multichar -g -Wno-error
LOCAL_MODULE_TAGS := optional
LOCAL_CLANG := true
LOCAL_MODULE := $[libname]$_fuzzer_$[model]$
LOCAL_SHARED_LIBRARIES := libutils $[libshr]$
LOCAL_STATIC_LIBRARIES += liblog $[libstc]$
include $(BUILD_FUZZ_TEST)
################################################################################
)";
// ------------------------------------------------------------------------------------------------
const string gloMakefile = R"(#
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# ~~~ THIS MAKEFILE HAS BEEN GENERATED AUTOMATICALLY BY *FUZZGEN* AT: $[date]$ ~~~
#
#
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
# decoder
include $[makefiles]$
)";
// ------------------------------------------------------------------------------------------------
// Simply initialize class members.
//
Composer::Composer(string currDir, Context *ctx) : ctx(ctx), currDir(currDir), header(ctx->header),
global(ctx->global), inclDep(ctx->inclDep), tDef(ctx->tDef), ctr(0), minEat(0), maxEat(0),
lastEat(0), maxlastEat(0) {
if (ctx->seed) {
srand(ctx->seed); // initialize with a given seed
} else {
srand(time(NULL)); // initialize with random seed
}
/* a pool can have up to 20 functions (21! needs >64 bits) */
if (MAX_FUNCS_PER_POOL > 20) {
throw FuzzGenException("Composer(): A pool can have up to 20 functions");
}
}
// ------------------------------------------------------------------------------------------------
// Create a new function pool.
//
uint16_t Composer::mkpool() {
list <APICall*> pl; // declare an empty
pool.push_back(pl); // extend pool by 1 element
return ctr++; // ctr is consistent with pool.size()
}
// ------------------------------------------------------------------------------------------------
// Push a function to an existing pool.
//
bool Composer::push(uint16_t poolID, APICall *call) {
/* check if index is valid first */
if (poolID < 0 || poolID >= pool.size()) {
return false; // failure x(
}
pool[poolID].push_back(call); // push function
return true;
}
// ------------------------------------------------------------------------------------------------
// Get pool's size.
//
size_t Composer::size(uint16_t poolID) {
return pool[poolID].size();
}
// ------------------------------------------------------------------------------------------------
// Base function for substitution. This is actually the identity function.
//
string Composer::substitute(string templ) {
return templ;
}
// ------------------------------------------------------------------------------------------------
// Substitute an arbitrary number of variables from a template. This function uses variadic
// templates to recursively substitute one variable at a time.
//
template<typename T, typename ... couple>
string Composer::substitute(string templ, T var, couple... replacement) {
string tmp(templ); // make a hard copy
string a = var.first;
string b = var.second;
/* regex doesn't work properly in C++11, so we use an alternative */
for(size_t idx=0; (idx = tmp.find(var.first, idx)) != string::npos;
idx += max(a.length(), b.length())) {
tmp.replace(idx, a.length(), var.second);
}
/* recursively move on the next variable substitution */
return substitute(tmp, replacement...);
}
// ------------------------------------------------------------------------------------------------
// Cast an interwork basic type to a C++ type.
//
string Composer::toCppTy(Argument *arg) {
switch(arg->baseType) {
case Ty_void: return "void";
/* NOTE: 'singed char' and 'char' are different! Use 'char' instead of 'int8_t' */
case Ty_i8: return arg->isSigned ? "char" : "uint8_t";
case Ty_i16: return arg->isSigned ? "int16_t" : "uint16_t";
case Ty_i32: return arg->isSigned ? "int32_t" : "uint32_t";
case Ty_i64: return arg->isSigned ? "int64_t" : "uint64_t";
case Ty_float: return "float";
case Ty_double: return "double";
case Ty_struct: {
/* before you declare a struct make sure that the right #include is present */
string name = substitute(arg->structName, P("struct.", ""));
/* find struct's header */
if (global.find(name) != global.end()) {
includes.insert(global[name]);
} else {
ctx->reportIssue("Cannot find header file for struct '" + name + "'." +
" Function is discarded.");
// throw FuzzGenStructException("toCppTy(): Cannot find struct's declaration."
// " Much sad. Discarding current function");
}
/* if struct declared as "typedef" omit the "struct" keyword */
if (tDef.find(name) != tDef.end()) {
return name;
}
return "struct " + name;
}
case Ty_funcptr: return ptrTy;
}
fatal() << "Type with ID:" << arg->baseType << " is not implemented.\n";
return "__NOT_IMPLEMENTED__";
}
// ------------------------------------------------------------------------------------------------
// Create a string of n stars.
//
inline string Composer::star(unsigned n) {
string star;
for (unsigned i=0; i<n; ++i, star+="*")
{ }
return star;
}
// ------------------------------------------------------------------------------------------------
// Subscript an argument with an index.
//
inline string Composer::makeName(Argument *arg, unsigned subIdx) {
return arg->name + "_" + to_string(subIdx);
}
// ------------------------------------------------------------------------------------------------
// Subscript a name with an index.
//
inline string Composer::makeName(string name, unsigned subIdx) {
return name + "_" + to_string(subIdx);
}
// ------------------------------------------------------------------------------------------------
// Cast a dependence ID into a pretty string
//
inline string Composer::prettyDep(unsigned depID, string prefix="dep_") {
return prefix + to_string(depID >> 16) + // use offsets only if it's != 0
(depID & 0xffff ? "_" + to_string(depID & 0xffff) : "");
}
// ------------------------------------------------------------------------------------------------
// Adjust a dependency type. The type of a dependency should match with the type of the argument/
// element that is being used. However it is possible to have a mismatch between the type of the
// definition and the type of the usage. For example:
//
// Dependence Defined: int *dep_1; foo(dep_1); // foo(int *);
// Dependence Used: bar(*dep_1); // bar(int);
//
// Here, dependency is defined as a pointer, but it is used as an integer. This function detects
// such cases and adjusts the dependence type accordingly.
//
bool Composer::adjustDependency(Argument *arg) {
if (arg->depTy != Dep_use) { // base check
return false; // no adjustment made
}
if (depArg.find(arg->depID) == depArg.end()) { // this should never happen
return false;
throw FuzzGenException("adjustDependency(): Dependency used without defined");
}
info(v3) << "Adjusting dependence ...\n";
Argument *argDef = depArg[arg->depID];
/* mismatch #1: off by 1 pointer. Use dereference */
if (argDef->nptr[0] == arg->nptr[0] + 1 && arg->prefix == Pref_none) {
info(v3) << "argDef: " << argDef->dump() << "\n";
info(v3) << "arg : " << argDef->dump() << "\n";
arg->prefix = Pref_deref;
return true;
}
/* mismatch #2: off by 1 pointer (reverse direction). Use ampersand */
else if (argDef->nptr[0] == arg->nptr[0] - 1 && arg->prefix == Pref_none) {
info(v3) << "argDef: " << argDef->dump() << "\n";
info(v3) << "arg : " << argDef->dump() << "\n";
arg->prefix = Pref_amp;
return true;
}
/* mismatch #3: off by 1 dereference (reverse direction). Drop prefix */
else if (argDef->nptr[0] == arg->nptr[0] - 1 && arg->prefix == Pref_deref) {
info(v3) << "argDef: " << argDef->dump() << "\n";
info(v3) << "arg : " << argDef->dump() << "\n";
arg->prefix = Pref_none;
return true;
}
/* TODO: Consider more cases as you go */
return false;
}
// ------------------------------------------------------------------------------------------------
// Generate n array indices for iterations, starting from iterFrom. Example:
// iterIndices(3, 3) = "[i_3][i_4][i_5]"
//
inline string Composer::iterIndices(unsigned iterFrom, unsigned len) {
string indices;
for (unsigned i=0; i<len; indices+="[i_" + to_string(iterFrom + i++) + "]")
{ }
return indices;
}
// ------------------------------------------------------------------------------------------------
// Generate n array indices starting from iter. However, this time use a single iterator.
// Example:
// iterIndices(0, [77,88,99]) = "[i_0/(1*88*99) % 77][i_0/(1*99) % 88][i_0/(1) % 99]"
//
inline string Composer::iterIndices(unsigned iter, vector<size_t> sizes) {
string indices, div;
/* optimize the special case for 1D arrays */
if (sizes.size() == 1) {
return "[i_" + to_string(iter) + "]";
}
for (unsigned i=0; i<sizes.size(); ++i) {
/* generate divisors first */
div = "/(1";
for (unsigned j=i+1; j<sizes.size(); ++j) {
div += "*" + to_string(sizes[j]);
}
/* then indices */
indices += "[i_" + to_string(iter) + div + ") % " + to_string(sizes[i]) + "]";
}
return indices;
}
// ------------------------------------------------------------------------------------------------
// Generate n array indices for array declarations. Each index has a constant size.
//
inline string Composer::declIndices(unsigned val, unsigned len) {
string indices;
for (unsigned i=0; i<len; ++i, indices+="[" + to_string(val) + "]")
{ }
return indices;
}
// ------------------------------------------------------------------------------------------------
// Generate n array indices for array declarations. Each index has a predefined size.
//
inline string Composer::declIndices(const vector<size_t> sizes) {
string indices;
for (unsigned i=0; i<sizes.size(); indices+="[" + to_string(sizes[i++]) + "]")
{ }
return indices;
}
// ------------------------------------------------------------------------------------------------
// Generate n nested for loops starting from iterator iterFrom. Each loop goes up to upper.
//
string Composer::makeForLoops(unsigned iterFrom, unsigned n, string upper, string body) {
string loops, iter;
/* create n nested for statements with the right indentation */
for (unsigned i=0; i<n; ++i) {
iter = "i_" + to_string(iterFrom + i);
loops += tab("for (uint64_t " + iter + "=0; " + iter + "<" + upper +
"; ++" + iter + ") {\n", i);
}
/* to keep minEat consistent in nested makeForLoops(), we keep updating lastEat */
if (lastEat & 0x80000000) { // lastEat set for 1st time?
lastEat &= 0x7fffffff; // clear MSBit
minEat -= lastEat; // cancel increment that makeVal() did
maxEat -= maxlastEat;
}
/* multiply eat value by loop count */
try {
lastEat *= stoul(upper) * n;
maxlastEat *= stoul(upper) * n;
} catch (const invalid_argument& invArg) {
lastEat *= ctx->minbuflen * n; // upper is a variable. Use min buflen instead
maxlastEat *= ctx->maxbuflen * n; // the different with lastEat: find upper bound
}
/* it's much simpler if we use 2 variables (minEat, maxEat) for upper and lower bounds */
minEat += lastEat; // minEat is aware of the loop now
maxEat += maxlastEat; // maxEat as well
/* write loop's body at the n'th indentation */
loops += tab(body, n);
/* close open curly brackets */
for (int i=n-1; i>=0; --i) { // use "int" because we need i to be <0
loops += tab("}\n", i);
}
return loops;
}
// ------------------------------------------------------------------------------------------------
// Generate n nested for loops starting from iterator iterFrom. This time upper is a vector, so
// each loop has a different upper bound.
//
string Composer::makeForLoops(unsigned iterFrom, vector<size_t> upper, string body) {
string loops, iter;
size_t n = upper.size(); // get vector size
size_t totalIter = 1;
/* create n nested for statements with the right indentation */
for (unsigned i=0; i<n; totalIter*=upper[i++]) {
iter = "i_" + to_string(iterFrom + i);
loops += tab("for (uint64_t " + iter + "=0; " + iter + "<" + to_string(upper[i]) +
"; ++" + iter + ") {\n", i);
}
/* to keep minEat consistent in nested makeForLoops(), we keep updating lastEat */
if (lastEat & 0x80000000) { // lastEat set for 1st time?
lastEat &= 0x7fffffff; // clear MSBit
minEat -= lastEat; // cancel increment that makeVal() did
maxEat -= maxlastEat;
}
/* multiply eat value by loop count */
lastEat *= totalIter;
minEat += lastEat; // minEat is aware of the loop now
maxlastEat *= totalIter;
maxEat += maxlastEat; // maxEat as well
/* write loop's body at the n'th indentation */
loops += tab(body, n);
/* close open curly brackets */
for (int i=n-1; i>=0; --i) { // use "int" because we need i to be <0
loops += tab("}\n", i);
}
return loops;
}
// ------------------------------------------------------------------------------------------------
// Create an assignment statement, that creates a value for an argument and then assigns this
// value to name.
//
string Composer::makeAssign(string name, Argument *arg, unsigned deep=0) {
if (arg->baseType == Ty_struct) {
/* structs can't be assigned directly. Element must be assigned instead */
remark(v2) << "makeAssign() creates a struct!\n";
/* if struct is initialized from another dependency, make the assignment first */
if (depInit) {
return name + " = (" + toCppTy(arg) + star(arg->nptr[0]) + ")" +
prettyDep(arg->depIDInit) + ";\n\n" + makeStruct(arg, deep, name);
}
/* the recursion here can be arbitrary deep here */
return name + ";\n\n" + makeStruct(arg, deep, name);
}
return name + " = " + makeVal(arg) + ";\n";
}
// ------------------------------------------------------------------------------------------------
// Create an assignment statement, to initialize a field in a struct. Because we don't know the
// element name, assignment is done in the assembly style. For example:
// *(uint8_t*) ((uint64_t)&foo + 16) = 1;
//
string Composer::makeAssign(Element *elt, unsigned displacement, string ampersand,
string value, string name) {
string assign, pointer, type;