forked from jackwadden/VASim
/
main.cpp
635 lines (505 loc) · 18.7 KB
/
main.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
#include "automata.h"
#include "pass.h"
#include "profiler.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "getopt.h"
#include <chrono>
#include <ctime>
#include <thread>
#include "errno.h"
#define FROM_INPUT_STRING false
using namespace std;
void usage(char * argv) {
printf("USAGE: %s [OPTIONS] <automata anml> <input file/string> \n", argv);
printf(" -i, --input Input chars are taken from command line\n");
printf(" -s, --step Useful if debugging; simulation advances one cycle per when a key is pressed\n");
printf(" -r, --report Print reports to stdout\n");
printf(" -b, --batchsim Output report mimics format of batchsim\n");
printf(" -q, --quiet Suppress all non-debugging output\n");
printf(" -p, --profile Profiles automata, storing activation and enable histograms in .out files.\n");
printf(" -c, --charset Compute charset complexity of automata.\n");
printf(" -d, --dot Output automata as dot file. Builds a heat map if profiling is turned on\n");
printf(" -a, --anml Output automata as anml file. Useful for storing graphs after long running optimizations.\n");
printf(" -n, --nfa Output automata as nfa readable by Michela Becchi's tools.\n");
printf(" -f, --hdl Output automata as one-hot encoded verilog HDL for execution on an FPGA.\n");
printf(" -R, --regex Convert automata to regular expressions.\n");
printf(" -t, --time Time simulation.\n");
printf("\nOPTIMIZATIONS:\n");
printf(" -O, --left-min-before Enable left minimization before connected component search.\n");
printf(" -L, --left-min-after Enable left minimization after within connected components.\n");
printf(" -l, --level Specify max level for left minimization.\n");
printf(" -x, --remove-ors Remove or gates that report and have no children.\n");
printf("\nMULTITHREADING:\n");
printf(" -T, --threads Specify number of threads to compute connected components of automata.\n");
printf(" -P, --packets Specify number of threads to compute input stream. NOT SAFE. TODO: allow for overlap.\n");
printf(" -h, --help Print this help and exit\n");
printf("\n");
}
uint32_t fileSize(string fn) {
// open the file:
std::ifstream file(fn, ios::binary);
// Stop eating new lines in binary mode!!!
file.unsetf(std::ios::skipws);
// get its size:
std::streampos fileSize;
file.seekg(0, ios::end);
fileSize = file.tellg();
file.seekg(0, ios::beg);
return fileSize;
}
void inputFileCheck() {
if(errno == ENOENT) {
cout<< "VAsim Error: no such input file." << endl;
exit(-1);
}
}
vector<unsigned char> file2CharVector(string fn) {
// open the file:
std::ifstream file(fn, ios::binary);
if(file.fail()){
inputFileCheck();
}
// get its size:
std::streampos fileSize;
file.seekg(0, ios::end);
fileSize = file.tellg();
file.seekg(0, ios::beg);
// Stop eating new lines in binary mode!!!
file.unsetf(std::ios::skipws);
// reserve capacity
std::vector<unsigned char> vec;
vec.reserve(fileSize);
// read the data:
vec.insert(vec.begin(),
std::istream_iterator<unsigned char>(file),
std::istream_iterator<unsigned char>());
return vec;
}
/*
*
*/
void simulateAutomaton(Automata *a, uint8_t *input, uint32_t start_index, uint32_t size, bool step) {
a->simulate(input, start_index, size, step);
}
/*
* Returns the input stream byte array, stores length in size pointer input
*/
uint8_t * parseInputStream(bool simulate, bool input_string, uint32_t *size, char ** argv, uint32_t optind) {
uint8_t * input;
if(simulate){
// From command line
if(input_string){
string input2 = argv[optind];
*size = (uint32_t)input2.length();
uint32_t counter = 0;
input = (uint8_t*)malloc(sizeof(uint8_t) * *size);
// copy bytes to unsigned ints
for(unsigned char val : input2){
input[counter] = (uint8_t)val;
counter++;
}
// From file
} else {
string input_fn = argv[optind];
vector<unsigned char> input2 = file2CharVector(input_fn);
*size = input2.size();
input = (uint8_t*)malloc(sizeof(uint8_t) * input2.size());
// copy bytes to unsigned ints
uint32_t counter = 0;
for(uint8_t val : input2){
input[counter] = (uint8_t)val;
counter++;
}
}
}
return input;
}
/*
*
*/
int main(int argc, char * argv[]) {
bool input_string = false;
bool step = false;
bool quiet = false;
bool batchsim = false;
bool report = false;
bool profile = false;
bool charset_complexity = false;
bool to_dot = false;
bool to_anml = false;
bool time = false;
bool optimize = false;
bool optimize_after = false;
bool remove_ors = false;
bool to_nfa = false;
bool to_hdl = false;
bool to_regex = false;
uint32_t max_level = 10000; // artificial (and arbitrary) max depth of attempted left-minimization
uint32_t num_threads = 1;
uint32_t num_threads_packets = 1;
int c;
const char * short_opt = "thsqrbnfcdaRxipOLl:T:P:";
struct option long_opt[] = {
{"help", no_argument, NULL, 'h'},
{"step", no_argument, NULL, 's'},
{"quiet", no_argument, NULL, 'q'},
{"report", no_argument, NULL, 'r'},
{"batchsim", no_argument, NULL, 'b'},
{"input", no_argument, NULL, 'i'},
{"dot", no_argument, NULL, 'd'},
{"anml", no_argument, NULL, 'a'},
{"nfa", no_argument, NULL, 'n'},
{"hdl", no_argument, NULL, 'f'},
{"regex", no_argument, NULL, 'R'},
{"profile", no_argument, NULL, 'p'},
{"charset", no_argument, NULL, 'c'},
{"time", no_argument, NULL, 't'},
{"left-min-before", no_argument, NULL, 'O'},
{"left-min-after", no_argument, NULL, 'L'},
{"remove-ors", no_argument, NULL, 'x'},
{"level", required_argument, NULL, 'l'},
{"threadd-width", required_argument, NULL, 'T'},
{"thread-height", required_argument, NULL, 'P'},
{NULL, 0, NULL, 0 }
};
while((c = getopt_long(argc, argv, short_opt, long_opt, NULL)) != -1) {
switch(c) {
case -1: /* no more arguments */
case 0: /* long options toggles */
break;
case 'i':
input_string = true;
break;
case 'q':
quiet = true;
break;
case 's':
step = true;
break;
case 'r':
report = true;
break;
case 'b':
report = true;
batchsim = true;
break;
case 'p':
profile = true;
break;
case 'd':
to_dot = true;
break;
case 'a':
to_anml = true;
break;
case 'R':
to_regex = true;
break;
case 't':
time = true;
break;
case 'c':
charset_complexity = true;
break;
case 'O':
optimize = true;
break;
case 'L':
optimize_after = true;
break;
case 'x':
remove_ors = true;
break;
case 'l':
max_level = atoi(optarg);
break;
case 'T':
num_threads = atoi(optarg);
break;
case 'P':
num_threads_packets = atoi(optarg);
break;
case 'n':
to_nfa = true;
break;
case 'f':
to_hdl = true;
break;
case 'h':
usage(argv[0]);
return(0);
case ':':
case '?':
fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
return(-2);
default:
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
usage(argv[0]);
return(-2);
};
};
if(optind >= argc) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
// Parse command line args
string fn(argv[optind++]);
uint8_t *input;
uint32_t size;
bool simulate = true;
if(optind >= argc) {
simulate = false;
}
// Parse automata input file or input from command line
input = parseInputStream(simulate, input_string, &size, argv, optind);
// Build automata
if(!quiet){
cout << "|------------------------|" << endl;
cout << "| Parsing |" << endl;
cout << "|------------------------|" << endl;
cout << "Building automata from file: " << fn << endl;
}
//
Automata ap(fn);
uint32_t automata_size = ap.getElements().size();
uint32_t orig_automata_size = ap.getElements().size();
if(!quiet){
ap.printGraphStats();
}
if(quiet)
ap.enableQuiet();
// Remove special elements that have no functional benefit
// E.g. this removes or gates at the end of trees
if(remove_ors) {
if(!quiet)
cout << "Removing OR gates..." << endl;
ap.removeOrGates();
//if(!quiet)
// cout << "Removing counters..." << endl;
//ap.removeCounters();
if(!quiet)
cout << endl;
}
// Optimize automata before identifying connected components
// Start optimizations
if(optimize) {
if(!quiet){
cout << "|------------------------|" << endl;
cout << "| Optimization |" << endl;
cout << "|------------------------|" << endl;
cout << "Starting Optimizations..." << endl;
}
// Global automata optimizations
ap.leftMinimize(max_level);
// ******
// ADD OTHER OPTIMIZATIONS
// ******
}
// Partition automata into connected components
if(!quiet)
cout << "Finding distinct subgraphs..." << endl;
vector<Automata*> ccs;
ccs = ap.splitConnectedComponents();
if(!quiet)
cout << endl;
// Combine connected components into N automata
if(!quiet)
cout << "Combining " << ccs.size() << " distinct subgraphs into " << num_threads << " graphs..." << endl;
unsigned int counter = 0;
vector<Automata*> merged(num_threads);
for(Automata *a : ccs) {
if(merged[counter % num_threads] == NULL){
merged[counter % num_threads] = ccs[counter];
}else{
merged[counter % num_threads]->unsafeMerge(a);
if(quiet)
merged[counter % num_threads]->enableQuiet();
}
counter++;
}
if(!quiet)
cout << endl;
// Preprocess all automata partitions
// Set up multi-dimensional structure for parallelization
Automata *automata[num_threads][num_threads_packets];
counter = 0;
for(Automata *a : merged) {
// Optimize after connected component merging
if(optimize_after) {
if(!quiet)
cout << "Starting post merge optimizations..." << endl;
// Left minimization
automata_size = a->getElements().size();
a->leftMinimize(max_level);
while(automata_size != a->getElements().size()){
automata_size = a->getElements().size();
a->leftMinimize(max_level);
}
// ******
// ADD OTHER OPTIMIZATIONS
// ******
if(!quiet)
cout << endl;
}
// Save automata anml if desired
if(to_anml) {
a->automataToANMLFile("automata_" + to_string(counter) + ".anml");
}
// Print regex for each automata partition
if(to_regex) {
if(!quiet)
cout << "Converting automata to regular expression rule set..." << endl;
a->automataToRegex("automata_"+ to_string(counter) + ".regex");
}
// Print NFA
if(to_nfa){
a->automataToNFAFile("automata_" + to_string(counter) + ".nfa");
}
// Emit as HDL
if(to_hdl) {
a->automataToHDLFile("automata_" + to_string(counter) + ".v");
}
// Save each parallel automata and replicate for multiple streams
// *** TODO: this is a lazy way of avoiding writing a copy constructor
const char * tmp_fn = "temp_vasim_unique_temp_file_name.anml";
a->automataToANMLFile(tmp_fn);
// Insert automata into correct index for multiple input streams
automata[counter][0] = a;
for (int packet = 1; packet < num_threads_packets; ++packet) {
automata[counter][packet] = new Automata(tmp_fn);
}
// Delete temp file
remove(tmp_fn);
// Print final stats
a->printGraphStats();
counter++;
}
//
if(!quiet){
if(num_threads == 1){
// Compressability
cout << "Compressability: " << 1.0 - ((double)automata[0][0]->getElements().size()/(double)orig_automata_size) << endl;
// STE complexity
if(charset_complexity)
automata[0][0]->printSTEComplexity();
}
}
// Simulate all automata
if(simulate){
if(!quiet){
cout << "|------------------------|" << endl;
cout << "| Simulation |" << endl;
cout << "|------------------------|" << endl;
cout << "Starting simulation using " << num_threads << "x" << num_threads_packets << "=" << num_threads*num_threads_packets << " thread(s)..." << endl;
}
thread threads[num_threads][num_threads_packets];
// Start timer
chrono::high_resolution_clock::time_point start_time;
if(time) {
start_time = chrono::high_resolution_clock::now();
}
// Simulate all automata
// Launch threads
// For each automata
//
for (int tid= 0; tid < num_threads; tid++) {
//for(Automata *a : merged) {
uint64_t packet_offset = 0;
uint64_t packet_size = size/num_threads_packets;
// For each input packet of the input stream
//for (int tid= 0; tid < num_threads; tid++) {
for(int packet = 0; packet < num_threads_packets; packet++) {
Automata *a = automata[tid][packet];
// print
if(DEBUG)
a->print();
// enable runtime profiling
if(profile){
a->enableProfile();
}
if(report)
a->enableReport();
// Handle odd divisors
uint64_t length = packet_size;
if(packet == num_threads_packets - 1)
length += size % packet_size;
//cout << "Launching thread:" << endl;
//cout << " packet: " << packet << endl;
//cout << " packet_offset: " << packet_offset << endl;
//cout << " length: " << length << endl;
//cout << " packet_size: " << packet_size << endl;
// Launch thread
threads[tid][packet] = thread(simulateAutomaton,
a,
input,
packet_offset,
length,
step);
packet_offset += packet_size;
}
}
// Join threads
for (int i = 0; i < num_threads; ++i) {
for(int j = 0; j < num_threads_packets; j++){
threads[i][j].join();
}
}
// Stop timer
if(time) {
chrono::high_resolution_clock::time_point end_time = chrono::high_resolution_clock::now();
double duration = chrono::duration<double, std::milli>(end_time - start_time).count();
std::cout << "Simulation Time: " << duration << " ms" << std::endl;
std::cout << "Throughput: " << (size/1000)/(duration) << " MB/s" << std::endl;
}
}
// Post process automata
uint32_t num_reports = 0;
uint32_t match_cycles = 0;
for (int tid= 0; tid < num_threads; tid++) {
for(int packet = 0; packet < num_threads_packets; packet++) {
Automata *a = automata[tid][packet];
// quiet supresses all non-debug output
if(report){
// number of reports
num_reports += a->getReportVector().size();
// number of reporting cycles
uint32_t cur = 0;
for(auto e : a->getReportVector()) {
if(e.first != cur){
match_cycles++;
cur = e.first;
}
}
if(batchsim){
a->printReportBatchSim();
}else{
//a->printReport();
a->writeReportToFile("reports_" +
to_string(tid) + "tid_" +
to_string(packet) + "packet.txt");
}
}
// Sort elements based on usage
if(profile && to_anml)
a->defrag();
}
}
if(report && !quiet && simulate) {
std::cout << "Reports: " << num_reports << std::endl;
std::cout << "Reporting Cycles: " << match_cycles << std::endl;
}
for (int tid= 0; tid < num_threads; tid++) {
// Remember, the y direction are identical, so only need y = 0
Automata *a = automata[tid][0];
// print graphviz
// this is done after simulation to account for profiling metadata
if(to_dot) {
a->automataToDotFile("automata_" + to_string(tid) + ".dot");
}
}
if(simulate){
delete input;
}
}