-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfastchart_target.c
More file actions
1189 lines (1098 loc) · 41.6 KB
/
Copy pathfastchart_target.c
File metadata and controls
1189 lines (1098 loc) · 41.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
/*
+----------------------------------------------------------------------+
| Copyright (c) 2025-2026, Ilia Alshanetsky |
| Copyright (c) 2025-2026, Advanced Internet Designs Inc. |
+----------------------------------------------------------------------+
| This source file is subject to the BSD 3-Clause license that is |
| bundled with this package in the file LICENSE. |
+----------------------------------------------------------------------+
| Author: Ilia Alshanetsky <ilia@ilia.ws> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "Zend/zend_smart_str.h"
#include "Zend/zend_exceptions.h"
#include "ext/standard/base64.h"
#include "main/fopen_wrappers.h"
#include "main/php_streams.h"
#include "main/streams/php_stream_plain_wrapper.h"
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#ifdef PHP_WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include <ft2build.h>
#include FT_FREETYPE_H
#include <plutovg.h>
#include "fastchart_target.h"
#include "fastchart_svg.h"
#include "fastchart_rasterize.h"
#include "php_fastchart.h"
#include "fastchart_pdf.h"
/* Source-image bytes cap. FC_IMAGE_MAX_DIM / FC_IMAGE_MAX_PIXELS
* are shared with the SVG rasterizer via fastchart_rasterize.h. */
#define FC_IMAGE_MAX_BYTES (8 * 1024 * 1024)
#define FC_FONT_MAX_BYTES (16 * 1024 * 1024)
#define FC_FONT_CACHE_BYTES FC_FONT_MAX_BYTES
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/* ============================================================ *
* Init *
* ============================================================ */
void fastchart_target_from_svg(fastchart_target_t *t, smart_str *buf,
int width, int height, int dpi,
int text_mode)
{
memset(t, 0, sizeof(*t));
t->kind = FASTCHART_TARGET_SVG;
t->u.svg.buf = buf;
t->u.svg.width = width;
t->u.svg.height = height;
/* SVG output is DPI-invariant: vectors scale infinitely, so DPI
* has no effect on the output viewport, and we deliberately keep
* layout / text measurement at the 96 baseline so an SVG render
* with setDpi(200) is identical to one with setDpi(96). Honoring
* the chart's DPI here would inflate label-reserved margins and
* make text-measurement reserve room for 2x glyphs that the SVG
* still emits at 1x — producing the "huge left margin" symptom.
* The `dpi` parameter is accepted for signature stability but is
* intentionally ignored. */
(void)dpi;
t->u.svg.dpi = 96;
t->u.svg.next_clip_id = 1;
t->u.svg.next_grad_id = 1;
t->u.svg.next_image_id = 1;
t->u.svg.text_mode = (text_mode == FASTCHART_SVG_TEXT_NATIVE)
? FASTCHART_SVG_TEXT_NATIVE
: FASTCHART_SVG_TEXT_PATHS;
}
void fastchart_target_from_pdf(fastchart_target_t *t, smart_str *out,
int width, int height, int dpi)
{
memset(t, 0, sizeof(*t));
t->kind = FASTCHART_TARGET_PDF;
#ifdef HAVE_FASTCHART_PDF
t->u.pdf.state = fc_pdf_doc_open(out, width, height);
#else
(void)out;
t->u.pdf.state = NULL;
#endif
t->u.pdf.width = width;
t->u.pdf.height = height;
/* Vector output is DPI-invariant, same rationale as the SVG target:
* layout/text measurement stay on the 96 baseline. */
(void)dpi;
t->u.pdf.dpi = 96;
}
int fastchart_target_pdf_ok(const fastchart_target_t *t)
{
return (t->kind == FASTCHART_TARGET_PDF && t->u.pdf.state != NULL) ? 1 : 0;
}
int fastchart_target_pdf_finish(fastchart_target_t *t)
{
if (t->kind != FASTCHART_TARGET_PDF) return -1;
#ifdef HAVE_FASTCHART_PDF
fc_pdf_state *st = (fc_pdf_state *)t->u.pdf.state;
t->u.pdf.state = NULL;
/* pdfioFileClose streams the xref/trailer (and the page content
* stream) through our smart_str output callback, then frees all
* pdfio objects in the same call. A memory_limit bailout during that
* flush would longjmp past the frees, leaking pdfio's malloc'd
* objects (untracked by the request allocator) for the life of a
* worker — and pdfioFileClose is not re-entrant (it re-adds the PDF/A
* OutputIntent and re-closes objects on each call), so the interrupted
* close cannot simply be retried. Lift the limit across the bounded
* flush so the close runs to completion atomically; the zend_try guard
* still tears the document down before re-entering the bailout should
* any other fatal (e.g. timeout) fire. */
zend_long saved = PG(memory_limit);
zend_set_memory_limit((size_t)-1);
int rc = 0;
zend_try {
rc = fc_pdf_doc_close(st);
} zend_catch {
/* Reached only if some non-memory_limit fatal (e.g. timeout)
* fired mid-close. pdfioFileClose is not re-entrant, so we can't
* safely retry it; restore the limit and let the bailout unwind
* the dying request. */
zend_set_memory_limit((size_t)saved);
zend_bailout();
} zend_end_try();
zend_set_memory_limit((size_t)saved);
return rc;
#else
return -1;
#endif
}
void fastchart_target_pdf_abort(fastchart_target_t *t)
{
if (t->kind != FASTCHART_TARGET_PDF) return;
#ifdef HAVE_FASTCHART_PDF
fc_pdf_doc_abort((fc_pdf_state *)t->u.pdf.state);
t->u.pdf.state = NULL;
#endif
}
/* ============================================================ *
* Color *
* ============================================================ */
/* Fibonacci-hash slot for a packed rgba key. */
static inline int fc_color_slot(uint32_t key, int mask)
{
return (int)((key * 2654435761u) & (uint32_t)mask);
}
static void fc_color_hash_grow(fastchart_target_t *t)
{
int cap = t->color_hash_cap ? t->color_hash_cap * 2 : 128;
if (t->color_hash) efree(t->color_hash);
t->color_hash = safe_emalloc((size_t)cap, sizeof(int), 0);
t->color_hash_cap = cap;
memset(t->color_hash, 0xFF, (size_t)cap * sizeof(int)); /* -1 = empty */
int mask = cap - 1;
for (int i = 0; i < t->n_colors; i++) {
int slot = fc_color_slot(t->color_rgba[i], mask);
while (t->color_hash[slot] != -1) slot = (slot + 1) & mask;
t->color_hash[slot] = i;
}
}
int fastchart_target_color(fastchart_target_t *t, int r, int g, int b, int a)
{
/* Clamp 0..255. */
if (r < 0) r = 0; else if (r > 255) r = 255;
if (g < 0) g = 0; else if (g > 255) g = 255;
if (b < 0) b = 0; else if (b > 255) b = 255;
if (a < 0) a = 0; else if (a > 255) a = 255;
uint32_t key = ((uint32_t)a << 24) | ((uint32_t)r << 16)
| ((uint32_t)g << 8) | (uint32_t)b;
if (t->n_colors * 2 >= t->color_hash_cap) {
fc_color_hash_grow(t);
}
int mask = t->color_hash_cap - 1;
int slot = fc_color_slot(key, mask);
while (t->color_hash[slot] != -1) {
if (t->color_rgba[t->color_hash[slot]] == key) {
return t->color_hash[slot];
}
slot = (slot + 1) & mask;
}
if (t->n_colors >= t->color_cap) {
int new_cap = t->color_cap ? t->color_cap * 2 : 64;
t->color_rgba = erealloc(t->color_rgba,
(size_t)new_cap * sizeof(*t->color_rgba));
t->color_cap = new_cap;
}
int idx = t->n_colors++;
t->color_rgba[idx] = key;
t->color_hash[slot] = idx;
return idx;
}
int fastchart_target_color_rgb(fastchart_target_t *t, int rgb)
{
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return fastchart_target_color(t, r, g, b, 0xFF);
}
uint32_t fastchart_target_color_to_rgba(fastchart_target_t *t, int handle)
{
if (handle < 0 || handle >= t->n_colors) return 0xFF000000u;
return t->color_rgba[handle];
}
/* ============================================================ *
* Dimensions *
* ============================================================ */
void fastchart_target_get_dims(fastchart_target_t *t, int *w, int *h)
{
if (t->kind == FASTCHART_TARGET_PDF) {
*w = t->u.pdf.width;
*h = t->u.pdf.height;
return;
}
*w = t->u.svg.width;
*h = t->u.svg.height;
}
int fastchart_target_get_dpi(fastchart_target_t *t)
{
if (t->kind == FASTCHART_TARGET_PDF) return t->u.pdf.dpi;
return t->u.svg.dpi;
}
/* ============================================================ *
* Primitives *
* ============================================================ */
void fastchart_target_line(fastchart_target_t *t,
int x0, int y0, int x1, int y1,
int color, int thickness, int dash)
{
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_line(t->u.pdf.state, x0, y0, x1, y1, rgba, thickness, dash);
return;
}
#endif
fc_svg_emit_line(t->u.svg.buf, x0, y0, x1, y1, rgba, thickness, dash);
}
void fastchart_target_rect(fastchart_target_t *t,
int x, int y, int w, int h,
int color, int fill, int thickness)
{
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_rect(t->u.pdf.state, x, y, w, h, rgba, fill, thickness);
return;
}
#endif
fc_svg_emit_rect(t->u.svg.buf, x, y, w, h, rgba, fill, thickness);
}
void fastchart_target_polygon(fastchart_target_t *t,
const fastchart_point_t *pts, int n,
int color, int fill, int thickness)
{
if (n < 2) return;
int xs_stack[256], ys_stack[256];
int *xs = xs_stack, *ys = ys_stack;
FASTCHART_SPLIT_POINTS(pts, n, xs, ys);
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_polygon(t->u.pdf.state, xs, ys, n, rgba, fill, thickness);
if (n > 256) { efree(xs); efree(ys); }
return;
}
#endif
fc_svg_emit_polygon(t->u.svg.buf, xs, ys, n, rgba, fill, thickness);
if (n > 256) { efree(xs); efree(ys); }
}
void fastchart_target_polyline(fastchart_target_t *t,
const fastchart_point_t *pts, int n,
int color, int thickness, int dash)
{
if (n < 2) return;
int xs_stack[256], ys_stack[256];
int *xs = xs_stack, *ys = ys_stack;
FASTCHART_SPLIT_POINTS(pts, n, xs, ys);
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
/* One stroked path, matching SVG's single <polyline>: decomposing
* into n-1 independent segments left butt-cap notches at interior
* vertices for thickness > 1. */
fc_pdf_emit_polyline(t->u.pdf.state, xs, ys, n, rgba, thickness, dash);
} else
#endif
fc_svg_emit_polyline(t->u.svg.buf, xs, ys, n, rgba, thickness, dash);
if (n > 256) { efree(xs); efree(ys); }
}
void fastchart_target_arc(fastchart_target_t *t,
int cx, int cy, int rx, int ry,
double start_deg, double end_deg,
int color, int fill, int thickness)
{
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_arc(t->u.pdf.state, cx, cy, rx, ry,
start_deg, end_deg, rgba, fill, thickness);
return;
}
#endif
fc_svg_emit_path_arc(t->u.svg.buf, cx, cy, rx, ry,
start_deg, end_deg, rgba, fill, thickness);
}
void fastchart_target_ellipse(fastchart_target_t *t,
int cx, int cy, int rx, int ry,
int color, int fill, int thickness)
{
uint32_t rgba = fastchart_target_color_to_rgba(t, color);
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_ellipse(t->u.pdf.state, cx, cy, rx, ry, rgba, fill, thickness);
return;
}
#endif
fc_svg_emit_ellipse(t->u.svg.buf, cx, cy, rx, ry, rgba, fill, thickness);
}
/* ============================================================ *
* Font family resolution via FreeType *
* ============================================================ */
/* FT state lives in TSRM module globals (see ZEND_BEGIN_MODULE_GLOBALS
* in php_fastchart.h). Under NTS this is one struct shared process-
* wide; under ZTS each thread gets its own copy via TSRM. No mutex
* needed: FreeType operations on different FT_Library handles are
* independent, and the face cache lives inside each thread's
* globals so no two threads ever share an FT_Face.
*
* The "4-slot LRU" sizing matches the typical mixed-font dashboard:
* one chart font, one symbol font, two for axis-label/title splits.
* Linear scan + swap-to-front on hit keeps the hot path at slot 0. */
FT_Library fastchart_ft_library(void)
{
if (FASTCHART_G(ft_lib) != NULL) return FASTCHART_G(ft_lib);
if (FASTCHART_G(ft_lib_init_failed)) return NULL;
FT_Library lib = NULL;
if (FT_Init_FreeType(&lib) != 0) {
FASTCHART_G(ft_lib) = NULL;
FASTCHART_G(ft_lib_init_failed) = 1;
return NULL;
}
FASTCHART_G(ft_lib) = lib;
return lib;
}
/* Invalidate any glyph cache entries that point at `victim`. Called
* just before FT_Done_Face on the evicted face so the cache never
* carries dangling face pointers. */
static void fastchart_glyph_cache_drop_face(FT_Face victim)
{
fc_glyph_cache_entry *g = FASTCHART_G(glyph_cache);
for (int i = 0; i < FC_GLYPH_CACHE_N; i++) {
if (g[i].face == victim) {
free(g[i].ops);
free(g[i].pts);
memset(&g[i], 0, sizeof(g[i]));
}
}
/* The measurement cache keys on the same face pointer; drop its
* entries too so a reused pointer (a later FT_New_Face landing at
* the freed address) can't produce a stale-advance false hit. */
fc_measure_cache_entry *m = FASTCHART_G(measure_cache);
for (int i = 0; i < FC_MEASURE_CACHE_N; i++) {
if (m[i].face == victim) m[i].face = NULL;
}
}
/* Advance-only glyph lookup for text measurement, backed by the
* per-thread measure cache. The caller must have positioned the face
* with FT_Set_Char_Size(size_64, dpi) already — the cache key records
* that size so a hit returns an advance consistent with it. On a miss
* the glyph is loaded for its advance (no outline decompose — the
* measure path never needs the path stream) and cached. Returns 0 with
* the advance in *out_adv, or -1 on FT_Load_Glyph failure (caller skips
* the glyph, matching the pre-cache behaviour). */
int fastchart_measured_advance(FT_Face face, int32_t size_64, int dpi,
uint32_t codepoint, int32_t *out_adv)
{
fc_measure_cache_entry *m = FASTCHART_G(measure_cache);
fc_measure_cache_entry *e = &m[codepoint & (FC_MEASURE_CACHE_N - 1)];
if (e->face == face && e->codepoint == codepoint
&& e->size_64 == size_64 && e->dpi == dpi) {
*out_adv = e->advance_x_64;
return 0;
}
FT_UInt gi = FT_Get_Char_Index(face, codepoint);
if (FT_Load_Glyph(face, gi, FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING)) {
return -1;
}
int32_t adv = (int32_t)face->glyph->advance.x;
e->face = face;
e->codepoint = codepoint;
e->size_64 = size_64;
e->dpi = dpi;
e->advance_x_64 = adv;
*out_adv = adv;
return 0;
}
static zend_string *fc_stream_copy_and_close(php_stream *stream, size_t max_len)
{
php_stream * volatile live = stream;
zend_string *raw = NULL;
zend_try {
raw = php_stream_copy_to_mem((php_stream *)live, max_len, 0);
php_stream *closing = (php_stream *)live;
live = NULL;
php_stream_close(closing);
} zend_catch {
if (live) php_stream_close((php_stream *)live);
zend_bailout();
} zend_end_try();
return raw;
}
static unsigned char *fastchart_load_font_bytes(const char *font_path,
size_t *out_len)
{
*out_len = 0;
if (php_check_open_basedir_ex(font_path, 0) != 0) return NULL;
int flags = O_RDONLY;
#ifdef O_NONBLOCK
flags |= O_NONBLOCK;
#endif
#ifdef O_BINARY
flags |= O_BINARY;
#endif
int fd = VCWD_OPEN(font_path, flags);
if (fd < 0) return NULL;
zend_stat_t st;
if (zend_fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) ||
st.st_size <= 0 || (uintmax_t)st.st_size > FC_FONT_MAX_BYTES) {
#ifdef PHP_WIN32
_close(fd);
#else
close(fd);
#endif
return NULL;
}
php_stream *stream = php_stream_fopen_from_fd(fd, "rb", NULL);
if (!stream) {
#ifdef PHP_WIN32
_close(fd);
#else
close(fd);
#endif
return NULL;
}
zend_string *raw = fc_stream_copy_and_close(stream, FC_FONT_MAX_BYTES + 1);
if (!raw || ZSTR_LEN(raw) == 0 || ZSTR_LEN(raw) > FC_FONT_MAX_BYTES) {
if (raw) zend_string_release(raw);
return NULL;
}
size_t len = ZSTR_LEN(raw);
unsigned char *data = malloc(len);
if (!data) {
zend_string_release(raw);
return NULL;
}
memcpy(data, ZSTR_VAL(raw), len);
zend_string_release(raw);
*out_len = len;
return data;
}
static void fastchart_ft_face_slot_release(fc_ft_face_slot *slot)
{
if (slot->face) {
fastchart_glyph_cache_drop_face(slot->face);
FT_Done_Face(slot->face);
}
free(slot->path);
free(slot->data);
memset(slot, 0, sizeof(*slot));
}
FT_Face fastchart_ft_face(const char *font_path)
{
if (!font_path) return NULL;
FT_Library lib = fastchart_ft_library();
if (!lib) return NULL;
fc_ft_face_slot *cache = FASTCHART_G(ft_face_cache);
/* Hit? Swap-to-front to keep the hot path at slot 0. */
for (int i = 0; i < FC_FT_FACE_CACHE_N; i++) {
if (cache[i].path && strcmp(cache[i].path, font_path) == 0) {
if (i != 0) {
fc_ft_face_slot tmp = cache[0];
cache[0] = cache[i];
cache[i] = tmp;
}
return cache[0].face;
}
}
/* Raw libc allocators are deliberate throughout this cache (an
* exception to the extension-wide pemalloc convention): the
* face/glyph caches live for the process, and unlike pemalloc(n, 1)
* a malloc failure degrades to an uncached face instead of fataling
* the request.
*
* Miss. Build the new entry (malloc + FT_New_Memory_Face) BEFORE
* evicting anything so a failure mid-build leaves the cache
* untouched. */
size_t data_len;
unsigned char *data = fastchart_load_font_bytes(font_path, &data_len);
if (!data) return NULL;
size_t path_len = strlen(font_path);
char *path_copy = malloc(path_len + 1);
if (!path_copy) {
free(data);
return NULL;
}
memcpy(path_copy, font_path, path_len + 1);
FT_Face face = NULL;
if (FT_New_Memory_Face(lib, data, (FT_Long)data_len, 0, &face)) {
free(path_copy);
free(data);
return NULL;
}
/* Keep the retained backing bytes within one maximum-size font.
* Typical fonts still occupy all four LRU slots; unusually large
* faces evict as many cold entries as their bytes require. */
size_t cached_bytes = 0;
int used = 0;
for (int i = 0; i < FC_FT_FACE_CACHE_N; i++) {
if (!cache[i].path) break;
cached_bytes += cache[i].data_len;
used++;
}
while (used > 0 && (used >= FC_FT_FACE_CACHE_N ||
cached_bytes > FC_FONT_CACHE_BYTES - data_len)) {
used--;
cached_bytes -= cache[used].data_len;
fastchart_ft_face_slot_release(&cache[used]);
}
for (int i = used; i > 0; i--) {
cache[i] = cache[i - 1];
}
cache[0].path = path_copy;
cache[0].data = data;
cache[0].data_len = data_len;
cache[0].face = face;
return face;
}
void fastchart_ft_library_shutdown(void)
{
/* Free cached glyph paths first — they reference cached faces. */
fc_glyph_cache_entry *gcache = FASTCHART_G(glyph_cache);
for (int i = 0; i < FC_GLYPH_CACHE_N; i++) {
free(gcache[i].ops);
free(gcache[i].pts);
memset(&gcache[i], 0, sizeof(gcache[i]));
}
memset(FASTCHART_G(measure_cache), 0,
sizeof(fc_measure_cache_entry) * FC_MEASURE_CACHE_N);
/* Free cached faces explicitly. FT_Done_FreeType would walk and
* free them anyway, but doing it ourselves keeps the cache state
* machine deterministic and the path-string ownership tidy.
* Called from PHP_GSHUTDOWN — once per thread under ZTS, once
* at MSHUTDOWN under NTS. */
fc_ft_face_slot *cache = FASTCHART_G(ft_face_cache);
for (int i = 0; i < FC_FT_FACE_CACHE_N; i++) {
if (cache[i].face) {
FT_Done_Face(cache[i].face);
cache[i].face = NULL;
}
if (cache[i].path) {
free(cache[i].path);
cache[i].path = NULL;
}
if (cache[i].data) {
free(cache[i].data);
cache[i].data = NULL;
cache[i].data_len = 0;
}
}
if (FASTCHART_G(ft_lib) != NULL) {
FT_Done_FreeType(FASTCHART_G(ft_lib));
FASTCHART_G(ft_lib) = NULL;
}
FASTCHART_G(ft_lib_init_failed) = 0;
}
/* Glyph cache lookup. Linear scan + swap-to-front. Returns NULL on
* miss (caller must FT_Load_Glyph + FT_Outline_Decompose itself, then
* insert via fastchart_glyph_cache_insert).
*
* Caller MUST have already called FT_Set_Pixel_Sizes(face, 0, pix_size)
* to position the face at the requested size — the cache uses
* (face, pix_size, codepoint) as the key but does not touch FT state.
*/
const fc_glyph_cache_entry *fastchart_glyph_cache_get(
FT_Face face, uint16_t pix_size, uint32_t codepoint)
{
fc_glyph_cache_entry *g = FASTCHART_G(glyph_cache);
for (int i = 0; i < FC_GLYPH_CACHE_N; i++) {
if (g[i].face == face
&& g[i].pix_size == pix_size
&& g[i].codepoint == codepoint) {
if (i != 0) {
fc_glyph_cache_entry tmp = g[0];
g[0] = g[i];
g[i] = tmp;
}
return &g[0];
}
}
return NULL;
}
/* Glyph cache insert. Evicts the tail slot. ops_buf and pts_buf are
* owned by the cache after this call (do not free in the caller).
* Pass NULL for both with n_ops == 0 for whitespace glyphs (advance
* is still cached). */
void fastchart_glyph_cache_insert(FT_Face face, uint16_t pix_size,
uint32_t codepoint, int32_t advance_x_64,
char *ops_buf, uint16_t n_ops,
float *pts_buf, uint16_t n_pts)
{
fc_glyph_cache_entry *g = FASTCHART_G(glyph_cache);
int tail = FC_GLYPH_CACHE_N - 1;
/* Evict tail. */
free(g[tail].ops);
free(g[tail].pts);
/* Shift right. */
for (int i = tail; i > 0; i--) {
g[i] = g[i - 1];
}
g[0].face = face;
g[0].pix_size = pix_size;
g[0].codepoint = codepoint;
g[0].advance_x_64 = advance_x_64;
g[0].ops = ops_buf;
g[0].n_ops = n_ops;
g[0].pts = pts_buf;
g[0].n_pts = n_pts;
}
static void copy_family_name(char *out, size_t out_n, const char *src)
{
if (!src || !*src) {
snprintf(out, out_n, "sans-serif");
return;
}
/* Allow ASCII letters/digits/space/hyphen/underscore through; any
* other byte gets dropped. Keeps the result safe to inline in an
* XML attribute even if the resolver is bypassed downstream. */
size_t j = 0;
for (size_t i = 0; src[i] && j + 1 < out_n; i++) {
unsigned char c = (unsigned char)src[i];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| c == ' ' || c == '-' || c == '_' || c == '.') {
out[j++] = (char)c;
}
}
if (j == 0) {
snprintf(out, out_n, "sans-serif");
return;
}
out[j] = '\0';
}
void fastchart_target_resolve_font_family(fastchart_target_t *t,
const char *font_path,
char *out, size_t out_n)
{
if (out_n == 0) return;
if (!font_path || !*font_path) {
copy_family_name(out, out_n, NULL);
return;
}
/* Cache lookup. Pointer-equality first (palette helpers reuse
* the same const char *); fall back to strcmp. */
for (int i = 0; i < t->font_cache_n; i++) {
fastchart_target_font_cache_entry *e = &t->font_cache[i];
if (e->path == font_path
|| (e->path && strcmp(e->path, font_path) == 0)) {
snprintf(out, out_n, "%s", e->family);
return;
}
}
/* FT lookup via the shared face cache. The face is owned by the
* cache; family_name is a pointer into face-owned memory so we
* copy the bytes out before the next caller might mutate face
* state. */
char raw[128] = "";
FT_Face face = fastchart_ft_face(font_path);
if (face && face->family_name) {
snprintf(raw, sizeof(raw), "%s", face->family_name);
}
copy_family_name(out, out_n, raw[0] ? raw : NULL);
/* Cache (path,family). Capacity is FASTCHART_TARGET_FONT_CACHE;
* past that we silently skip the cache (next call hits FT
* again — rare, since charts use 1-4 fonts max). */
if (t->font_cache_n < FASTCHART_TARGET_FONT_CACHE) {
fastchart_target_font_cache_entry *e =
&t->font_cache[t->font_cache_n++];
e->path = font_path;
snprintf(e->family, sizeof(e->family), "%s", out);
}
}
/* ============================================================ *
* Release *
* ============================================================ */
void fastchart_target_release(fastchart_target_t *t)
{
for (int i = 0; i < t->image_cache_n; i++) {
fastchart_target_image_cache_entry *entry = &t->image_cache[i];
if (entry->path) efree(entry->path);
if (entry->bytes) zend_string_release(entry->bytes);
memset(entry, 0, sizeof(*entry));
}
t->image_cache_n = 0;
if (t->color_rgba) {
efree(t->color_rgba);
t->color_rgba = NULL;
}
t->n_colors = 0;
t->color_cap = 0;
if (t->color_hash) {
efree(t->color_hash);
t->color_hash = NULL;
}
t->color_hash_cap = 0;
}
/* ============================================================ *
* Clip *
* ============================================================ */
void fastchart_target_clip_push(fastchart_target_t *t,
int x, int y, int w, int h)
{
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
if (t->clip_depth < FASTCHART_TARGET_CLIP_DEPTH) t->clip_depth++;
fc_pdf_emit_clip_open(t->u.pdf.state, x, y, w, h);
return;
}
#endif
/* Saturate rather than overflow: signed wrap is UB, and a wrapped
* negative id would emit an invalid NCName. Unreachable in practice
* (2^31 clips in one document exhausts memory first). */
int id = t->u.svg.next_clip_id;
if (t->u.svg.next_clip_id < INT_MAX) t->u.svg.next_clip_id++;
if (t->clip_depth < FASTCHART_TARGET_CLIP_DEPTH) {
t->clip_stack[t->clip_depth++] = id;
}
fc_svg_emit_clip_open(t->u.svg.buf, t->u.svg.id_ns, id, x, y, w, h);
}
void fastchart_target_clip_pop(fastchart_target_t *t)
{
if (t->clip_depth > 0) t->clip_depth--;
#ifdef HAVE_FASTCHART_PDF
if (t->kind == FASTCHART_TARGET_PDF) {
fc_pdf_emit_clip_close(t->u.pdf.state);
return;
}
#endif
fc_svg_emit_clip_close(t->u.svg.buf);
}
/* ============================================================ *
* Image blit *
* ============================================================ */
/* Sniff first 16 bytes of `data` (len `n`) to recover a MIME type
* the SVG <image> data URI loader can decode. Returns "image/png" /
* "image/jpeg" or NULL for unsupported formats. WebP / GIF / AVIF
* are unsupported by plutosvg's data-URI path, so they fall through
* to NULL and the caller skips emission. */
static const char *fc_sniff_image_mime(const unsigned char *data, size_t n)
{
if (n < 8) return NULL;
if (data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G'
&& data[4] == '\r' && data[5] == '\n' && data[6] == 0x1A
&& data[7] == '\n') {
return "image/png";
}
if (data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF) {
return "image/jpeg";
}
return NULL;
}
/* Walk a PNG's chunk list and verify every declared chunk length
* fits within the buffer. The vendored stb_image accepts IDAT chunk
* lengths up to ~1 GB before attempting the read, so a 30-byte PNG
* declaring length=0x3FFFFFFF triggers a ~1 GB realloc — single-
* request OOM-kill on memory-constrained workers. stb's threat
* model treats resource validation as the caller's responsibility,
* so the check lives here. Returns 0 on PNGs with self-consistent
* chunk framing (or any non-PNG input), -1 if any chunk declares a
* length that overruns the remaining buffer. */
static int fc_validate_png_chunks(const unsigned char *b, size_t n)
{
if (n < 16 || b[0] != 0x89 || b[1] != 'P'
|| b[2] != 'N' || b[3] != 'G') {
return 0;
}
size_t off = 8; /* past PNG signature */
/* Cap iterations purely as a runaway guard — each pass advances off
* by at least 12 bytes, so a buffer under FC_IMAGE_MAX_BYTES already
* bounds the loop. libpng emits ~8KB IDATs, so a valid file near the
* cap can hold well over 1000 chunks; keep the ceiling high enough
* that legal PNGs are never rejected into the solid-fill fallback. */
for (int iter = 0; iter < 65536; iter++) {
if (off + 12 > n) return 0; /* truncated tail; stb handles it */
uint32_t len = ((uint32_t)b[off] << 24)
| ((uint32_t)b[off + 1] << 16)
| ((uint32_t)b[off + 2] << 8)
| (uint32_t)b[off + 3];
if (len > (uint32_t)INT32_MAX) return -1;
if ((size_t)len > n - off - 12) return -1;
if (b[off + 4] == 'I' && b[off + 5] == 'E'
&& b[off + 6] == 'N' && b[off + 7] == 'D') {
return 0;
}
off += 12 + (size_t)len;
}
return -1;
}
/* Sniff width/height for a PNG or JPEG buffer. Returns 0 on success,
* -1 if the header layout doesn't yield dimensions. Mirrors the
* fastchart_axis.c routine but operates on an in-memory buffer. */
static int fc_sniff_image_dims_mem(const unsigned char *b, size_t n,
int *out_w, int *out_h)
{
if (n < 24) return -1;
if (b[0] == 0x89 && b[1] == 'P' && b[2] == 'N' && b[3] == 'G') {
/* PNG IHDR width/height are big-endian uint32. b[i] integer-
* promotes to (signed) int before the shift; for b[16] >= 0x80,
* b[16] << 24 lands in the sign bit which is C11 UB. Parse via
* uint32_t, reject 0 or > INT_MAX, then narrow. */
uint32_t w = ((uint32_t)b[16] << 24) | ((uint32_t)b[17] << 16)
| ((uint32_t)b[18] << 8) | (uint32_t)b[19];
uint32_t h = ((uint32_t)b[20] << 24) | ((uint32_t)b[21] << 16)
| ((uint32_t)b[22] << 8) | (uint32_t)b[23];
if (w == 0 || h == 0 || w > INT_MAX || h > INT_MAX) return -1;
*out_w = (int)w;
*out_h = (int)h;
return 0;
}
if (b[0] == 0xFF && b[1] == 0xD8) {
size_t i = 2;
while (i + 9 < n) {
if (b[i] != 0xFF) return -1;
unsigned char marker = b[i + 1];
if (marker == 0x00 || marker == 0xFF) { i++; continue; }
if (marker == 0xD8 || marker == 0xD9) { i += 2; continue; }
if ((marker >= 0xC0 && marker <= 0xCF)
&& marker != 0xC4 && marker != 0xC8 && marker != 0xCC) {
*out_h = (b[i + 5] << 8) | b[i + 6];
*out_w = (b[i + 7] << 8) | b[i + 8];
return 0;
}
unsigned int seg_len = (b[i + 2] << 8) | b[i + 3];
if (seg_len < 2) return -1;
i += 2 + seg_len;
}
}
return -1;
}
/* Load `path` once through the PHP stream layer. The stream wrapper
* enforces open_basedir natively, so there is no TOCTOU window
* between an open_basedir check and the open. Reads up to
* FC_IMAGE_MAX_BYTES + 1 so a file at exactly the cap passes while a
* file one byte over gets rejected (php_stream_copy_to_mem with a
* smaller cap would silently truncate). On success populates *out
* with the bytes, sniffed MIME type, and declared width/height, then
* applies the dimension caps. Returns 0 / -1; on -1 the cache entry
* retains only its path. */
static int fastchart_load_source_image(const char *path,
fastchart_target_image_cache_entry *out)
{
if (!path || !*path || !out) return -1;
/* Stat BEFORE open: open(2) on a FIFO with no writer blocks
* indefinitely (the plain-files wrapper forced by IGNORE_URL
* passes no O_NONBLOCK), so the post-open non-regular-file check
* below would never be reached for exactly the FIFO case it
* names. A stat failure falls through — the open below reports
* it with proper warning suppression. The post-open fstat stays
* authoritative; it closes the swap race this pre-check alone
* would reintroduce. */
zend_stat_t pre_st;
if (VCWD_STAT(path, &pre_st) == 0 && !S_ISREG(pre_st.st_mode)) {
return -1;
}
/* Suppress the E_WARNING the stream wrapper would emit on
* open_basedir refusal / missing file. Background-image and
* icon callers fall back to their solid-color backup; the
* refusal isn't an error condition from their POV. */
int er = EG(error_reporting);
EG(error_reporting) = 0;
php_stream *stream = php_stream_open_wrapper((char *)path, "rb",
IGNORE_PATH | IGNORE_URL, NULL);
EG(error_reporting) = er;
if (!stream) {
if (EG(exception)) zend_clear_exception();
return -1;
}
/* Reject non-regular files (directories, FIFOs, sockets, char
* devices, /proc entries). The stream wrapper happily opens any
* readable inode; without this check a render fed
* /proc/self/maps would either trip the byte cap or return
* unbounded data before the MIME sniff rejects it. The stat
* call uses the stream's own backend (so wrappers without a real
* stat — http, php://memory — silently fall through and the
* MIME sniff is the only gate; that's intentional). */
php_stream_statbuf ssb;
if (php_stream_stat(stream, &ssb) == 0) {
if (!S_ISREG(ssb.sb.st_mode)) {
php_stream_close(stream);
return -1;
}
}
zend_string *raw = fc_stream_copy_and_close(stream, FC_IMAGE_MAX_BYTES + 1);
if (!raw) return -1;
size_t n = ZSTR_LEN(raw);
if (n == 0 || n > FC_IMAGE_MAX_BYTES) {
zend_string_release(raw);
return -1;
}
const unsigned char *bytes = (const unsigned char *)ZSTR_VAL(raw);
const char *mime = fc_sniff_image_mime(bytes, n);
if (!mime) {
zend_string_release(raw);
return -1;
}
int src_w = 0, src_h = 0;
if (fc_sniff_image_dims_mem(bytes, n, &src_w, &src_h) != 0) {