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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
(** Generate verified C libraries from Wire codecs via EverParse. *)
open Wire.Everparse
let is_upper c = Char.uppercase_ascii c = c && Char.lowercase_ascii c <> c
let normalize_segment seg =
let len = String.length seg in
let b = Buffer.create len in
let i = ref 0 in
while !i < len do
if is_upper seg.[!i] then begin
let j = ref !i in
while !j < len && is_upper seg.[!j] do
incr j
done;
Buffer.add_char b seg.[!i];
if !j - !i >= 2 then
for k = !i + 1 to !j - 1 do
Buffer.add_char b (Char.lowercase_ascii seg.[k])
done;
i := !j
end
else begin
Buffer.add_char b seg.[!i];
incr i
end
done;
Buffer.contents b
let everparse_name name =
String.split_on_char '_' name
|> List.map (fun seg -> String.capitalize_ascii (normalize_segment seg))
|> String.concat ""
let pascal_case name =
if not (String.contains name '_') then String.capitalize_ascii name
else begin
let keep = 0 and up = 1 and low = 2 in
let what_next = ref up in
let b = Buffer.create (String.length name) in
String.iter
(fun c ->
if c = '_' then what_next := up
else begin
if !what_next = keep then Buffer.add_char b c
else if !what_next = up then
Buffer.add_char b (Char.uppercase_ascii c)
else Buffer.add_char b (Char.lowercase_ascii c);
if Char.uppercase_ascii c = c then what_next := low
else if Char.lowercase_ascii c = c then what_next := keep
end)
name;
Buffer.contents b
end
let file_base (s : t) = String.capitalize_ascii s.name
let c_ident (s : t) = everparse_name s.name
let read_extern_names ~outdir s =
let path = Filename.concat outdir (file_base s ^ "_ExternalAPI.h") in
let ic = open_in path in
let names = ref [] in
(try
while true do
let line = input_line ic in
match
( String.index_opt line '(',
String.index_opt line ' ',
String.length line )
with
| Some lp, _, _ when String.length line >= 11 ->
let prefix = "extern void " in
let plen = String.length prefix in
if
String.length line > plen
&& String.sub line 0 plen = prefix
&& lp > plen
then
let name = String.sub line plen (lp - plen) in
names := name :: !names
| _ -> ()
done
with End_of_file -> ());
close_in ic;
List.rev !names
let read_validate_name ~outdir s =
let path = Filename.concat outdir (file_base s ^ ".h") in
let ic = open_in path in
let found = ref None in
let needle = "Validate" in
let nlen = String.length needle in
let is_ident c =
(c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| c = '_'
in
let base_before_validate line =
let len = String.length line in
let rec scan i =
if i + nlen > len then None
else if i > 0 && is_ident line.[i - 1] && String.sub line i nlen = needle
then begin
let j = ref i in
while !j > 0 && is_ident line.[!j - 1] do
decr j
done;
Some (String.sub line !j (i - !j))
end
else scan (i + 1)
in
scan 0
in
(try
while !found = None do
let line = String.trim (input_line ic) in
found := base_before_validate line
done
with End_of_file -> ());
close_in ic;
match !found with
| Some n -> n
| None -> Fmt.failwith "could not find Validate function name in %s" path
let write_3d ~outdir schemas = Wire.Everparse.write ~mode:`Ffi ~outdir schemas
let copy_file ~src ~dst =
let ic = open_in_bin src in
let n = in_channel_length ic in
let buf = Bytes.create n in
really_input ic buf 0 n;
close_in ic;
let oc = open_out_bin dst in
output_bytes oc buf;
close_out oc
let locate_3d_exe () =
let ic = Unix.open_process_in "command -v 3d.exe 2>/dev/null" in
let path = try Some (input_line ic) with End_of_file -> None in
ignore (Unix.close_process_in ic);
match path with
| Some p -> Some p
| None ->
let local =
Filename.concat (Sys.getenv "HOME") ".local/everparse/bin/3d.exe"
in
if Sys.file_exists local then Some local else None
let everparse_dir () =
match locate_3d_exe () with
| Some exe -> Filename.dirname exe |> Filename.dirname
| None -> failwith "3d.exe not found"
let copy_everparse_endianness ~outdir =
let dst = Filename.concat outdir "EverParseEndianness.h" in
if not (Sys.file_exists dst) then begin
let ep_dir = everparse_dir () in
let src = Filename.concat ep_dir "src/3d/EverParseEndianness.h" in
if Sys.file_exists src then copy_file ~src ~dst
else Fmt.failwith "Cannot find EverParseEndianness.h at %s" src
end
let has_3d_exe () = locate_3d_exe () <> None
let write_external_typedefs ~outdir schemas =
List.iter
(fun s ->
if Wire.Everparse.uses_wire_ctx s then begin
let path =
Filename.concat outdir (file_base s ^ "_ExternalTypedefs.h")
in
let oc = open_out path in
Fmt.pf
(Format.formatter_of_out_channel oc)
"#ifndef WIRECTX_DEFINED@\n\
#define WIRECTX_DEFINED@\n\
typedef struct %sFields WIRECTX;@\n\
#endif@\n"
(c_ident s);
close_out oc
end)
schemas
let ~outdir s =
let fields = Wire.Everparse.plug_fields s in
let base = file_base s in
let ident = c_ident s in
let path = Filename.concat outdir (base ^ "_Fields.h") in
let oc = open_out path in
let ppf = Format.formatter_of_out_channel oc in
let pr fmt = Fmt.pf ppf fmt in
let guard =
String.uppercase_ascii ident ^ "_FIELDS_H" |> fun g ->
String.map (fun c -> if c = '-' then '_' else c) g
in
let prefix =
String.uppercase_ascii ident |> fun p ->
String.map (fun c -> if c = '-' then '_' else c) p
in
pr "#ifndef %s@\n" guard;
pr "#define %s@\n" guard;
pr "#include <stdint.h>@\n@\n";
pr "/* Field indices -- use with the schema's WireSet* callbacks in a@\n";
pr " custom [WIRECTX] if you only want to capture a subset. */@\n";
List.iter
(fun f ->
pr "#define %s_IDX_%s %d@\n" prefix
(String.uppercase_ascii f.Wire.Everparse.name)
f.idx)
fields;
if fields <> [] then pr "@\n";
pr "/* Default plug: one typed member per named field. Pass a pointer to@\n";
pr " [%sFields] as [WIRECTX *] when you want every field populated. */@\n"
ident;
pr "typedef struct %sFields {@\n" ident;
List.iter (fun f -> pr " %s %s;@\n" f.Wire.Everparse.c_type f.name) fields;
if fields = [] then pr " int _unused;@\n";
pr "} %sFields;@\n" ident;
pr "#endif@\n";
Format.pp_print_flush ppf ();
close_out oc
let emit_setter_case ppf logical f =
if String.equal f.Wire.Everparse.setter logical then
match f.c_type with
| "float" | "double" ->
Fmt.pf ppf
" case %d: { %s _x; memcpy(&_x, &v, sizeof _x); f->%s = _x; \
break; }@\n"
f.idx f.c_type f.name
| _ ->
Fmt.pf ppf " case %d: f->%s = (%s) v; break;@\n" f.idx f.name
f.c_type
let write_fields_impl ~outdir s =
let fields = Wire.Everparse.plug_fields s in
let setters = Wire.Everparse.plug_setters s in
let base = file_base s in
let ident = c_ident s in
let physical_names = read_extern_names ~outdir s in
let path = Filename.concat outdir (base ^ "_Fields.c") in
let oc = open_out path in
let ppf = Format.formatter_of_out_channel oc in
let pr fmt = Fmt.pf ppf fmt in
pr "#include <stdint.h>@\n";
pr "#include <string.h>@\n";
pr "#include \"%s_Fields.h\"@\n" base;
pr "#include \"%s_ExternalTypedefs.h\"@\n" base;
pr "#include \"%s_ExternalAPI.h\"@\n@\n" base;
List.iter2
(fun (logical, val_c_type) physical ->
pr "void %s(WIRECTX *ctx, uint32_t idx, %s v) {@\n" physical val_c_type;
pr " %sFields *f = (%sFields *) ctx;@\n" ident ident;
pr " switch (idx) {@\n";
List.iter (fun f -> emit_setter_case ppf logical f) fields;
pr " default: (void) f; (void) v; break;@\n";
pr " }@\n";
pr "}@\n@\n")
setters physical_names;
Format.pp_print_flush ppf ();
close_out oc
let write_fields ~outdir schemas =
List.iter
(fun s ->
if Wire.Everparse.uses_wire_ctx s then begin
write_fields_header ~outdir s;
write_fields_impl ~outdir s
end)
schemas
let wire_ctx_files schemas =
List.concat_map
(fun s ->
if Wire.Everparse.uses_wire_ctx s then
let base = file_base s in
[
base ^ "_ExternalTypedefs.h";
base ^ "_ExternalAPI.h";
base ^ "Wrapper.c";
base ^ "Wrapper.h";
base ^ "_Fields.h";
base ^ "_Fields.c";
]
else [])
schemas
let fields_c_files schemas =
List.filter_map
(fun s ->
if Wire.Everparse.uses_wire_ctx s then Some (file_base s ^ "_Fields.c")
else None)
schemas
let wrapper_success_tail = "\t\treturn FALSE;\n\t}\n\treturn TRUE;\n}"
let wrapper_consumption_check = "result != (uint64_t) len"
let wrapper_hardened_tail =
"\t\treturn FALSE;\n\
\t}\n\
\tif (result != (uint64_t) len)\n\
\t{\n\
\t\treturn FALSE;\n\
\t}\n\
\treturn TRUE;\n\
}"
let harden_wrapper ~outdir base =
let path = Filename.concat outdir (base ^ "Wrapper.c") in
if Sys.file_exists path then begin
let src = In_channel.with_open_text path In_channel.input_all in
let tail = Re.compile (Re.str wrapper_success_tail) in
if Re.execp tail src then
Out_channel.with_open_text path (fun oc ->
Out_channel.output_string oc
(Re.replace_string tail ~by:wrapper_hardened_tail src))
else if not (Re.execp (Re.compile (Re.str wrapper_consumption_check)) src)
then
Fmt.failwith
"%s: unrecognized EverParse wrapper shape; cannot insert the \
full-consumption check"
path
end
let run_everparse_files ?(quiet = true) ~outdir files =
let exe =
match locate_3d_exe () with
| Some e -> e
| None -> failwith "3d.exe not found in PATH or ~/.local/everparse/bin/"
in
List.iter
(fun f ->
let redirect = if quiet then " > /dev/null 2>&1" else "" in
let cmd = Fmt.str "cd %s && %s --batch %s%s" outdir exe f redirect in
let ret = Sys.command cmd in
if ret <> 0 then Fmt.failwith "EverParse failed on %s with code %d" f ret;
harden_wrapper ~outdir (Filename.remove_extension (Filename.basename f)))
files;
copy_everparse_endianness ~outdir
let run_everparse ?(quiet = true) ~outdir schemas =
run_everparse_files ~quiet ~outdir (List.map Wire.Everparse.filename schemas)
let parse_3d ?(batch = false) ~outdir file =
let exe =
match locate_3d_exe () with
| Some e -> e
| None -> failwith "3d.exe not found in PATH or ~/.local/everparse/bin/"
in
let log_path = Filename.temp_file "wire_parse_3d" ".log" in
let flag = if batch then "--batch " else "" in
let cmd =
Fmt.str "cd %s && %s %s%s > %s 2>&1" outdir exe flag file log_path
in
let ret = Sys.command cmd in
let captured =
try In_channel.with_open_text log_path In_channel.input_all
with Sys_error _ -> ""
in
(try Sys.remove log_path with Sys_error _ -> ());
if ret = 0 then Ok ()
else
let msg =
String.split_on_char '\n' captured
|> List.filter (fun l ->
let l = String.trim l in
l <> ""
&& not (String.length l >= 11 && String.sub l 0 11 = "Processing "))
|> String.concat "\n"
in
Error (if msg = "" then Fmt.str "exit %d" ret else msg)
let emit_sanity_check ppf ~name ~ep ~ctx_arg wire_size =
let pr fmt = Fmt.pf ppf fmt in
pr " r = %sValidate%s(%sNULL, counting_error_handler, buf, %d, 0);\n" ep ep
ctx_arg wire_size;
pr " if (!EverParseIsSuccess(r) || r != %d) {\n" wire_size;
pr " fprintf(stderr,\n";
pr " \"FATAL: %s wire_size mismatch -- codec declared %d bytes, \"\n"
name wire_size;
pr " \"EverParse validator returned %%llu. Fix the OCaml codec's \"\n";
pr " \"wire_size or the .3d projection.\\n\",\n";
pr " (unsigned long long) r);\n";
pr " return 2;\n";
pr " }\n"
let emit_truncation_checks ppf ~ep ~ctx_arg wire_size =
let pr fmt = Fmt.pf ppf fmt in
pr " r = %sValidate%s(%sNULL, counting_error_handler, buf, %d, 0);\n" ep ep
ctx_arg (wire_size * 2);
pr " CHECK(\"larger buffer validates\", EverParseIsSuccess(r));\n";
pr " CHECK(\"position is %d not %d\", r == %d);\n" wire_size
(wire_size * 2) wire_size;
pr "\n";
pr " for (uint64_t len = 0; len < %d; len++) {\n" wire_size;
pr " error_count = 0;\n";
pr " r = %sValidate%s(%sNULL, counting_error_handler, buf, len, 0);\n" ep
ep ctx_arg;
pr " CHECK(\"truncated to len fails\", EverParseIsError(r));\n";
pr " }\n";
pr "\n";
pr " r = %sValidate%s(%sNULL, counting_error_handler, buf, 0, 0);\n" ep ep
ctx_arg;
pr " CHECK(\"empty input fails\", EverParseIsError(r));\n"
let emit_random_checks ppf ~ep ~ctx_arg wire_size =
let pr fmt = Fmt.pf ppf fmt in
pr " srand(42);\n";
pr " for (int i = 0; i < 1000; i++) {\n";
pr " for (int j = 0; j < %d; j++)\n" wire_size;
pr " buf[j] = (uint8_t)(rand() & 0xff);\n";
pr " r = %sValidate%s(%sNULL, counting_error_handler, buf, %d, 0);\n" ep
ep ctx_arg wire_size;
pr " CHECK(\"random buffer validates\", EverParseIsSuccess(r));\n";
pr " CHECK(\"random position correct\", r == %d);\n" wire_size;
pr " }\n"
let emit_schema_test ?outdir ppf s wire_size =
let pr fmt = Fmt.pf ppf fmt in
let ep =
match outdir with
| Some dir -> read_validate_name ~outdir:dir s
| None -> file_base s
in
let lower = String.lowercase_ascii s.name in
let uses_ctx = Wire.Everparse.uses_wire_ctx s in
let ctx_arg = if uses_ctx then "(WIRECTX *) &ctx, " else "" in
pr "\n /* %s (%d bytes) */\n" s.name wire_size;
pr " {\n";
pr " int pass = 0, fail = 0;\n";
pr " uint8_t buf[%d];\n" wire_size;
pr " uint64_t r;\n";
if uses_ctx then pr " %sFields ctx = {0};\n" (c_ident s);
pr "\n";
pr " memset(buf, 0, %d);\n" wire_size;
emit_sanity_check ppf ~name:s.name ~ep ~ctx_arg wire_size;
pr " CHECK(\"zero buffer validates\", EverParseIsSuccess(r));\n";
pr " CHECK(\"position advanced to %d\", r == %d);\n" wire_size wire_size;
pr "\n";
emit_truncation_checks ppf ~ep ~ctx_arg wire_size;
pr "\n";
emit_random_checks ppf ~ep ~ctx_arg wire_size;
pr "\n";
if uses_ctx then pr " (void) ctx;\n";
pr " printf(\"%s: %%d passed, %%d failed\\n\", pass, fail);\n" lower;
pr " failures += fail;\n";
pr " }\n"
let generate_test ~outdir schemas =
let oc = open_out (Filename.concat outdir "test.c") in
let ppf = Format.formatter_of_out_channel oc in
let pr fmt = Fmt.pf ppf fmt in
pr "#include <stdio.h>\n";
pr "#include <stdlib.h>\n";
pr "#include <stdint.h>\n";
pr "#include <string.h>\n";
pr "#include \"EverParse.h\"\n";
let fixed_schemas =
List.filter_map
(fun s -> Option.map (fun ws -> (s, ws)) s.wire_size)
schemas
in
List.iter
(fun (s, _) ->
let base = file_base s in
pr "#include \"%s.h\"\n" base;
if Wire.Everparse.uses_wire_ctx s then
pr "#include \"%s_Fields.h\"\n" base)
fixed_schemas;
if fixed_schemas <> [] then begin
pr "\nstatic int error_count;\n\n";
pr "static void counting_error_handler(\n";
pr " EVERPARSE_STRING t, EVERPARSE_STRING f, EVERPARSE_STRING r,\n";
pr " uint64_t c, uint8_t *ctx, uint8_t *i, uint64_t p) {\n";
pr " (void)t; (void)f; (void)r; (void)c; (void)ctx; (void)i; (void)p;\n";
pr " error_count++;\n";
pr "}\n\n"
end;
pr "#define CHECK(msg, cond) do { \\\n";
pr " if (cond) { pass++; } \\\n";
pr " else { fail++; fprintf(stderr, \" FAIL: %%s\\n\", msg); } \\\n";
pr "} while(0)\n\n";
pr "int main(void) {\n";
pr " int failures = 0;\n";
List.iter (fun (s, ws) -> emit_schema_test ~outdir ppf s ws) fixed_schemas;
pr "\n if (failures == 0)\n";
pr " printf(\"All tests passed.\\n\");\n";
pr " else\n";
pr " printf(\"%%d test(s) failed.\\n\", failures);\n";
pr " return failures ? 1 : 0;\n";
pr "}\n";
Format.pp_print_flush ppf ();
close_out oc
let ensure_dir outdir =
try Unix.mkdir outdir 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> ()
let generate_3d ~outdir schemas =
ensure_dir outdir;
write_3d ~outdir schemas
let rm_rf dir =
(try Sys.readdir dir with Sys_error _ -> [||])
|> Array.iter (fun f ->
try Sys.remove (Filename.concat dir f) with Sys_error _ -> ());
try Sys.rmdir dir with Sys_error _ -> ()
let default_job_count () = max 1 (min 4 (Domain.recommended_domain_count ()))
let fork_pool ~max_jobs jobs =
let n = Array.length jobs in
let ok = Array.make n false in
let pid_idx = Hashtbl.create 64 in
let next = ref 0 and running = ref 0 in
let reap () =
let pid, status = Unix.wait () in
match Hashtbl.find_opt pid_idx pid with
| Some i ->
Hashtbl.remove pid_idx pid;
decr running;
ok.(i) <- (match status with Unix.WEXITED 0 -> true | _ -> false)
| None -> ()
in
Format.pp_print_flush Fmt.stderr ();
Format.pp_print_flush Fmt.stdout ();
while !next < n || !running > 0 do
if !next < n && !running < max_jobs then begin
let i = !next in
incr next;
match Unix.fork () with
| 0 -> (
try
jobs.(i) ();
Unix._exit 0
with e ->
Fmt.epr "%s\n%!" (Printexc.to_string e);
Unix._exit 1)
| pid ->
Hashtbl.add pid_idx pid i;
incr running
end
else reap ()
done;
ok
let batch_check ?max_jobs ~outdir schemas =
match (locate_3d_exe (), schemas) with
| None, _ -> Error "3d.exe not found in PATH or ~/.local/everparse/bin/"
| Some _, [] -> Ok ()
| Some exe, _ -> (
ensure_dir outdir;
let arr : t array = Array.of_list schemas in
let log_of i = Filename.concat outdir (arr.(i).name ^ ".batchlog") in
let jobs =
Array.mapi
(fun i schema () ->
let work = Filename.temp_dir "wire_batchchk" "" in
Fun.protect
~finally:(fun () -> rm_rf work)
(fun () ->
generate_3d ~outdir:work [ schema ];
let cmd =
Fmt.str
"cd %s && %s --batch --no_copy_everparse_h %s > %s 2>&1"
work exe
(Wire.Everparse.filename schema)
(Filename.quote (log_of i))
in
if Sys.command cmd <> 0 then failwith "EverParse rejected"))
arr
in
let max_jobs = Option.value max_jobs ~default:(default_job_count ()) in
let ok = fork_pool ~max_jobs jobs in
let errors =
Array.to_list ok
|> List.mapi (fun i passed ->
if passed then None
else
let msg =
try In_channel.with_open_text (log_of i) In_channel.input_all
with Sys_error _ -> ""
in
Fmt.kstr (fun s -> Some s) "%s:\n%s" arr.(i).name msg)
|> List.filter_map Fun.id
in
match errors with [] -> Ok () | _ -> Error (String.concat "\n" errors))
let generate_c ?(quiet = true) ~outdir schemas =
ensure_dir outdir;
if has_3d_exe () then begin
run_everparse ~quiet ~outdir schemas;
write_external_typedefs ~outdir schemas;
write_fields ~outdir schemas;
generate_test ~outdir schemas
end
else
failwith
"3d.exe not found in PATH. Install EverParse to regenerate C files."
let run ?(quiet = true) ~outdir schemas =
generate_3d ~outdir schemas;
generate_c ~quiet ~outdir schemas
let strict_cc_flags =
"-std=c11 -D_DEFAULT_SOURCE -Wall -Werror -Wpedantic -Wstrict-prototypes \
-Wmissing-prototypes -Wshadow -Wcast-qual"
let everparse_type_defines =
"-DUINT8=uint8_t -DUINT16=uint16_t -DUINT16BE=uint16_t -DUINT32=uint32_t \
-DUINT32BE=uint32_t -DUINT64=uint64_t -DUINT64BE=uint64_t"
let emit_gen_rules ppf three_d_files c_files ctx_files =
Fmt.pf ppf
"(rule\n\
\ (alias 3d)\n\
\ (mode promote)\n\
\ (targets %s)\n\
\ (action\n\
\ (run %%{exe:gen.exe} 3d)))\n\n\
(rule\n\
\ (alias 3d)\n\
\ (enabled_if\n\
\ (= %%{env:BUILD_EVERPARSE=} \"1\"))\n\
\ (mode promote)\n\
\ (targets EverParse.h EverParseEndianness.h %s test.c)\n\
\ (deps %s)\n\
\ (action\n\
\ (run %%{exe:gen.exe} c)))\n\n"
(String.concat " " three_d_files)
(String.concat " " (c_files @ ctx_files))
(String.concat " " three_d_files)
let emit_runtest_rule ppf ~test_bin ~all_deps ~c_srcs =
Fmt.pf ppf
"(rule\n\
\ (targets %s)\n\
\ (deps %s)\n\
\ (action\n\
\ (run cc %s -o %s test.c %s)))\n\n\
(rule\n\
\ (alias runtest)\n\
\ (deps %s)\n\
\ (action\n\
\ (run %%{dep:%s})))\n\n"
test_bin
(String.concat " " all_deps)
strict_cc_flags test_bin (String.concat " " c_srcs) test_bin test_bin
let emit_install_stanza ppf ~package ~three_d_files ~c_files ~ctx_files =
let pr fmt = Fmt.pf ppf fmt in
pr "(install\n (package %s)\n (section lib)\n (files\n" package;
List.iter (fun f -> pr " (%s as c/%s)\n" f f) three_d_files;
List.iter (fun f -> pr " (%s as c/%s)\n" f f) c_files;
List.iter (fun f -> pr " (%s as c/%s)\n" f f) ctx_files;
pr " (EverParse.h as c/EverParse.h)\n";
pr " (EverParseEndianness.h as c/EverParseEndianness.h)))\n"
let generate_dune ~outdir ~package schemas =
let oc = open_out (Filename.concat outdir "dune.inc") in
let ppf = Format.formatter_of_out_channel oc in
let names = List.map file_base schemas in
let c_files = List.concat_map (fun n -> [ n ^ ".h"; n ^ ".c" ]) names in
let ctx_files = wire_ctx_files schemas in
let fields_srcs = fields_c_files schemas in
let three_d_files = List.map (fun n -> n ^ ".3d") names in
let test_bin =
"test_" ^ String.map (fun c -> if c = '-' then '_' else c) package
in
let all_deps =
[ "test.c"; "EverParse.h"; "EverParseEndianness.h" ] @ c_files @ ctx_files
in
let c_srcs = List.map (fun n -> n ^ ".c") names @ fields_srcs in
emit_gen_rules ppf three_d_files c_files ctx_files;
emit_runtest_rule ppf ~test_bin ~all_deps ~c_srcs;
emit_install_stanza ppf ~package ~three_d_files ~c_files ~ctx_files;
Format.pp_print_flush ppf ();
close_out oc
type packed = Pack : 'a Wire.Codec.t -> packed
let pack c = Pack c
let doc_module_name package =
let alnum c =
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
in
package
|> String.map (fun c -> if alnum c then c else '_')
|> String.split_on_char '_'
|> List.filter (fun s -> s <> "")
|> List.map String.capitalize_ascii
|> String.concat ""
let standalone_base ?name ~package () =
doc_module_name (match name with Some n -> n | None -> package)
let hex_of_bytes b =
let buf = Buffer.create (Bytes.length b * 2) in
let ppf = Fmt.with_buffer buf in
Bytes.iter (fun c -> Fmt.pf ppf "%02x" (Char.code c)) b;
Format.pp_print_flush ppf ();
Buffer.contents buf
let codec_accepts ?env c buf =
match Wire.Codec.decode ?env c buf 0 with
| Ok _ -> (
try
Wire.Codec.validate ?env c buf 0;
Wire.Codec.wire_size_at c buf 0 = Bytes.length buf
with Wire.Validation_error _ -> false)
| Error _ -> false
let fuzz_param_value rng center =
match Random.State.int rng 6 with
| 0 -> 0
| 1 -> center
| 2 -> center + 1
| 3 -> Random.State.int rng (max 1 ((2 * center) + 4))
| _ -> Random.State.int rng (max 1 (center + 1))
let fuzz_length rng center =
match Random.State.int rng 10 with
| 0 -> 0
| 1 | 2 -> Random.State.int rng (max 1 (center + 1))
| 3 -> (2 * center) + Random.State.int rng 4
| 4 -> center + 1
| _ -> center
let generate_corpus ?(count = 256) ppf codecs =
let rng = Random.State.make [| 0x5eed51 |] in
List.iter
(fun (Pack c) ->
let s = project ~mode:`Standalone c in
let name = s.name in
let pnames =
match s.source with Some st -> Raw.input_param_names st | None -> []
in
let center = Wire.Codec.min_wire_size c in
for _ = 1 to count do
let len = fuzz_length rng center in
let b = Bytes.init len (fun _ -> Char.chr (Random.State.int rng 256)) in
let pvals = List.map (fun _ -> fuzz_param_value rng center) pnames in
let env =
match pnames with
| [] -> None
| _ ->
Some
(List.fold_left2
(fun e n v -> Wire.Param.bind_by_name n v e)
(Wire.Codec.env c) pnames pvals)
in
let pfield =
match pvals with
| [] -> "-"
| _ -> String.concat "," (List.map string_of_int pvals)
in
let hex = if len = 0 then "-" else hex_of_bytes b in
Fmt.pf ppf "%s %s %s %d@\n" name pfield hex
(if codec_accepts ?env c b then 1 else 0)
done)
codecs;
Format.pp_print_flush ppf ()
let emit_agree_preamble ppf base ~has_params =
let pr fmt = Fmt.pf ppf (fmt ^^ "@\n") in
pr "/* Differential check: the EverParse validator must accept exactly the";
pr " inputs the OCaml codec accepts. Reads `<codec> <params> <hex>";
pr " <verdict>` lines from gen.exe's corpus, passing each codec's";
pr " parameters to its validator, and exits nonzero on any disagreement. */";
pr "#include <stdio.h>";
pr "#include <stdlib.h>";
pr "#include <string.h>";
pr "#include <stdint.h>";
pr "#include \"%s.h\"" base;
pr "#include \"%sWrapper.h\"" base;
pr "";
pr "void %sEverParseError(const char *s, const char *f, const char *r);" base;
pr "void %sEverParseError(const char *s, const char *f, const char *r)" base;
pr "{ (void) s; (void) f; (void) r; }";
if has_params then begin
pr "";
pr "/* Parse the corpus's comma-separated parameter values. */";
pr "static void parse_params(const char *s, unsigned long *out, int n) {";
pr " const char *p = s;";
pr " for (int i = 0; i < n; i++) {";
pr " out[i] = strtoul(p, NULL, 10);";
pr " const char *c = strchr(p, ',');";
pr " if (c == NULL) break;";
pr " p = c + 1;";
pr " }";
pr "}"
end
let emit_agree_run ppf triples =
let pr fmt = Fmt.pf ppf (fmt ^^ "@\n") in
pr "";
pr
"static int run(const char *name, const char *params, uint8_t *base, \
uint32_t len) {";
pr " (void) params;";
List.iter
(fun (cname, check, ptypes) ->
let n = List.length ptypes in
if n = 0 then
pr " if (strcmp(name, \"%s\") == 0) return %s(base, len) ? 1 : 0;"
cname check
else begin
let args =
ptypes
|> List.mapi (fun i t -> Fmt.str "(%s) p[%d]" t i)
|> String.concat ", "
in
pr " if (strcmp(name, \"%s\") == 0) {" cname;
pr " unsigned long p[%d];" n;
pr " parse_params(params, p, %d);" n;
pr " return %s(%s, base, len) ? 1 : 0;" check args;
pr " }"
end)
triples;
pr " fprintf(stderr, \"agree: unknown codec '%%s'\\n\", name);";
pr " exit(3);";
pr "}"
let emit_agree_main ppf =
let pr fmt = Fmt.pf ppf (fmt ^^ "@\n") in
pr "";
pr "int main(int argc, char **argv) {";
pr
" if (argc < 2) { fprintf(stderr, \"usage: %%s <corpus>\\n\", argv[0]); \
return 2; }";
pr " FILE *fp = fopen(argv[1], \"r\");";
pr " if (!fp) { perror(\"fopen\"); return 2; }";
pr " char name[256];";
pr " char params[4096];";
pr " uint8_t buf[65536];";
pr " char hex[2 * sizeof(buf) + 1];";
pr " long verdict, total = 0, mismatch = 0;";
pr
" while (fscanf(fp, \"%%255s %%4095s %%131072s %%ld\", name, params, hex, \
&verdict) == 4) {";
pr " uint32_t len = 0;";
pr " if (strcmp(hex, \"-\") != 0) {";
pr " size_t hl = strlen(hex);";
pr " len = (uint32_t) (hl / 2);";
pr
" if (len > sizeof(buf)) { fprintf(stderr, \"input too long\\n\"); \
fclose(fp); return 2; }";
pr " for (uint32_t i = 0; i < len; i++) {";
pr " unsigned b;";
pr
" if (sscanf(hex + 2 * i, \"%%2x\", &b) != 1) { fprintf(stderr, \
\"bad hex\\n\"); fclose(fp); return 2; }";
pr " buf[i] = (uint8_t) b;";
pr " }";
pr " }";
pr " int accept = run(name, params, buf, len);";
pr " total++;";
pr " if (accept != (int) verdict) {";
pr " mismatch++;";
pr " if (mismatch <= 20)";
pr
" fprintf(stderr, \"MISMATCH codec=%%s len=%%u validator=%%d \
oracle=%%ld\\n\", name, len, accept, verdict);";
pr " }";
pr " }";
pr " fclose(fp);";
pr
" fprintf(stdout, \"agree: %%ld inputs, %%ld mismatches\\n\", total, \
mismatch);";
pr " return mismatch == 0 ? 0 : 1;";
pr "}"
let generate_agree ?name ~outdir ~package codecs =
let base = standalone_base ?name ~package () in
let triples =
List.map
(fun (Pack c) ->
let s = project ~mode:`Standalone c in
let ptypes =
match s.source with
| Some st -> Raw.input_param_c_types st
| None -> []
in
(s.name, pascal_case (base ^ "_check_" ^ s.name), ptypes))
codecs
in
let has_params = List.exists (fun (_, _, ptypes) -> ptypes <> []) triples in
let oc = open_out (Filename.concat outdir "agree.c") in
let ppf = Format.formatter_of_out_channel oc in
emit_agree_preamble ppf base ~has_params;
emit_agree_run ppf triples;
emit_agree_main ppf;
Format.pp_print_flush ppf ();
close_out oc
let generate_3d_standalone ?name ~outdir ~package codecs =
ensure_dir outdir;
write ~mode:`Standalone ~outdir
~name:(standalone_base ?name ~package ())
(List.map (fun (Pack c) -> project ~mode:`Standalone c) codecs)
let generate_c_standalone ?(quiet = true) ?name ~outdir ~package () =
ensure_dir outdir;
if has_3d_exe () then
run_everparse_files ~quiet ~outdir
[ standalone_base ?name ~package () ^ ".3d" ]
else
failwith
"3d.exe not found in PATH. Install EverParse to regenerate C files."
let generate_standalone ?(quiet = true) ?name ~outdir ~package codecs =
generate_3d_standalone ?name ~outdir ~package codecs;
generate_c_standalone ~quiet ?name ~outdir ~package ();
generate_agree ?name ~outdir ~package codecs
let emit_standalone_gen_rules ppf ~three_d ~c_files =
Fmt.pf ppf
"(rule\n\
\ (alias 3d)\n\
\ (mode promote)\n\
\ (targets %s)\n\
\ (action\n\
\ (run %%{exe:gen.exe} 3d)))\n\n\
(rule\n\
\ (targets agree.c)\n\
\ (action\n\
\ (run %%{exe:gen.exe} agree)))\n\n\
(rule\n\
\ (alias 3d)\n\
\ (enabled_if\n\
\ (= %%{env:BUILD_EVERPARSE=} \"1\"))\n\
\ (mode promote)\n\
\ (targets EverParse.h EverParseEndianness.h %s)\n\
\ (deps %s)\n\
\ (action\n\
\ (run %%{exe:gen.exe} c)))\n\n"
three_d
(String.concat " " c_files)
three_d
let emit_standalone_build_rules ppf ~base ~archive ~c_files =
Fmt.pf ppf
"(rule\n\
\ (targets %s)\n\
\ (deps EverParse.h EverParseEndianness.h %s)\n\
\ (action\n\
\ (progn\n\
\ (run cc %s %s -c %s.c %sWrapper.c)\n\
\ (run ar rcs %s %s.o %sWrapper.o))))\n\n"
archive
(String.concat " " c_files)
strict_cc_flags everparse_type_defines base base archive base base;
Fmt.pf ppf
"(rule\n\
\ (targets corpus)\n\
\ (action\n\
\ (with-stdout-to corpus (run %%{exe:gen.exe} corpus))))\n\n\
(rule\n\
\ (targets agree)\n\
\ (deps agree.c %s EverParse.h EverParseEndianness.h %s.h %sWrapper.h)\n\
\ (action\n\
\ (run cc %s %s agree.c %s -o agree)))\n\n\
(rule\n\
\ (alias runtest)\n\
\ (deps corpus agree)\n\
\ (action\n\
\ (run %%{dep:agree} corpus)))\n\n"
archive base base strict_cc_flags everparse_type_defines archive
let emit_standalone_install ppf ~package ~three_d ~archive ~c_files =
let pr fmt = Fmt.pf ppf fmt in
pr "(install\n (package %s)\n (section lib)\n (files\n" package;
List.iter (fun f -> pr " (%s as c/%s)\n" f f) (three_d :: archive :: c_files);
pr " (EverParse.h as c/EverParse.h)\n";
pr " (EverParseEndianness.h as c/EverParseEndianness.h)))\n"
let generate_dune_standalone ?name ~outdir ~package _codecs =
let base = standalone_base ?name ~package () in
let three_d = base ^ ".3d" in
let c_files =
[ base ^ ".c"; base ^ ".h"; base ^ "Wrapper.c"; base ^ "Wrapper.h" ]
in
let archive = "lib" ^ String.lowercase_ascii base ^ ".a" in
let oc = open_out (Filename.concat outdir "dune.inc") in
let ppf = Format.formatter_of_out_channel oc in
emit_standalone_gen_rules ppf ~three_d ~c_files;
emit_standalone_build_rules ppf ~base ~archive ~c_files;
emit_standalone_install ppf ~package ~three_d ~archive ~c_files;
Format.pp_print_flush ppf ();
close_out oc
let main ?name ~mode ~package codecs =
let argv = Array.to_list Sys.argv in
match mode with
| `Ffi -> (
let schemas = List.map (fun (Pack c) -> project ~mode:`Ffi c) codecs in
match argv with
| [ _; "3d" ] -> generate_3d ~outdir:"." schemas
| [ _; "c" ] -> generate_c ~outdir:"." schemas
| [ _; "dune" ] -> generate_dune ~outdir:"." ~package schemas
| _ -> run ~outdir:"." schemas)
| `Standalone -> (
match argv with
| [ _; "3d" ] -> generate_3d_standalone ?name ~outdir:"." ~package codecs
| [ _; "c" ] -> generate_c_standalone ?name ~outdir:"." ~package ()
| [ _; "agree" ] -> generate_agree ?name ~outdir:"." ~package codecs
| [ _; "dune" ] ->
generate_dune_standalone ?name ~outdir:"." ~package codecs
| [ _; "corpus" ] -> generate_corpus Format.std_formatter codecs
| _ -> generate_standalone ?name ~outdir:"." ~package codecs)