-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
18504 lines (14727 loc) · 670 KB
/
index.html
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
<!DOCTYPE html>
<html>
<!-- vim:set tw=100 ts=8 sw=4 et :-->
<head>
<title>Is Prefix Of String In Table? A Journey Into SIMD String Processing.</title>
<meta name="msvalidate.01" content="E828541C73A98C315E3D6B8C88EF6057" />
<meta name="viewport" content="width=device-width, initial-scale=0.65, maximum-scale=1.0" />
<!-- https://www.google.com/fonts#UsePlace:use/Collection:Lato:200,300,300italic -->
<!--
<meta name="viewport" content="width=device-width, min-width=1100px, initial-scale=0.7, maximum-scale=1.0, shrint-to-fit=no" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:200,300,300italic">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Merriweather:300,300i,400,400i">
-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet">
<link rel="stylesheet" href="//oss.maxcdn.com/normalize/3.0.1/normalize.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="../prism.css">
<link rel="stylesheet" href="../home.css">
<link rel="stylesheet" href="page.css">
<script src="//oss.maxcdn.com/jquery/2.1.1/jquery.min.js"></script>
<script src="../prism.js"></script>
<script src="../home.js"></script>
<script src="page.js"></script>
</head>
<body>
<header class="header">
<div class="header-logo" href="#">
<!--
<a class="homename" href="http://trent.me"><strong>T</strong>rent <strong>N</strong>elson</a>
-->
<a class="homename" href=".."><strong>T</strong>rent <strong>N</strong>elson</a>
</div>
<ul class="header-links">
<li><a href="#home"><i class="fa fa-home"></i> Is Prefix Of String In Table?</a></li>
<li><a href="#contents"><i class="fa fa-align-left"></i> Contents</a></li>
<li><a href="https://github.com/tpn/tracer/tree/v0.1.12/StringTable2" target="_blank"><i class="fa fa-github"></i> GitHub</a></li>
<li><a href="https://twitter.com/trentnelson" target="_blank"><i class="fa fa-twitter"></i> Twitter</a></li>
<!--
<li><a href="https://twitter.com/trentnelson" class="twitter-follow-button" data-show-count="false">Follow @trentnelson</a></li>
-->
</ul>
</header>
<a class="xref" name="home"></a>
<section class="section section-hero">
<div class="container">
<h1>
Is Prefix Of String In Table?
</h1>
<h3>
A Journey Into SIMD String Processing.
</h3>
</div>
</section>
<section class="section section-summary">
<div class="container">
<small>
Published: 4th May, 2018.
<!--
Updated: 4th May, 2018.
Target publish date: <del>20th April, 2018</del> <del>23rd April, 2018</del>
<del>25th April, 2018</del> <del>30th April, 2018</del> <del>2nd May, 2018</del>
7th May, 2018.
-->
Thanks to <a href="https://twitter.com/rygorous">Fabian Giesen</a>,
<a href="https://twitter.com/pshufb">Wojciech Muła</a>,
<a href="https://twitter.com/geofflangdale">Geoff Langdale</a>,
<a href="https://twitter.com/lemire">Daniel Lemire</a>, and
<a href="https://twitter.com/KendallWillets">Kendall Willets</a>
for their valuable
<a href="https://twitter.com/trentnelson/status/985715037934440448">feedback</a>
on an early draft of this article. <a
href="https://github.com/tpn/website/blob/master/is-prefix-of-string-in-table/index.html">
View this page's source on GitHub.</a>
<!-- 15.6 + 48.53 + 2.42 + 33.85 + 42 + 49.67 + 11.55 + 9.12 + 12.95 + 4.87 -->
Hours spent on this article to date: 230.56.
<hr/>
<h3>TL;DR</h3>
<p>
Wrote some C and assembly code that uses SIMD instructions to perform prefix
matching of strings. The C code was between 4-7x faster than the baseline
implementation for prefix matching. The assembly code was 9-12x faster than the
baseline specifically for the negative match case (determining that an incoming
string definitely does <strong>not</strong> prefix match any of our known
strings). The fastest negative match could be done in around 6 CPU cycles, which
is pretty quick. (Integer division, for example, takes about 90 cycles.)
</p>
</small>
<hr/>
<h2>Overview</h2>
<p>
Goal: given a string, determine if it prefix-matches a set of known strings as
fast as possible. That is, in a set of known strings, do any of them prefix
match the incoming search string?
</p>
<p>
A reference implementation was written in C as a <a
href="#IsPrefixOfCStrInArray">baseline</a>, which simply looped
through an array of strings, comparing each one, byte-by-byte, looking for a
prefix match. Prefix match performance ranged from 28 CPU cycles to 130, and
negative match performance was around 74 cycles.
</p>
<p>
A SIMD-friendly C structure called <a href="#STRING_TABLE">STRING_TABLE</a> was
derived. It is optimized for up to 16 strings, ideally of length less than or
equal 16 characters. The table is created from the set of known strings
up-front; it is sorted by length, ascending, and a unique character (with
regards to other characters at the same byte offset) is then extracted, along
with its index. A 16 byte character array, <a
href="#STRING_SLOT">STRING_SLOT</a>, is used to capture the unique characters.
A 16 element array of unsigned characters, SLOT_INDEX, is used to capture the
index. Similarly, lengths are stored in the same fashion via SLOT_LENGTHS.
Finally, a 16 element array of STRING_SLOTs is used to capture up to the first
16 bytes of each string in the set.
</p>
<p>
An example of the memory layout of the STRING_TABLE structure at run time, using
sample <a href="#ntfs-reserved-names">test data</a>, is depicted below. Note
the width of each row is 16 bytes (128 bits), which is the size of an XMM register.
</p>
<a href="StringTable.svg" target="_blank">
<img class="svg-image" src="StringTable.svg"/>
</a>
<!--
<picture>
<source srcset="StringTableLayout2.png"/>
<img width="1042px" height="675px" srcset="StringTableLayout2.png"/>
</picture>
-->
<p>
The layout of the STRING_TABLE structure allows us to determine if a given
search string does <strong>not</strong> prefix match all 16 strings at once
in 12 assembly instructions. This breaks down into 18 µops, with a
block throughput of 3.48 cycles on Intel's Skylake architecture. (In practice,
this clocks in at around 6 CPU cycles.)
</p>
<div class="tab-box language box-intro">
<ul class="tabs">
<li data-content="content-intro-nasm">Assembly</li>
<li data-content="content-intro-iaca">IACA</li>
</ul>
<div class="content">
<pre class="code content-intro-nasm"><code class="language-nasm">
mov rax, String.Buffer[rdx] ; Load address of string buffer.
vpbroadcastb xmm4, byte ptr String.Length[rdx] ; Broadcast string length.
vmovdqa xmm3, xmmword ptr StringTable.Lengths[rcx] ; Load table lengths.
vmovdqu xmm0, xmmword ptr [rax] ; Load string buffer.
vpcmpgtb xmm1, xmm3, xmm4 ; Identify slots > string len.
vpshufb xmm5, xmm0, StringTable.UniqueIndex[rcx] ; Rearrange string by unique index.
vpcmpeqb xmm5, xmm5, StringTable.UniqueChars[rcx] ; Compare rearranged to unique.
vptest xmm1, xmm5 ; Unique slots AND (!long slots).
jnc short Pfx10 ; CY=0, continue with routine.
xor eax, eax ; CY=1, no match.
not al ; al = -1 (NO_MATCH_FOUND).
ret ; Return NO_MATCH_FOUND.
</code></pre>
<pre class="code content-intro-iaca"><code class="language-nasm">
S:\Source\tracer>iaca x64\Release\StringTable2.dll
Intel(R) Architecture Code Analyzer
Version - v3.0-28-g1ba2cbb build date: 2017-10-23;17:30:24
Analyzed File - x64\Release\StringTable2.dll
Binary Format - 64Bit
Architecture - SKL
Analysis Type - Throughput
Throughput Analysis Report
--------------------------
Block Throughput: 3.48 Cycles Throughput Bottleneck: FrontEnd
Loop Count: 24
Port Binding In Cycles Per Iteration:
----------------------------------------------------------------------------
| Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | 6 | 7 |
----------------------------------------------------------------------------
| Cycles | 2.0 0.0 | 1.0 | 3.5 3.5 | 3.5 3.5 | 0.0 | 3.0 | 2.0 | 0.0 |
----------------------------------------------------------------------------
DV - Divider pipe (on port 0)
D - Data fetch pipe (on ports 2 and 3)
* - instruction micro-ops not bound to a port
^ - Micro Fusion occurred
| | Ports pressure in cycles | |
|µops|0DV| 1 | 2 - D | 3 - D |4| 5 | 6 |7|
-------------------------------------------
| 1 | | |0.5 0.5|0.5 0.5| | | | | mov rax, qword ptr [rdx+0x8]
| 2 | | |0.5 0.5|0.5 0.5| |1.0| | | vpbroadcastb xmm4, byte ptr [rdx]
| 1 | | |0.5 0.5|0.5 0.5| | | | | vmovdqa xmm3, xmmword ptr [rcx+0x20]
| 1 | | |0.5 0.5|0.5 0.5| | | | | vmovdqu xmm0, xmmword ptr [rax]
| 1 |1.0| | | | | | | | vpcmpgtb xmm1, xmm3, xmm4
| 2^ | | |0.5 0.5|0.5 0.5| |1.0| | | vpshufb xmm5, xmm0, xmmword ptr [rcx+0x10]
| 2^ | |1.0|0.5 0.5|0.5 0.5| | | | | vpcmpeqb xmm5, xmm5, xmmword ptr [rcx]
| 2 |1.0| | | | |1.0| | | vptest xmm1, xmm5
| 1 | | | | | | |1.0| | jnb 0x10
| 1* | | | | | | | | | xor eax, eax
| 1 | | | | | | |1.0| | not al
| 3^ | | |0.5 0.5|0.5 0.5| | | | | ret
Total Num Of µops: 18
</code></pre>
</div>
</div>
<p>
Here's a simplified walk-through of a negative match in action,
using the search string "CAT":
<a href="StringTable-NegativeMatch-v3.svg" target="_blank">
<img class="svg-image" src="StringTable-NegativeMatch-v3.svg"/>
</a>
</p>
<p>
Ten iterations of a function named IsPrefixOfStringInTable were authored. The
<a href="#IsPrefixOfStringInTable_10">tenth</a> and final iteration was the
fastest, prefix matching in as little as 19 cycles — a 4x improvement over
the baseline. Negative matching took 11 cycles — a 6.7x improvement.
</p>
<p>
An <a
href="#IsPrefixOfStringInTable_x64_2">assembly</a>
version of the algorithm was authored specifically to optimize for the negative
match case, and was able to do so in as little as 8 cycles, representing a 9x
improvement over the baseline. (It was a little bit slower than the fastest
C routine in the case of prefix matches, though, as can be seen below.)
</p>
<p>
Feedback for an early draft of this article was then solicited via <a
href="https://twitter.com/trentnelson/status/985715037934440448">Twitter</a>,
resulting in four more iterations of the C version, and three more iterations of
the assembly version. The PGO build of the fastest C version prefix matched in
about 16 cycles (and also had the best "worst case input string" performance
(where three slots needed comparison), negative matching in about 26 cycles).
The fifth iteration of the assembly version negative matched in about 6 cycles,
a 3 and 1 cycle improvement, respectively.
</p>
<p>
<a href="Benchmark-Overview-v2.svg" target="_blank">
<img class="svg-image" src="Benchmark-Overview-v2.svg"/>
</a>
</p>
<p>
We were then ready to publish, but felt compelled to investigate an odd
performance quirk we'd noticed with one of the assembly routines, which
yielded 7 more assembly versions. Were any of them faster? Let's find out.
</p>
</div>
</section>
<hr/>
<section class="section section-toc">
<div class="container">
<a class="xref" name="contents"></a>
<h1>Contents</h1>
<p>
<ul class="toc-list">
<li>
<a href="#background">Background</a>
<ul class="toc-list-2">
<li><a href="#tracer-project">The Tracer Project</a></li>
<li><a href="#baseline">Baseline C Implementation</a></li>
<li>
<a href="#proposed-interface">Proposed Interface</a>
<ul>
<li>
The <a href="#IsPrefixOfStringInTable">
IsPrefixOfStringInTable</a> function.
</li>
<li>
The <a href="#STRING_MATCH">STRING_MATCH</a> structure.
</li>
</ul>
</li>
<li><a href="#test-data">The Test Data</a></li>
<li>
<a href="#requirements-and-design-decisions">
Requirements and Design Decisions
</a>
</li>
</ul>
</li>
<li>
<a href="#data-structures">The Data Structures</a>
<ul class="toc-list-2">
<li>
<a href="#STRING_TABLE">STRING_TABLE</a>
</li>
<li><a href="#STRING_ARRAY">STRING_ARRAY</a></li>
<li><a href="#STRING_SLOT">STRING_SLOT</a></li>
<li><a href="#SLOT_INDEX">SLOT_INDEX</a></li>
<li><a href="#SLOT_LENGTHS">SLOT_LENGTHS</a></li>
<li><a href="CreateStringTable">String Table Construction</a>
</ul>
</li>
<li>
<a href="#benchmark">The Benchmark</a>
</li>
<li>
<a href="#implementations">The Implementations</a>
<ul class="toc-list-2">
<li>
Round 1
<ul class="toc-list-3">
<li><a href="#round1-c">C</a></li>
<ul class="toc-list-4">
<li>
<a href="#IsPrefixOfCStrInArray">IsPrefixOfCStrInArray</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_1">IsPrefixOfStringInTable_1</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_2">IsPrefixOfStringInTable_2</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_3">IsPrefixOfStringInTable_3</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_4">IsPrefixOfStringInTable_4</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_5">IsPrefixOfStringInTable_5</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_6">IsPrefixOfStringInTable_6</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_7">IsPrefixOfStringInTable_7</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_8">IsPrefixOfStringInTable_8</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_9">IsPrefixOfStringInTable_9</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_10">IsPrefixOfStringInTable_10</a>
</li>
</ul>
<li><a href="#round1-assembly">Assembly</a>
<ul class="toc-list-4">
<li>
<a href="#IsPrefixOfStringInTable_x64_1">IsPrefixOfStringInTable_x64_1</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_2">IsPrefixOfStringInTable_x64_2</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_3">IsPrefixOfStringInTable_x64_3</a>
</li>
</ul>
</ul>
</li>
<li>
<a href="#round2">Round 2; Post-Internet Feedback</a>
<ul class="toc-list-3">
<li>C</li>
<ul class="toc-list-4">
<li>
<a href="#IsPrefixOfStringInTable_11">IsPrefixOfStringInTable_11</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_12">IsPrefixOfStringInTable_12</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_13">IsPrefixOfStringInTable_13</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_14">IsPrefixOfStringInTable_14</a>
</li>
</ul>
<li>Assembly</a>
<ul class="toc-list-4">
<li>
<a href="#IsPrefixOfStringInTable_x64_4">IsPrefixOfStringInTable_x64_4</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_5">IsPrefixOfStringInTable_x64_5</a>
</li>
</ul>
</ul>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_3-review">Round 3; Investigating why IsPrefixOfStringInTable_x64_3 was so slow...</a>
<ul class="toc-list-3">
<ul class="toc-list-4">
<li>
<a href="#IsPrefixOfStringInTable_x64_7">IsPrefixOfStringInTable_x64_7</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_8">IsPrefixOfStringInTable_x64_8</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_9">IsPrefixOfStringInTable_x64_9</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_10">IsPrefixOfStringInTable_x64_10</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_11">IsPrefixOfStringInTable_x64_11</a>
</li>
<li>
<a href="#IsPrefixOfStringInTable_x64_12">IsPrefixOfStringInTable_x64_12</a>
</li>
</ul>
</ul>
</li>
</ul>
</li>
<li>
<a href="#other-applications">Other Applications</a>
</li>
<li>
<a href="#appendix">Appendix</a>
<ul class="toc-list-2">
<li><a href="#implementation-considerations">Implementation Considerations</a></li>
<li><a href="#release-vs-pgo">Release vs PGO</a></li>
<li>A list of all C <a href="#typedefs">typedefs</a> referenced in the article</li>
</ul>
</li>
</ul>
</p>
</div>
</section>
<hr/>
<section class="section section-body">
<div class="container">
<h1>The Background</h1>
<h2>The Tracer Project</h2>
<p>
One of the frustrations I had with existing Python profilers was that there was
no easy or efficient means to filter or exclude trace information based on the module
name of the code being executed. I tackled this in my
<a href="https://github.com/tpn/tracer">tracer</a> project, which allows you to
set an environment variable named TRACER_MODULE_NAMES to restrict which modules
should be traced, e.g.:
<pre>set TRACER_MODULE_NAMES=myproject1;myproject2;myproject3.subproject;numpy;pandas;scipy</pre>
</p>
<p>
If the code being executed is coming from the module
<code>myproject3.subproject.foo</code>, then we need to trace it, as that string
<strong>prefix matches</strong> the third entry on our list.
</p>
<p>
This article details the custom data structure and algorithm I came up with in
order to try and solve the prefix matching problem more optimally with a SIMD
approach. The resulting <a
href="https://github.com/tpn/tracer/tree/master/StringTable2">StringTable</a>
component is used extensively within the tracer project, and as such, must
conform to unique constraints such as no use of the C runtime library and
allocating all memory through TraceStore-backed allocators. Thus, it's not
really something you'd drop in to your current project in its current form.
Hopefully, the article still proves to be interesting.
</p>
<small>
<p>
Note: the code samples provided herein are copied directly from the tracer
project, which is written in C and assembly, and uses the Pascal-esque
<em>Cutler Normal Form</em> style for C. If you're used to the more UNIX-style
<a href="https://www.freebsd.org/cgi/man.cgi?query=style&sektion=9">
<em>Kernel Normal Form</em></a> of C, it's quite like that, except that it's
absolutely nothing like that, and all these code samples will probably be
very jarring.
<p>
</small>
<a class="xref" name="baseline"></a>
<h2>Baseline C Implementation</h2>
<p>
The simplest way of solving this in C is to have an array of C strings (i.e.
NULL terminated byte arrays), then for each string, loop through byte by byte
and see if it prefix matches the search string.
</p>
<div class="tab-box language box-simple">
<ul class="tabs">
<li data-content="content-simple-cnf">Baseline (Cutler Normal Form)</li>
<li data-content="content-simple-knf">Baseline (Kernel Normal Form)</li>
</ul>
<div class="content">
<pre class="code content-simple-cnf"><code class="language-c">
//
// Declare a set of module names to be used as a string array.
//
const PCSZ ModuleNames[] = {
"myproject1",
"myproject2",
"myproject3.subproject",
"numpy",
"pandas",
"scipy",
NULL,
};
//
// Define the function pointer typedef.
//
typedef
STRING_TABLE_INDEX
(IS_PREFIX_OF_CSTR_IN_ARRAY)(
_In_ PCSZ *StringArray,
_In_ PCSZ String,
_Out_opt_ PSTRING_MATCH Match
);
typedef IS_PREFIX_OF_CSTR_IN_ARRAY *PIS_PREFIX_OF_CSTR_IN_ARRAY;
//
// Forward declaration.
//
IS_PREFIX_OF_CSTR_IN_ARRAY IsPrefixOfCStrInArray;
_Use_decl_annotations_
STRING_TABLE_INDEX
IsPrefixOfCStrInArray(
PCSZ *StringArray,
PCSZ String,
PSTRING_MATCH Match
)
{
PCSZ Left;
PCSZ Right;
PCSZ *Target;
ULONG Index = 0;
ULONG Count;
for (Target = StringArray; *Target != NULL; Target++, Index++) {
Count = 0;
Left = String;
Right = *Target;
while (*Left && *Right && *Left++ == *Right++) {
Count++;
}
if (Count > 0 && !*Right) {
if (ARGUMENT_PRESENT(Match)) {
Match->Index = (BYTE)Index;
Match->NumberOfMatchedCharacters = (BYTE)Count;
Match->String = NULL;
}
return (STRING_TABLE_INDEX)Index;
}
}
return NO_MATCH_FOUND;
}
</code></pre>
<pre class="code content-simple-knf"><code class="language-c">
const char *module_names[] = {
"myproject1",
"myproject2",
"myproject3.subproject",
"numpy",
"pandas",
"scipy",
0,
};
struct string_match {
/* Index of the match. */
unsigned char index;
/* Number of characters matched. */
unsigned char number_of_chars_matched;
/* Pad out to an 8-byte boundary. */
unsigned short padding[3];
/* Pointer to the string that was matched. */
char *str;
};
unsigned char
is_prefix_of_c_str_in_array(const char **array,
const char *str,
struct string_match *match)
{
char *left, *right, **target;
unsigned int c, i = 0;
for (target = array; target; target++, i++) {
c = 0;
left = str;
right *target;
while (*left && *right && *left++ == *right) {
c++;
}
if (c > 0 && !*right) {
if (match) {
match->index = i;
match->chars_matched = c;
match->str = target[i];
}
return i;
}
}
return -1;
}
</code></pre>
</div>
</div>
<p>
Another type of code pattern that the string table attempts to replace is
anything that does a lot of if/else if/else if-type string comparisons to
look for keywords. For example, in the
<a href="https://github.com/id-Software/Quake-III-Arena/blob/dbe4ddb10315479fc00086f08e25d968b4b43c49/q3asm/q3asm.c#L609">
Quake III</a> source, there's some symbol/string processing logic that looks
like this:
</p>
<pre class="code content-q3"><code class="language-c">
// call instructions reset currentArgOffset
if ( !strncmp( token, "CALL", 4 ) ) {
EmitByte( &segment[CODESEG], OP_CALL );
instructionCount++;
currentArgOffset = 0;
return;
}
// arg is converted to a reversed store
if ( !strncmp( token, "ARG", 3 ) ) {
EmitByte( &segment[CODESEG], OP_ARG );
instructionCount++;
if ( 8 + currentArgOffset >= 256 ) {
CodeError( "currentArgOffset >= 256" );
return;
}
EmitByte( &segment[CODESEG], 8 + currentArgOffset );
currentArgOffset += 4;
return;
}
// ret just leaves something on the op stack
if ( !strncmp( token, "RET", 3 ) ) {
EmitByte( &segment[CODESEG], OP_LEAVE );
instructionCount++;
EmitInt( &segment[CODESEG], 8 + currentLocals + currentArgs );
return;
}
// pop is needed to discard the return value of
// a function
if ( !strncmp( token, "pop", 3 ) ) {
EmitByte( &segment[CODESEG], OP_POP );
instructionCount++;
return;
}
...
</code></pre>
<p>
An example of using the string table approach for this problem is discussed
in the <a href="#other-applications">Other Applications</a> section.
</p>
<a class="xref" name="proposed-interface"></a>
<h3>The Proposed Interface</h3>
<p>
Let's take a look at the interface we're proposing, the
<code>IsPrefixOfStringInTable</code> function, that this article is based upon:
</p>
<a class="xref" name="IsPrefixOfStringInTable"></a>
<pre class="code content-proposed-interface-cnf"><code class="language-c">
//
// Our string table index is simply a char, with -1 indicating no match found.
//
typedef CHAR STRING_TABLE_INDEX;
#define NO_MATCH_FOUND -1
typedef
STRING_TABLE_INDEX
(IS_PREFIX_OF_STRING_IN_TABLE)(
_In_ PSTRING_TABLE StringTable,
_In_ PSTRING String,
_Out_opt_ PSTRING_MATCH StringMatch
);
typedef IS_PREFIX_OF_STRING_IN_TABLE *PIS_PREFIX_OF_STRING_IN_TABLE;
IS_PREFIX_OF_STRING_IN_TABLE IsPrefixOfStringInTable;
_Use_decl_annotations_
STRING_TABLE_INDEX
IsPrefixOfStringInTable(
PSTRING_TABLE StringTable,
PSTRING String,
PSTRING_MATCH Match
)
/*++
Routine Description:
Searches a string table to see if any strings "prefix match" the given
search string. That is, whether any string in the table "starts with
or is equal to" the search string.
Arguments:
StringTable - Supplies a pointer to a STRING_TABLE struct.
String - Supplies a pointer to a STRING struct that contains the string to
search for.
Match - Optionally supplies a pointer to a variable that contains the
address of a STRING_MATCH structure. This will be populated with
additional details about the match if a non-NULL pointer is supplied.
Return Value:
Index of the prefix match if one was found, NO_MATCH_FOUND if not.
--*/
</code></pre>
<p>
All implementations discussed in this article adhere to that function signature.
The <a href="#STRING_TABLE">STRING_TABLE</a> structure will be discussed shortly.
</p>
<p>
The STRING_MATCH structure is used to optionally communicate information about
the prefix match back to the caller. The index and characters matched fields
are often very useful when using the string table for text parsing; see the <a
href="#other-applications">other applications</a> section below for an example.
</p>
<p>
The structure is defined as follows:
</p>
<a class="xref" name="STRING_MATCH"></a>
<pre class="code content-string-match"><code class="language-c">
//
// This structure is used to communicate matches back to the caller.
//
typedef struct _STRING_MATCH {
//
// Index of the match.
//
BYTE Index;
//
// Number of characters matched.
//
BYTE NumberOfMatchedCharacters;
//
// Pad out to 8-bytes.
//
USHORT Padding[3];
//
// Pointer to the string that was matched. The underlying buffer will
// stay valid for as long as the STRING_TABLE struct persists.
//
PSTRING String;
} STRING_MATCH, *PSTRING_MATCH, **PPSTRING_MATCH;
C_ASSERT(sizeof(STRING_MATCH) == 16);
</code></pre>
<a class="xref" name="test-data"></a>
<h2>The Test Data</h2>
<p>
Instead of using some arbitrary Python module names, this article is going to
focus on a string table constructed out of a set of 16 strings that represent
reserved names of the NTFS file system, at least when it was first released
way back in the early 90s.
</p>
<p>
This list is desirable as it has good distribution of characters, there is
a good mix of both short and long entries, plus one oversized one
($INDEX_ALLOCATION, which clocks in at 17 characters), and almost all
strings lead with a common character (the dollar sign), preventing a simple
<em>first character</em> optimization used by <a href="https://github.com/tpn/tracer/blob/2018-04-18.1/StringTable/StringTable.h#L324">
the initial version of the StringTable component I wrote in 2016</a>.
</p>
<p>
So the scenario we'll be emulating, in this case, is that we've just been passed
a filename for creation, and we need to check if it prefix matches any of the
reserved names.
</p>
<p>
Here's the full list of NTFS names we'll be using. We're assuming 8-bit ASCII
encoding (no UTF-8) and case sensitive. (If this were actually the NT kernel,
we'd need to use wide characters with UTF-16 enconding, and be
case-insensitive.)
</p>
<a class="xref" name="ntfs-reserved-names"></a>
<h3>NTFS Reserved Names</h3>
<p>
<ul>
<li>$AttrDef</li>
<li>$BadClus</li>
<li>$Bitmap</li>
<li>$Boot</li>
<li>$Extend</li>
<li>$LogFile</li>
<li>$MftMirr</li>
<li>$Mft</li>
<li>$Secure</li>
<li>$UpCase</li>
<li>$Volume</li>
<li>$Cairo</li>
<li>$INDEX_ALLOCATION</li>
<li>$DATA</li>
<li>????</li>
<li>.</li>
</ul>
</p>
<p>
The ordering is important in certain cases. For example, when you have
overlapping strings, such as $MftMirr, and $Mft, you should put the longest
strings first. They will be matched first, and as our routine terminates upon
the first successful prefix match — if a longer string resided after a
shorter one, it would never get detected.
</p>
<p>
Let's review some guiding design requirements and cover some of the design
decisions I made, which should help shape your understanding of the
implementation.
</p>
<a class="xref" name="requirements-and-design-decisions"></a>
<h2>Requirements and Design Decisions</h2>
<p>
The STRING struct will be used to capture incoming search strings as well as the
representation of any strings registered in the table (or more accurately, in
the corresponding StringArray structure associated with the string table.
</p>
<pre class="code content-string-struct"><code class="language-c">
//
// The STRING structure used by the NT kernel. Our STRING_ARRAY structure
// relies on an array of these structures. We never pass raw 'char *'s
// around, only STRING/PSTRING structs/pointers.
//
typedef struct _STRING {
USHORT Length;
USHORT MaximumLength;
ULONG Padding;
PCHAR Buffer;
} STRING, *PSTRING;
typedef const STRING *PCSTRING;
</code></pre>
<p>
The design should optimize for string lengths less than or equal to 16. Lengths
greater than 16 are permitted, up to 128 bytes, but they incur more overhead during
the prefix lookup.
</p>
<p>
The design should prioritize the fast-path code where there is no match for a
given search string. Being able to terminate the search as early as possible is
ideal.
</p>
<p>
The performance hits taken by unaligned data access are non-nelgible, especially
when dealing with XMM/YMM loads. Pay special care to alignment constrants and
make sure that everything under our control is aligned on a suitable boundary.
(The only thing we can't really control in the real world is the alignment of
the incoming search string buffer, which will often be at undesirable alignments
like 2, 4, 6, etc. Our test program explicitly aligns the incoming search
strings on 32-byte boundaries to avoid the penalties associated with unaligned
access.)
</p>
<p>
The string table is geared toward a single-shot build. Once you've created it
with a given string array or used a delimited environment variable, that's it.
There are no AddString() or RemoveString() routines. The order you provided the
strings in will be the same order the table uses — no re-ordering will be
done. Thus, for prefix matching purposes, if two strings share a common prefix,
the longer one should go first, as the prefix search routine will check it first.
</p>