Debian Codegraph @

texk/web2c/mfluadir/otfcc/lib/libcff/subr.c

raw
1 #include "subr.h"
2 /**
3 Type 2 CharString subroutinizer.
4 This program uses SEQUITUR (Nevill-Manning algorithm) to construct a CFG from the input sequence of
5 opcodes (in the minimum unit of a operator call. That is, operand* operator special*.)
6 Kieffer-Yang optimization is unnecessary, given that in almost all payloads, there are no repeating
7 subroutines.
8 */
9
10 #ifdef DEBUG
11 static int nodesCreated = 0;
12 static int nodesRemoved = 0;
13 static int rulesCreated = 0;
14 static int rulesRemoved = 0;
15 #endif
16
17 static cff_SubrNode *cff_new_Node() {
18 cff_SubrNode *n;
19 NEW(n);
20 n->rule = NULL;
21 n->terminal = NULL;
22 n->guard = false;
23 n->hard = false;
24 n->prev = NULL;
25 n->next = NULL;
26 #ifdef DEBUG
27 nodesCreated += 1;
28 #endif
29 return n;
30 }
31
32 static cff_SubrRule *cff_new_Rule() {
33 cff_SubrRule *r;
34 NEW(r);
35 r->refcount = 0;
36 r->guard = cff_new_Node();
37 r->guard->prev = r->guard;
38 r->guard->next = r->guard;
39 r->guard->terminal = 0;
40 r->guard->guard = true;
41 r->guard->rule = r;
42 r->next = NULL;
43 #ifdef DEBUG
44 rulesCreated += 1;
45 #endif
46 return r;
47 }
48
49 static void initSubrGraph(cff_SubrGraph *g) {
50 g->root = cff_new_Rule();
51 g->last = g->root;
52 g->diagramIndex = NULL;
53 g->totalRules = 0;
54 g->totalCharStrings = 0;
55 g->doSubroutinize = false;
56 }
57
58 static void clean_Node(cff_SubrNode *x) {
59 if (x->rule) { x->rule->refcount -= 1; }
60 x->rule = NULL;
61 buffree(x->terminal);
62 x->terminal = NULL;
63 }
64 static void delete_Node(cff_SubrNode *x) {
65 if (!x) return;
66 clean_Node(x);
67 #ifdef DEBUG
68 nodesRemoved += 1;
69 #endif
70 FREE(x);
71 }
72
73 static void deleteFullRule(cff_SubrRule *r) {
74 if (r->guard) {
75 for (cff_SubrNode *e = r->guard->next; e != r->guard;) {
76 cff_SubrNode *next = e->next;
77 if (e->terminal) buffree(e->terminal);
78 FREE(e);
79 #ifdef DEBUG
80 nodesRemoved += 1;
81 #endif
82 e = next;
83 }
84 {
85 FREE(r->guard);
86 #ifdef DEBUG
87 nodesRemoved += 1;
88 #endif
89 }
90 }
91
92 FREE(r);
93 #ifdef DEBUG
94 rulesRemoved += 1;
95 #endif
96 }
97
98 static void disposeSubrGraph(cff_SubrGraph *g) {
99 {
100 cff_SubrRule *r = g->root;
101 while (r) {
102 cff_SubrRule *next = r->next;
103 deleteFullRule(r);
104 r = next;
105 }
106 }
107 cff_SubrDiagramIndex *s, *tmp;
108 HASH_ITER(hh, g->diagramIndex, s, tmp) {
109 HASH_DEL(g->diagramIndex, s);
110 FREE(s->key);
111 FREE(s);
112 }
113 #ifdef DEBUG
114 fprintf(stderr, "ALLOC: %d >< %d nodes\n", nodesCreated, nodesRemoved);
115 fprintf(stderr, "ALLOC: %d >< %d rules\n", rulesCreated, rulesRemoved);
116 #endif
117 }
118
119 caryll_standardRefType(cff_SubrGraph, cff_iSubrGraph, initSubrGraph, disposeSubrGraph);
120
121 // Subroutinizer
122
123 static void joinNodes(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrNode *n);
124
125 static uint8_t *getSingletHashKey(cff_SubrNode *n, size_t *len) {
126 size_t l1;
127 if (n->rule) {
128 l1 = sizeof(n->rule->uniqueIndex);
129 } else {
130 l1 = buflen(n->terminal) * sizeof(uint8_t);
131 }
132
133 *len = 3 + l1 + 1;
134 uint8_t *key;
135 NEW(key, *len);
136 key[0] = '1';
137 key[1] = (n->rule ? '1' : '0');
138 key[2] = '0';
139 key[*len - 1] = 0;
140
141 if (n->rule) {
142 memcpy(key + 3, &(n->rule->uniqueIndex), l1);
143 } else {
144 memcpy(key + 3, n->terminal->data, l1);
145 }
146 return key;
147 }
148
149 static uint8_t *getDoubletHashKey(cff_SubrNode *n, size_t *len) {
150 size_t l1, l2;
151 if (n->rule) {
152 l1 = sizeof(n->rule->uniqueIndex);
153 } else {
154 l1 = buflen(n->terminal) * sizeof(uint8_t);
155 }
156 if (n->next->rule) {
157 l2 = sizeof(n->next->rule->uniqueIndex);
158 } else {
159 l2 = buflen(n->next->terminal) * sizeof(uint8_t);
160 }
161 *len = 3 + l1 + l2 + 1;
162 uint8_t *key;
163 NEW(key, *len);
164 key[0] = '2';
165 key[1] = (n->rule ? '1' : '0');
166 key[2] = (n->next->rule ? '1' : '0');
167 key[*len - 1] = 0;
168 if (n->rule) {
169 memcpy(key + 3, &(n->rule->uniqueIndex), l1);
170 } else {
171 memcpy(key + 3, n->terminal->data, l1);
172 }
173 if (n->next->rule) {
174 memcpy(key + 3 + l1, &(n->next->rule->uniqueIndex), l2);
175 } else {
176 memcpy(key + 3 + l1, n->next->terminal->data, l2);
177 }
178 return key;
179 }
180
181 static cff_SubrNode *lastNodeOf(cff_SubrRule *r) {
182 return r->guard->prev;
183 }
184
185 static cff_SubrNode *copyNode(cff_SubrNode *n) {
186 cff_SubrNode *m = cff_new_Node();
187 if (n->rule) {
188 m->rule = n->rule;
189 m->rule->refcount += 1;
190 } else {
191 m->terminal = bufnew();
192 bufwrite_buf(m->terminal, n->terminal);
193 }
194 m->last = n->last;
195 return m;
196 }
197
198 // checkNode: check whether node N is shrinkable
199 static bool checkDoubletMatch(cff_SubrGraph *g, cff_SubrNode *n);
200
201 static void unlinkNode(cff_SubrGraph *g, cff_SubrNode *a) {
202 if (a->hard || a->guard) return;
203 size_t len;
204 uint8_t *key = getDoubletHashKey(a, &len);
205 cff_SubrDiagramIndex *di = NULL;
206 HASH_FIND(hh, g->diagramIndex, key, len, di);
207 if (di && di->start == a) {
208 HASH_DEL(g->diagramIndex, di);
209 FREE(di->key);
210 FREE(di);
211 }
212 FREE(key);
213 key = getSingletHashKey(a, &len);
214 di = NULL;
215 HASH_FIND(hh, g->diagramIndex, key, len, di);
216 if (di && di->start == a) {
217 HASH_DEL(g->diagramIndex, di);
218 FREE(di->key);
219 FREE(di);
220 }
221 FREE(key);
222 return;
223 }
224
225 static void addDoublet(cff_SubrGraph *g, cff_SubrNode *n) {
226 if (!n || !n->next || n->guard || n->hard || n->next->hard || n->next->guard) return;
227 size_t len;
228 uint8_t *key = getDoubletHashKey(n, &len);
229 cff_SubrDiagramIndex *di = NULL;
230 HASH_FIND(hh, g->diagramIndex, key, len, di);
231 if (!di) {
232 NEW(di);
233 di->arity = 2;
234 di->key = key;
235 di->start = n;
236 HASH_ADD_KEYPTR(hh, g->diagramIndex, key, len, di);
237 } else {
238 di->start = n;
239 FREE(key);
240 }
241 }
242 static void addSinglet(cff_SubrGraph *g, cff_SubrNode *n) {
243 if (!n || n->guard || n->hard) return;
244 size_t len;
245 uint8_t *key = getSingletHashKey(n, &len);
246 cff_SubrDiagramIndex *di = NULL;
247 HASH_FIND(hh, g->diagramIndex, key, len, di);
248 if (!di) {
249 NEW(di);
250 di->arity = 1;
251 di->key = key;
252 di->start = n;
253 HASH_ADD_KEYPTR(hh, g->diagramIndex, key, len, di);
254 } else {
255 di->start = n;
256 FREE(key);
257 }
258 }
259
260 static bool identNode(cff_SubrNode *m, cff_SubrNode *n) {
261 if (m->rule)
262 return (m->rule == n->rule);
263 else if (n->rule)
264 return false;
265 else
266 return (m->terminal->size == n->terminal->size &&
267 strncmp((char *)m->terminal->data, (char *)n->terminal->data, m->terminal->size) == 0);
268 }
269 static void joinNodes(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrNode *n) {
270 if (m->next) {
271 unlinkNode(g, m);
272 if (n->prev && n->next && identNode(n->prev, n) && identNode(n, n->next)) { addDoublet(g, n); }
273 if (m->prev && m->next && identNode(m->prev, m) && identNode(m, m->next)) { addDoublet(g, m->prev); }
274 }
275 m->next = n;
276 n->prev = m;
277 }
278 static void xInsertNodeAfter(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrNode *n) {
279 joinNodes(g, n, m->next);
280 joinNodes(g, m, n);
281 }
282 static void removeNodeFromGraph(cff_SubrGraph *g, cff_SubrNode *a) {
283 joinNodes(g, a->prev, a->next);
284 if (!a->guard) {
285 unlinkNode(g, a);
286 delete_Node(a);
287 }
288 }
289
290 static void expandCall(cff_SubrGraph *g, cff_SubrNode *a) {
291 cff_SubrNode *aprev = a->prev;
292 cff_SubrNode *anext = a->next;
293 cff_SubrRule *r = a->rule;
294 cff_SubrNode *r1 = r->guard->next;
295 cff_SubrNode *r2 = r->guard->prev;
296
297 // We should move out [a, a'] from g's diagramIndex
298 unlinkNode(g, a);
299
300 joinNodes(g, aprev, r1);
301 joinNodes(g, r2, anext);
302 addDoublet(g, r2);
303 // make this rule a stub.
304 r->guard->prev = r->guard->next = r->guard;
305 r->refcount -= 1;
306 // remove call node
307 delete_Node(a);
308 }
309
310 static void substituteDoubletWithRule(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrRule *r) {
311 cff_SubrNode *prev = m->prev;
312 removeNodeFromGraph(g, prev->next);
313 removeNodeFromGraph(g, prev->next);
314 cff_SubrNode *invoke = cff_new_Node();
315 invoke->rule = r;
316 invoke->rule->refcount += 1;
317 xInsertNodeAfter(g, prev, invoke);
318 addDoublet(g, prev);
319 addDoublet(g, invoke);
320 addSinglet(g, invoke);
321
322 if (!checkDoubletMatch(g, prev)) { checkDoubletMatch(g, prev->next); }
323 }
324 static void substituteSingletWithRule(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrRule *r) {
325 cff_SubrNode *prev = m->prev;
326 removeNodeFromGraph(g, prev->next);
327 cff_SubrNode *invoke = cff_new_Node();
328 invoke->rule = r;
329 invoke->rule->refcount += 1;
330 xInsertNodeAfter(g, prev, invoke);
331 addDoublet(g, prev);
332 addDoublet(g, invoke);
333 addSinglet(g, invoke);
334 }
335
336 static void processMatchDoublet(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrNode *n) {
337 cff_SubrRule *rule = NULL;
338 if (m->prev->guard && m->next->next->guard) {
339 // The match [m, m'] is a rule's full content
340 rule = m->prev->rule;
341 substituteDoubletWithRule(g, n, rule);
342 } else {
343 rule = cff_new_Rule();
344 rule->uniqueIndex = g->totalRules;
345 g->totalRules += 1;
346 g->last->next = rule;
347 g->last = rule;
348 xInsertNodeAfter(g, lastNodeOf(rule), copyNode(m));
349 xInsertNodeAfter(g, lastNodeOf(rule), copyNode(m->next));
350 substituteDoubletWithRule(g, m, rule);
351 substituteDoubletWithRule(g, n, rule);
352 addDoublet(g, rule->guard->next);
353 addSinglet(g, rule->guard->next);
354 addSinglet(g, rule->guard->next->next);
355 }
356
357 if (rule->guard->next->rule && rule->guard->next->rule->refcount == 1) {
358 // The rule is shrinkable.
359 expandCall(g, rule->guard->next);
360 }
361 }
362 static void processMatchSinglet(cff_SubrGraph *g, cff_SubrNode *m, cff_SubrNode *n) {
363 cff_SubrRule *rule = NULL;
364 if (m->prev->guard && m->next->guard) {
365 // The match [m] is a rule's full content
366 rule = m->prev->rule;
367 substituteSingletWithRule(g, n, rule);
368 } else {
369 // Create a new rule
370 rule = cff_new_Rule();
371 rule->uniqueIndex = g->totalRules;
372 g->totalRules += 1;
373 g->last->next = rule;
374 g->last = rule;
375 xInsertNodeAfter(g, lastNodeOf(rule), copyNode(m));
376 substituteSingletWithRule(g, m, rule);
377 substituteSingletWithRule(g, n, rule);
378 addSinglet(g, rule->guard->next);
379 }
380 }
381
382 static bool checkDoubletMatch(cff_SubrGraph *g, cff_SubrNode *n) {
383 if (n->guard || n->next->guard || n->hard || n->next->hard) return false;
384 // printf("test "), printNode(n, false), printNode(n->next, true);
385 size_t len;
386 uint8_t *key = getDoubletHashKey(n, &len);
387 cff_SubrDiagramIndex *di = NULL;
388 HASH_FIND(hh, g->diagramIndex, key, len, di);
389 if (!di) {
390 NEW(di);
391 di->arity = 2;
392 di->key = key;
393 di->start = n;
394 HASH_ADD_KEYPTR(hh, g->diagramIndex, key, len, di);
395 return false;
396 } else if (di->arity == 2 && di->start != n && !di->start->guard && !di->start->next->guard) {
397 FREE(key);
398 processMatchDoublet(g, di->start, n);
399 return true;
400 } else {
401 FREE(key);
402 return true;
403 }
404 }
405
406 static bool checkSingletMatch(cff_SubrGraph *g, cff_SubrNode *n) {
407 if (n->guard || n->hard) return false;
408 size_t len;
409 uint8_t *key = getSingletHashKey(n, &len);
410 cff_SubrDiagramIndex *di = NULL;
411 HASH_FIND(hh, g->diagramIndex, key, len, di);
412 if (!di) {
413 NEW(di);
414 di->arity = 1;
415 di->key = key;
416 di->start = n;
417 HASH_ADD_KEYPTR(hh, g->diagramIndex, key, len, di);
418 return false;
419 } else if (di->arity == 1 && di->start != n && !di->start->guard) {
420 FREE(key);
421 processMatchSinglet(g, di->start, n);
422 return true;
423 } else {
424 FREE(key);
425 return false;
426 }
427 }
428
429 static void appendNodeToGraph(cff_SubrGraph *g, cff_SubrNode *n) {
430 cff_SubrNode *last = lastNodeOf(g->root);
431 xInsertNodeAfter(g, last, n);
432 if (g->doSubroutinize) {
433 if (!checkDoubletMatch(g, last)) {
434 if (buflen(n->terminal) > 15) checkSingletMatch(g, n);
435 }
436 }
437 }
438
439 void cff_insertILToGraph(cff_SubrGraph *g, cff_CharstringIL *il) {
440 caryll_Buffer *blob = bufnew();
441 bool flush = false;
442 bool last = false;
443 for (uint32_t j = 0; j < il->length; j++) {
444 switch (il->instr[j].type) {
445 case IL_ITEM_OPERAND: {
446 if (flush) {
447 cff_SubrNode *n = cff_new_Node();
448 n->rule = NULL;
449 n->terminal = blob;
450 n->last = last;
451 appendNodeToGraph(g, n);
452 blob = bufnew();
453 flush = false;
454 }
455 cff_mergeCS2Operand(blob, il->instr[j].d);
456 break;
457 }
458
459 case IL_ITEM_OPERATOR: {
460 cff_mergeCS2Operator(blob, il->instr[j].i);
461 if (il->instr[j].i == op_endchar) { last = true; }
462 flush = true;
463 break;
464 }
465 case IL_ITEM_SPECIAL: {
466 cff_mergeCS2Special(blob, il->instr[j].i);
467 flush = true;
468 break;
469 }
470 default:
471 break;
472 }
473 }
474 if (blob->size) {
475 cff_SubrNode *n = cff_new_Node();
476 n->rule = NULL;
477 n->last = last;
478 n->terminal = blob;
479 appendNodeToGraph(g, n);
480 }
481 {
482 blob = bufnew();
483 cff_SubrNode *n = cff_new_Node();
484 n->rule = NULL;
485 n->terminal = blob;
486 n->hard = true;
487 appendNodeToGraph(g, n);
488 g->totalCharStrings += 1;
489 }
490 }
491
492 static void cff_statHeight(cff_SubrRule *r, uint32_t height) {
493 if (height > r->height) r->height = height;
494 // Stat the heights bottom-up.
495 uint32_t effectiveLength = 0;
496 for (cff_SubrNode *e = r->guard->next; e != r->guard; e = e->next) {
497 if (e->rule) {
498 cff_statHeight(e->rule, height + 1);
499 effectiveLength += 4;
500 } else {
501 effectiveLength += e->terminal->size;
502 }
503 }
504 r->effectiveLength = effectiveLength;
505 }
506
507 static void numberASubroutine(cff_SubrRule *r, uint32_t *current) {
508 if (r->numbered) return;
509 if (r->height >= type2_subr_nesting) return;
510 if ((r->effectiveLength - 4) * (r->refcount - 1) - 4 <= 0) return;
511 r->number = *current;
512 (*current)++;
513 r->numbered = true;
514 for (cff_SubrNode *e = r->guard->next; e != r->guard; e = e->next) {
515 if (e->rule) { numberASubroutine(e->rule, current); }
516 }
517 }
518 static uint32_t cff_numberSubroutines(cff_SubrGraph *g) {
519 uint32_t current = 0;
520 for (cff_SubrNode *e = g->root->guard->next; e != g->root->guard; e = e->next) {
521 if (e->rule) numberASubroutine(e->rule, &current);
522 }
523 return current;
524 }
525
526 static inline int32_t subroutineBias(int32_t cnt) {
527 if (cnt < 1240)
528 return 107;
529 else if (cnt < 33900)
530 return 1131;
531 else
532 return 32768;
533 }
534
535 static bool endsWithEndChar(cff_SubrRule *rule) {
536 cff_SubrNode *node = lastNodeOf(rule);
537 if (node->terminal) {
538 return node->last;
539 } else {
540 return endsWithEndChar(node->rule);
541 }
542 }
543
544 static void serializeNodeToBuffer(cff_SubrNode *node, caryll_Buffer *buf, caryll_Buffer *gsubrs, uint32_t maxGSubrs,
545 caryll_Buffer *lsubrs, uint32_t maxLSubrs) {
546 if (node->rule) {
547 if (node->rule->numbered && node->rule->number < maxLSubrs + maxGSubrs &&
548 node->rule->height < type2_subr_nesting) {
549 // A call.
550 caryll_Buffer *target;
551 if (node->rule->number < maxLSubrs) {
552 int32_t stacknum = node->rule->number - subroutineBias(maxLSubrs);
553 target = lsubrs + node->rule->number;
554 cff_mergeCS2Int(buf, stacknum);
555 cff_mergeCS2Operator(buf, op_callsubr);
556 } else {
557 int32_t stacknum = node->rule->number - maxLSubrs - subroutineBias(maxGSubrs);
558 target = gsubrs + (node->rule->number - maxLSubrs);
559 cff_mergeCS2Int(buf, stacknum);
560 cff_mergeCS2Operator(buf, op_callgsubr);
561 }
562 cff_SubrRule *r = node->rule;
563 if (!r->printed) {
564 r->printed = true;
565 for (cff_SubrNode *e = r->guard->next; e != r->guard; e = e->next) {
566 serializeNodeToBuffer(e, target, gsubrs, maxGSubrs, lsubrs, maxLSubrs);
567 }
568 if (!endsWithEndChar(r)) { cff_mergeCS2Operator(target, op_return); }
569 }
570 } else {
571 // A call, but invalid
572 // Inline its code.
573 cff_SubrRule *r = node->rule;
574 for (cff_SubrNode *e = r->guard->next; e != r->guard; e = e->next) {
575 serializeNodeToBuffer(e, buf, gsubrs, maxGSubrs, lsubrs, maxLSubrs);
576 }
577 }
578 } else {
579 bufwrite_buf(buf, node->terminal);
580 }
581 }
582
583 static caryll_Buffer *from_array(void *_context, uint32_t j) {
584 caryll_Buffer *context = (caryll_Buffer *)_context;
585 caryll_Buffer *blob = bufnew();
586 bufwrite_buf(blob, context + j);
587 return blob;
588 }
589 void cff_ilGraphToBuffers(cff_SubrGraph *g, caryll_Buffer **s, caryll_Buffer **gs, caryll_Buffer **ls,
590 const otfcc_Options *options) {
591 cff_statHeight(g->root, 0);
592 uint32_t maxSubroutines = cff_numberSubroutines(g);
593 logProgress("[libcff] Total %d subroutines extracted.", maxSubroutines);
594 uint32_t maxLSubrs = maxSubroutines;
595 uint32_t maxGSubrs = 0;
596 {
597 // balance
598 if (maxLSubrs > type2_max_subrs) {
599 maxLSubrs = type2_max_subrs;
600 maxGSubrs = maxSubroutines - maxLSubrs;
601 }
602 if (maxGSubrs > type2_max_subrs) { maxGSubrs = type2_max_subrs; }
603 uint32_t total = maxLSubrs + maxGSubrs;
604 maxLSubrs = total / 2;
605 maxGSubrs = total - maxLSubrs;
606 }
607 caryll_Buffer *charStrings, *gsubrs, *lsubrs;
608 NEW(charStrings, g->totalCharStrings + 1);
609 NEW(lsubrs, maxLSubrs + 1);
610 NEW(gsubrs, maxGSubrs + 1);
611 uint32_t j = 0;
612 cff_SubrRule *r = g->root;
613 for (cff_SubrNode *e = r->guard->next; e != r->guard; e = e->next) {
614 serializeNodeToBuffer(e, charStrings + j, gsubrs, maxGSubrs, lsubrs, maxLSubrs);
615 if (!e->rule && e->terminal && e->hard) { j++; }
616 }
617
618 cff_Index *is = cff_iIndex.fromCallback(charStrings, g->totalCharStrings, from_array);
619 cff_Index *igs = cff_iIndex.fromCallback(gsubrs, maxGSubrs, from_array);
620 cff_Index *ils = cff_iIndex.fromCallback(lsubrs, maxLSubrs, from_array);
621
622 for (uint32_t j = 0; j < g->totalCharStrings; j++) {
623 FREE((charStrings + j)->data);
624 }
625 for (uint32_t j = 0; j < maxGSubrs; j++) {
626 FREE((gsubrs + j)->data);
627 }
628 for (uint32_t j = 0; j < maxLSubrs; j++) {
629 FREE((lsubrs + j)->data);
630 }
631 FREE(charStrings), FREE(gsubrs), FREE(lsubrs);
632
633 *s = cff_iIndex.build(is), *gs = cff_iIndex.build(igs), *ls = cff_iIndex.build(ils);
634 cff_iIndex.free(is), cff_iIndex.free(igs), cff_iIndex.free(ils);
635 }