-
Notifications
You must be signed in to change notification settings - Fork 149
/
ddtrace.c
2886 lines (2416 loc) · 100 KB
/
ddtrace.c
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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "ddtrace.h"
#include <SAPI.h>
#include <Zend/zend.h>
#include <Zend/zend_closures.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_extensions.h>
#include <Zend/zend_smart_str.h>
#include <components/sapi/sapi.h>
#include <headers/headers.h>
#include <hook/hook.h>
#include <json/json.h>
#include <inttypes.h>
#if PHP_VERSION_ID < 80000
#include <Zend/zend_vm.h>
#include <interceptor/php7/interceptor.h>
#else
#include <interceptor/php8/interceptor.h>
#endif
#include <jit_utils/jit_blacklist.h>
#include <php.h>
#include <php_ini.h>
#ifndef _WIN32
#include <pthread.h>
#include <stdatomic.h>
#include <sys/mman.h>
#else
#include <components/pthread_polyfill.h>
#include <components/atomic_win32_polyfill.h>
#endif
#include <ext/standard/info.h>
#include <ext/standard/php_string.h>
#include <json/json.h>
#include <components-rs/ddtrace.h>
#include <components/log/log.h>
#include "auto_flush.h"
#include "circuit_breaker.h"
#include "compatibility.h"
#ifndef _WIN32
#include "comms_php.h"
#include "coms.h"
#endif
#include "config/config.h"
#include "configuration.h"
#include "ddshared.h"
#include "ddtrace_string.h"
#ifndef _WIN32
#include "dogstatsd_client.h"
#endif
#include "engine_hooks.h"
#include "excluded_modules.h"
#include "handlers_http.h"
#include "handlers_internal.h"
#include "integrations/exec_integration.h"
#include "integrations/integrations.h"
#include "ip_extraction.h"
#include "logging.h"
#include "memory_limit.h"
#include "limiter/limiter.h"
#include "priority_sampling/priority_sampling.h"
#include "random.h"
#include "request_hooks.h"
#include "serializer.h"
#include "sidecar.h"
#ifndef _WIN32
#include "signals.h"
#endif
#include "span.h"
#include "startup_logging.h"
#include "telemetry.h"
#include "tracer_tag_propagation/tracer_tag_propagation.h"
#include "user_request.h"
#include "zend_hrtime.h"
#include "ext/standard/file.h"
#include "hook/uhook.h"
#include "handlers_fiber.h"
#include "handlers_exception.h"
#include "exceptions/exceptions.h"
// On PHP 7 we cannot declare arrays as internal values. Assign null and handle in create_object where necessary.
#if PHP_VERSION_ID < 80000
#undef ZVAL_EMPTY_ARRAY
#define ZVAL_EMPTY_ARRAY ZVAL_NULL
#endif
// CG(empty_string) is not accessible during MINIT (in ZTS at least)
#if PHP_VERSION_ID < 70200
#undef ZVAL_EMPTY_STRING
#define ZVAL_EMPTY_STRING(z) ZVAL_NEW_STR(z, zend_string_init("", 0, 1))
#endif
#include "ddtrace_arginfo.h"
#include "distributed_tracing_headers.h"
#if PHP_VERSION_ID < 70200
#undef ZVAL_EMPTY_STRING
#define ZVAL_EMPTY_STRING(z) ZVAL_INTERNED_STR(z, ZSTR_EMPTY_ALLOC())
#endif
#if PHP_VERSION_ID < 80000
#undef ZVAL_EMPTY_ARRAY
#define ZVAL_EMPTY_ARRAY DD_ZVAL_EMPTY_ARRAY
#endif
// For manual ZPP
#if PHP_VERSION_ID < 70400
#define _error_code error_code
#endif
bool ddtrace_has_excluded_module;
static zend_module_entry *ddtrace_module;
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200
static bool dd_has_other_observers;
static int dd_observer_extension_backup = -1;
#endif
static datadog_php_sapi ddtrace_active_sapi = DATADOG_PHP_SAPI_UNKNOWN;
_Atomic(int64_t) ddtrace_warn_legacy_api;
ZEND_DECLARE_MODULE_GLOBALS(ddtrace)
#ifdef COMPILE_DL_DDTRACE
ZEND_GET_MODULE(ddtrace)
#ifdef ZTS
TSRM_TLS void *TSRMLS_CACHE = NULL;
#endif
#endif
int ddtrace_disable = 0; // 0 = enabled, 1 = disabled via INI, 2 = disabled, but MINIT was fully executed
static ZEND_INI_MH(dd_OnUpdateDisabled) {
UNUSED(entry, mh_arg1, mh_arg2, mh_arg3, stage);
if (!ddtrace_disable) {
ddtrace_disable = zend_ini_parse_bool(new_value);
}
return SUCCESS;
}
PHP_INI_BEGIN()
ZEND_INI_ENTRY("ddtrace.disable", "0", PHP_INI_SYSTEM, dd_OnUpdateDisabled)
// Exposed for testing only
STD_PHP_INI_ENTRY("ddtrace.cgroup_file", "/proc/self/cgroup", PHP_INI_SYSTEM, OnUpdateString, cgroup_file,
zend_ddtrace_globals, ddtrace_globals)
PHP_INI_END()
#if PHP_VERSION_ID >= 70300 && PHP_VERSION_ID < 70400
static void ddtrace_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare, swap_func_t swp) {
UNUSED(siz);
UNUSED(compare);
UNUSED(swp);
// swap ddtrace and opcache for the rest of the modules lifecycle, so that opcache is always executed after ddtrace
for (Bucket *module = base, *end = module + count, *ddtrace_module = NULL; module < end; ++module) {
zend_module_entry *m = (zend_module_entry *)Z_PTR(module->val);
if (m->name == ddtrace_module_entry.name) {
ddtrace_module = module;
}
if (ddtrace_module && strcmp(m->name, "Zend OPcache") == 0) {
Bucket tmp = *ddtrace_module;
*ddtrace_module = *module;
*module = tmp;
break;
}
}
}
#endif
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200
// On PHP 8.0.0-8.0.16 and 8.1.0-8.1.2 call_attribute_constructor would stack allocate a dummy frame, which could have become inaccessible upon access.
// Thus, we implement the fix which was applied to PHP itself as well: we move the stack allocated data to the VM stack.
// See also https://github.com/php/php-src/commit/f7c3f6e7e25471da9cfb2ba082a77cc3c85bc6ed
static void dd_patched_zend_call_known_function(
zend_function *fn, zend_object *object, zend_class_entry *called_scope, zval *retval_ptr,
uint32_t param_count, zval *params, HashTable *named_params)
{
zval retval;
zend_fcall_info fci;
zend_fcall_info_cache fcic;
// If current_execute_data is on the stack, move it to the VM stack
zend_execute_data *execute_data = EG(current_execute_data);
if (execute_data && (uintptr_t)&retval > (uintptr_t)EX(func) && (uintptr_t)&retval - 0xfffff < (uintptr_t)EX(func)) {
zend_execute_data *call = zend_vm_stack_push_call_frame_ex(
ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_execute_data), sizeof(zval)) +
ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op), sizeof(zval)) +
ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_function), sizeof(zval)),
0, EX(func), 0, NULL);
memcpy(call, execute_data, sizeof(zend_execute_data));
zend_op *opline = (zend_op *)(call + 1);
memcpy(opline, EX(opline), sizeof(zend_op));
zend_function *func = (zend_function *)(opline + 1);
func->common.fn_flags |= ZEND_ACC_CALL_VIA_TRAMPOLINE; // See https://github.com/php/php-src/commit/2f6a06ccb0ef78e6122bb9e67f9b8b1ad07776e1
memcpy((zend_op *)(call + 1) + 1, EX(func), sizeof(zend_function));
call->opline = opline;
call->func = func;
EG(current_execute_data) = call;
}
// here follows the original implementation of zend_call_known_function
fci.size = sizeof(fci);
fci.object = object;
fci.retval = retval_ptr ? retval_ptr : &retval;
fci.param_count = param_count;
fci.params = params;
fci.named_params = named_params;
ZVAL_UNDEF(&fci.function_name); /* Unused */
fcic.function_handler = fn;
fcic.object = object;
fcic.called_scope = called_scope;
zend_result result = zend_call_function(&fci, &fcic);
if (UNEXPECTED(result == FAILURE)) {
if (!EG(exception)) {
zend_error_noreturn(E_CORE_ERROR, "Couldn't execute method %s%s%s",
fn->common.scope ? ZSTR_VAL(fn->common.scope->name) : "",
fn->common.scope ? "::" : "", ZSTR_VAL(fn->common.function_name));
}
}
if (!retval_ptr) {
zval_ptr_dtor(&retval);
}
}
// We need to hijack zend_call_known_function as that's what's being called by call_attribute_constructor, and call_attribute_constructor itself is not exported.
static void dd_patch_zend_call_known_function(void) {
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
size_t page_size = (size_t)si.dwPageSize;
#else
size_t page_size = sysconf(_SC_PAGESIZE);
#endif
void *page = (void *)(~(page_size - 1) & (uintptr_t)zend_call_known_function);
// 20 is the largest size of a trampoline we have to inject
if ((((uintptr_t)zend_call_known_function + 20) & page_size) < 20) {
page_size <<= 1; // if overlapping pages, use two
}
#ifdef _WIN32
DWORD old_protection;
if (VirtualProtect(page, page_size, PAGE_READWRITE, &old_protection))
#else
if (mprotect(page, page_size, PROT_READ | PROT_WRITE) != 0)
#endif
{ // Some architectures enforce W^X (either write _or_ execute, but not both).
LOG(ERROR, "Could not alter the memory protection for zend_call_known_function. Tracer execution continues, but may crash when encountering attributes.");
return; // Make absolutely sure we can write
}
#ifdef __aarch64__
// x13 is a scratch register
uint32_t absolute_jump_instrs[] = {
0x1000006D, // adr x13, 12 (load address from memory after this)
0xF94001AD, // ldr x13, [x13]
0xD61F01A0, // br x13
};
// The magical 12 is sizeof(absolute_jump_instrs) and hardcoded in the assembly above.
memcpy(zend_call_known_function, absolute_jump_instrs, 12);
*(void **)(12 + (uintptr_t)zend_call_known_function) = dd_patched_zend_call_known_function;
#else
// $r10 doesn't really have special meaning
uint8_t absolute_jump_instrs[] = {
0x49, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov $r10, imm_addr
0x41, 0xFF, 0xE2 // jmp $r10
};
*(void **)&absolute_jump_instrs[2] = dd_patched_zend_call_known_function;
memcpy(zend_call_known_function, absolute_jump_instrs, sizeof(absolute_jump_instrs));
#endif
#ifdef _WIN32
VirtualProtect(page, page_size, old_protection, NULL);
#else
mprotect(page, page_size, PROT_READ | PROT_EXEC);
#endif
}
#endif
// put this into startup so that other extensions running code as part of rinit do not crash
static int ddtrace_startup(zend_extension *extension) {
UNUSED(extension);
ddtrace_fetch_profiling_symbols();
#if PHP_VERSION_ID >= 70300 && PHP_VERSION_ID < 70400
// Turns out with zai config we have dynamically allocated INI entries. This does not play well with PHP 7.3
// As of PHP 7.3 opcache stores INI entry values in SHM. However, only as of PHP 7.4 opcache delays detaching SHM.
// In PHP 7.3 SHM is freed in MSHUTDOWN, which may be executed before our extension, if we do not force an order.
// We have to sort this manually here, as opcache only registers itself as extension during zend_extension.startup.
zend_hash_sort_ex(&module_registry, ddtrace_sort_modules, NULL, 0);
#endif
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200
dd_has_other_observers = ZEND_OBSERVER_ENABLED;
#endif
#if PHP_VERSION_ID < 80000
zai_interceptor_startup(ddtrace_module);
#else
zai_interceptor_startup();
#endif
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200
#if PHP_VERSION_ID < 80100
#define BUG_STACK_ALLOCATED_CALL_PATCH_VERSION 16
#else
#define BUG_STACK_ALLOCATED_CALL_PATCH_VERSION 3
#endif
zend_long patch_version = Z_LVAL_P(zend_get_constant_str(ZEND_STRL("PHP_RELEASE_VERSION")));
if (patch_version < BUG_STACK_ALLOCATED_CALL_PATCH_VERSION) {
dd_patch_zend_call_known_function();
}
#endif
ddtrace_excluded_modules_startup();
// We deliberately leave handler replacement during startup, even though this uses some config
// This touches global state, which, while unlikely, may play badly when interacting with other extensions, if done post-startup
ddtrace_internal_handlers_startup();
return SUCCESS;
}
static void ddtrace_shutdown(struct _zend_extension *extension) {
UNUSED(extension);
ddtrace_internal_handlers_shutdown();
zai_interceptor_shutdown();
}
bool dd_save_sampling_rules_file_config(zend_string *path, int modify_type, int stage) {
if (FG(default_context) == NULL) {
FG(default_context) = php_stream_context_alloc();
}
php_stream_context *context = FG(default_context);
php_stream *stream = php_stream_open_wrapper_ex(ZSTR_VAL(path), "rb", USE_PATH | REPORT_ERRORS, NULL, context);
if (!stream) {
return false;
}
zend_string *file = php_stream_copy_to_mem(stream, (ssize_t) PHP_STREAM_COPY_ALL, 0);
php_stream_close(stream);
bool altered = false;
if (file) {
altered = ZSTR_LEN(file) > 0 && SUCCESS == zend_alter_ini_entry_ex(
zai_config_memoized_entries[DDTRACE_CONFIG_DD_SPAN_SAMPLING_RULES].ini_entries[0]->name,
file, modify_type, stage, 1);
zend_string_release(file);
}
return altered;
}
bool ddtrace_alter_sampling_rules_file_config(zval *old_value, zval *new_value) {
(void) old_value;
if (Z_STRLEN_P(new_value) == 0) {
return true;
}
return dd_save_sampling_rules_file_config(Z_STR_P(new_value), PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
static inline bool dd_alter_meta_var(const char *tag, zval *old_value, zval *new_value) {
UNUSED(old_value);
ddtrace_span_properties *pspan = ddtrace_active_span_props();
while (pspan) {
zend_array *meta = ddtrace_property_array(&pspan->property_meta);
if (Z_STRLEN_P(new_value) == 0) {
zend_hash_str_del(meta, tag, strlen(tag));
} else {
Z_TRY_ADDREF_P(new_value);
zend_hash_str_update(meta, tag, strlen(tag), new_value);
}
pspan = pspan->parent;
}
return true;
}
bool ddtrace_alter_dd_env(zval *old_value, zval *new_value) {
return dd_alter_meta_var("env", old_value, new_value);
}
bool ddtrace_alter_dd_version(zval *old_value, zval *new_value) {
return dd_alter_meta_var("version", old_value, new_value);
}
static void dd_activate_once(void) {
ddtrace_config_first_rinit();
ddtrace_generate_runtime_id();
// must run before the first zai_hook_activate as ddtrace_telemetry_setup installs a global hook
if (!ddtrace_disable) {
#ifndef _WIN32
if (get_global_DD_INSTRUMENTATION_TELEMETRY_ENABLED() || get_global_DD_TRACE_SIDECAR_TRACE_SENDER())
#endif
{
bool modules_activated = PG(modules_activated);
PG(modules_activated) = false;
ddtrace_sidecar_setup();
PG(modules_activated) = modules_activated;
}
}
}
static pthread_once_t dd_activate_once_control = PTHREAD_ONCE_INIT;
static void ddtrace_activate(void) {
ddog_reset_log_once();
zai_hook_rinit();
zai_interceptor_activate();
zai_uhook_rinit();
zend_hash_init(&DDTRACE_G(traced_spans), 8, unused, NULL, 0);
zend_hash_init(&DDTRACE_G(tracestate_unknown_dd_keys), 8, unused, NULL, 0);
if (!ddtrace_disable && ddtrace_has_excluded_module == true) {
ddtrace_disable = 2;
}
// ZAI config is always set up
pthread_once(&dd_activate_once_control, dd_activate_once);
zai_config_rinit();
if (!ddtrace_disable && (get_global_DD_INSTRUMENTATION_TELEMETRY_ENABLED() || get_global_DD_TRACE_SIDECAR_TRACE_SENDER())) {
ddtrace_sidecar_ensure_active();
}
zend_string *sampling_rules_file = get_DD_SPAN_SAMPLING_RULES_FILE();
if (ZSTR_LEN(sampling_rules_file) > 0 && !zend_string_equals(get_global_DD_SPAN_SAMPLING_RULES_FILE(), sampling_rules_file)) {
dd_save_sampling_rules_file_config(sampling_rules_file, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
if (!ddtrace_disable && strcmp(sapi_module.name, "cli") == 0 && !get_DD_TRACE_CLI_ENABLED()) {
ddtrace_disable = 2;
}
if (ddtrace_disable) {
ddtrace_disable_tracing_in_current_request();
}
DDTRACE_G(request_init_hook_loaded) = 0;
#if PHP_VERSION_ID < 80000
// This allows us to hook the ZEND_HANDLE_EXCEPTION pseudo opcode
ZEND_VM_SET_OPCODE_HANDLER(EG(exception_op));
EG(exception_op)->opcode = ZEND_HANDLE_EXCEPTION;
#endif
}
static void ddtrace_deactivate(void) {
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80200
if (dd_observer_extension_backup != -1) {
zend_observer_fcall_op_array_extension = dd_observer_extension_backup;
dd_observer_extension_backup = -1;
}
#endif
}
static zend_extension _dd_zend_extension_entry = {"ddtrace",
PHP_DDTRACE_VERSION,
"Datadog",
"https://github.com/DataDog/dd-trace-php",
"Copyright Datadog",
ddtrace_startup,
ddtrace_shutdown,
ddtrace_activate,
ddtrace_deactivate,
NULL,
#if PHP_VERSION_ID < 80000
zai_interceptor_op_array_pass_two,
#else
NULL,
#endif
NULL,
NULL,
NULL,
#if PHP_VERSION_ID < 80000
zai_interceptor_op_array_ctor,
#else
NULL,
#endif
zai_hook_unresolve_op_array,
STANDARD_ZEND_EXTENSION_PROPERTIES};
static void php_ddtrace_init_globals(zend_ddtrace_globals *ng) { memset(ng, 0, sizeof(zend_ddtrace_globals)); }
static PHP_GINIT_FUNCTION(ddtrace) {
#if defined(COMPILE_DL_DDTRACE) && defined(ZTS)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
php_ddtrace_init_globals(ddtrace_globals);
zai_hook_ginit();
}
// Rust code will call __cxa_thread_atexit_impl. This is a weak symbol; it's defined by glibc.
// The problem is that calls to __cxa_thread_atexit_impl cause shared libraries to remain referenced until the calling thread terminates.
// However in NTS builds the calling thread is the main thread and thus the shared object (i.e. ddtrace.so) WILL remain loaded.
// This is problematic with e.g. apache which, upon reloading will unload all PHP modules including PHP itself, then reload.
// This prevents us from a) having the weak symbols updated to the new locations and b) having ddtrace updates going live without hard restart.
// Thus, we need to intercept it: define it ourselves so that the linker will force the rust code to call our code here.
// Then we can collect the callbacks and invoke them ourselves right at thread shutdown, i.e. GSHUTDOWN.
#if defined(COMPILE_DL_DDTRACE) && defined(__GLIBC__) && __GLIBC_MINOR__
#define CXA_THREAD_ATEXIT_WRAPPER 1
#endif
#ifdef CXA_THREAD_ATEXIT_WRAPPER
#define CXA_THREAD_ATEXIT_PHP ((void *)0)
#define CXA_THREAD_ATEXIT_UNINITIALIZED ((void *)1)
#define CXA_THREAD_ATEXIT_UNAVAILABLE ((void *)2)
static int (*glibc__cxa_thread_atexit_impl)(void (*func)(void *), void *obj, void *dso_symbol) = CXA_THREAD_ATEXIT_UNINITIALIZED;
static pthread_key_t dd_cxa_thread_atexit_key; // fallback for sidecar
struct dd_rust_thread_destructor {
void (*dtor)(void *);
void *obj;
struct dd_rust_thread_destructor *next;
};
// Use __thread explicitly: ZEND_TLS is empty on NTS builds.
static __thread struct dd_rust_thread_destructor *dd_rust_thread_destructors = NULL;
ZEND_TLS bool dd_is_main_thread = false;
static void dd_run_rust_thread_destructors(void *unused) {
UNUSED(unused);
struct dd_rust_thread_destructor *entry = dd_rust_thread_destructors;
dd_rust_thread_destructors = NULL; // destructors _may_ be invoked multiple times. We need to reset thus.
while (entry) {
struct dd_rust_thread_destructor *cur = entry;
cur->dtor(cur->obj);
entry = entry->next;
free(cur);
}
}
// Note: this symbol is not public
int __cxa_thread_atexit_impl(void (*func)(void *), void *obj, void *dso_symbol) {
if (glibc__cxa_thread_atexit_impl == CXA_THREAD_ATEXIT_UNINITIALIZED) {
glibc__cxa_thread_atexit_impl = NULL; // DL_FETCH_SYMBOL(RTLD_DEFAULT, "__cxa_thread_atexit_impl");
if (glibc__cxa_thread_atexit_impl == NULL) {
// no race condition here: logging is initialized in MINIT, at which point only a single thread lives
glibc__cxa_thread_atexit_impl = CXA_THREAD_ATEXIT_UNAVAILABLE;
pthread_key_create(&dd_cxa_thread_atexit_key, dd_run_rust_thread_destructors);
}
}
if (glibc__cxa_thread_atexit_impl != CXA_THREAD_ATEXIT_PHP && glibc__cxa_thread_atexit_impl != CXA_THREAD_ATEXIT_UNAVAILABLE) {
return glibc__cxa_thread_atexit_impl(func, obj, dso_symbol);
}
if (glibc__cxa_thread_atexit_impl == CXA_THREAD_ATEXIT_UNAVAILABLE) {
pthread_setspecific(dd_cxa_thread_atexit_key, (void *)0x1); // needs to be non-NULL
}
struct dd_rust_thread_destructor *entry = malloc(sizeof(struct dd_rust_thread_destructor));
entry->dtor = func;
entry->obj = obj;
entry->next = dd_rust_thread_destructors;
dd_rust_thread_destructors = entry;
return 0;
}
static void dd_clean_main_thread_locals() {
dd_run_rust_thread_destructors(NULL);
}
#endif
static PHP_GSHUTDOWN_FUNCTION(ddtrace) {
if (ddtrace_globals->remote_config_reader) {
ddog_agent_remote_config_reader_drop(ddtrace_globals->remote_config_reader);
}
zai_hook_gshutdown();
#ifdef CXA_THREAD_ATEXIT_WRAPPER
// FrankenPHP calls `ts_free_thread()` in rshutdown
if (!dd_is_main_thread && ddtrace_active_sapi != DATADOG_PHP_SAPI_FRANKENPHP) {
dd_run_rust_thread_destructors(NULL);
}
#endif
}
/* DDTrace\SpanLink */
zend_class_entry *ddtrace_ce_span_link;
PHP_METHOD(DDTrace_SpanLink, jsonSerialize) {
ddtrace_span_link *link = (ddtrace_span_link *)Z_OBJ_P(ZEND_THIS);
zend_array *array = zend_new_array(5);
zend_string *trace_id = zend_string_init("trace_id", sizeof("trace_id") - 1, 0);
zend_string *span_id = zend_string_init("span_id", sizeof("span_id") - 1, 0);
zend_string *trace_state = zend_string_init("trace_state", sizeof("trace_state") - 1, 0);
zend_string *attributes = zend_string_init("attributes", sizeof("attributes") - 1, 0);
zend_string *dropped_attributes_count = zend_string_init("dropped_attributes_count", sizeof("dropped_attributes_count") - 1, 0);
Z_TRY_ADDREF(link->property_trace_id);
zend_hash_add(array, trace_id, &link->property_trace_id);
Z_TRY_ADDREF(link->property_span_id);
zend_hash_add(array, span_id, &link->property_span_id);
Z_TRY_ADDREF(link->property_trace_state);
zend_hash_add(array, trace_state, &link->property_trace_state);
Z_TRY_ADDREF(link->property_attributes);
zend_hash_add(array, attributes, &link->property_attributes);
Z_TRY_ADDREF(link->property_dropped_attributes_count);
zend_hash_add(array, dropped_attributes_count, &link->property_dropped_attributes_count);
zend_string_release(trace_id);
zend_string_release(span_id);
zend_string_release(trace_state);
zend_string_release(attributes);
zend_string_release(dropped_attributes_count);
RETURN_ARR(array);
}
static ddtrace_distributed_tracing_result dd_parse_distributed_tracing_headers_function(INTERNAL_FUNCTION_PARAMETERS, bool *success);
ZEND_METHOD(DDTrace_SpanLink, fromHeaders) {
bool success;
ddtrace_distributed_tracing_result result = dd_parse_distributed_tracing_headers_function(INTERNAL_FUNCTION_PARAM_PASSTHRU, &success);
if (!success) {
RETURN_NULL();
}
object_init_ex(return_value, ddtrace_ce_span_link);
ddtrace_span_link *link = (ddtrace_span_link *)Z_OBJ_P(return_value);
if (!get_DD_TRACE_ENABLED()) {
return;
}
ZVAL_STR(&link->property_trace_id, ddtrace_trace_id_as_hex_string(result.trace_id));
ZVAL_STR(&link->property_span_id, ddtrace_span_id_as_hex_string(result.parent_id));
array_init(&link->property_attributes);
zend_hash_copy(Z_ARR(link->property_attributes), &result.meta_tags, NULL);
zend_string *propagated_tags = ddtrace_format_propagated_tags(&result.propagated_tags, &result.meta_tags);
zend_string *full_tracestate = ddtrace_format_tracestate(result.tracestate, 0, result.origin, result.priority_sampling, propagated_tags, &result.tracestate_unknown_dd_keys);
zend_string_release(propagated_tags);
if (full_tracestate) {
ZVAL_STR(&link->property_trace_state, full_tracestate);
}
result.meta_tags.pDestructor = NULL; // we moved values directly
zend_hash_destroy(&result.meta_tags);
zend_hash_destroy(&result.propagated_tags);
zend_hash_destroy(&result.tracestate_unknown_dd_keys);
if (result.origin) {
zend_string_release(result.origin);
}
if (result.tracestate) {
zend_string_release(result.tracestate);
}
}
/* DDTrace\SpanData */
zend_class_entry *ddtrace_ce_span_data;
zend_class_entry *ddtrace_ce_root_span_data;
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80100
HashTable dd_root_span_data_duplicated_properties_table;
#endif
zend_class_entry *ddtrace_ce_span_stack;
zend_object_handlers ddtrace_span_data_handlers;
zend_object_handlers ddtrace_root_span_data_handlers;
zend_object_handlers ddtrace_span_stack_handlers;
static zend_object *dd_init_span_data_object(zend_class_entry *class_type, ddtrace_span_data *span, zend_object_handlers *handlers) {
zend_object_std_init(&span->std, class_type);
span->std.handlers = handlers;
object_properties_init(&span->std, class_type);
#if PHP_VERSION_ID < 80000
// Not handled in arginfo on these old versions
array_init(&span->property_meta);
array_init(&span->property_metrics);
array_init(&span->property_links);
array_init(&span->property_peer_service_sources);
#endif
// Explicitly assign property-mapped NULLs
span->stack = NULL;
span->parent = NULL;
return &span->std;
}
static zend_object *ddtrace_span_data_create(zend_class_entry *class_type) {
ddtrace_span_data *span = ecalloc(1, sizeof(*span));
return dd_init_span_data_object(class_type, span, &ddtrace_span_data_handlers);
}
static zend_object *ddtrace_root_span_data_create(zend_class_entry *class_type) {
ddtrace_root_span_data *span = ecalloc(1, sizeof(*span));
dd_init_span_data_object(class_type, &span->span, &ddtrace_root_span_data_handlers);
#if PHP_VERSION_ID < 80000
// Not handled in arginfo on these old versions
array_init(&span->property_propagated_tags);
array_init(&span->property_tracestate_tags);
#endif
return &span->std;
}
static zend_object *ddtrace_span_stack_create(zend_class_entry *class_type) {
ddtrace_span_stack *stack = ecalloc(1, sizeof(*stack));
zend_object_std_init(&stack->std, class_type);
stack->root_stack = stack;
stack->std.handlers = &ddtrace_span_stack_handlers;
object_properties_init(&stack->std, class_type);
// Explicitly assign property-mapped NULLs
stack->active = NULL;
stack->parent_stack = NULL;
return &stack->std;
}
// Init with empty span stack if directly allocated via new()
static zend_function *ddtrace_span_data_get_constructor(zend_object *object) {
object_init_ex(&OBJ_SPANDATA(object)->property_stack, ddtrace_ce_span_stack);
return NULL;
}
static void ddtrace_span_stack_dtor_obj(zend_object *object) {
// We must not invoke span stack destructors during zend_objects_store_call_destructors to avoid them not being present for appsec rshutdown
if (EG(current_execute_data) == NULL && !DDTRACE_G(in_shutdown)) {
GC_DEL_FLAGS(object, IS_OBJ_DESTRUCTOR_CALLED);
return;
}
ddtrace_span_stack *stack = (ddtrace_span_stack *)object;
ddtrace_span_data *top;
while (stack->active && (top = SPANDATA(stack->active)) && top->stack == stack) {
dd_trace_stop_span_time(top);
// let's not stack swap to a) avoid side effects in destructors and b) avoid a crash on PHP 7.3 and older
ddtrace_close_top_span_without_stack_swap(top);
}
if (stack->closed_ring || stack->closed_ring_flush) {
// ensure dtor can be called again
GC_DEL_FLAGS(object, IS_OBJ_DESTRUCTOR_CALLED);
}
zend_objects_destroy_object(object);
}
// span stacks have intrinsic properties (managing other spans, can be switched to), unlike trivial span data which are just value objects
// thus we need to cleanup a little what exactly we can copy
#if PHP_VERSION_ID < 80000
static zend_object *ddtrace_span_stack_clone_obj(zval *old_zv) {
zend_object *old_obj = Z_OBJ_P(old_zv);
#else
static zend_object *ddtrace_span_stack_clone_obj(zend_object *old_obj) {
#endif
zend_object *new_obj = ddtrace_span_stack_create(old_obj->ce);
zend_objects_clone_members(new_obj, old_obj);
ddtrace_span_stack *stack = (ddtrace_span_stack *)new_obj;
ddtrace_span_stack *oldstack = (ddtrace_span_stack *)old_obj;
if (oldstack->parent_stack) { // if this is false, we're copying an initial stack
stack->root_stack = stack->parent_stack->root_stack;
stack->root_span = stack->parent_stack->root_span;
}
if (oldstack->root_stack == oldstack) {
stack->root_stack = stack;
}
ddtrace_span_properties *pspan = stack->active;
zval_ptr_dtor(&stack->property_active);
while (pspan && pspan->stack == oldstack) {
pspan = pspan->parent;
}
if (pspan) {
ZVAL_OBJ_COPY(&stack->property_active, &pspan->std);
} else {
if (oldstack->root_span && oldstack->root_span->stack == oldstack) {
stack->root_span = NULL;
}
stack->active = NULL;
ZVAL_NULL(&stack->property_active);
}
return new_obj;
}
static void ddtrace_span_data_free_storage(zend_object *object) {
zend_object_std_dtor(object);
// Prevent use after free after zend_objects_store_free_object_storage is called (e.g. preloading) [PHP < 8.1]
memset(object->properties_table, 0, sizeof(ddtrace_span_data) - XtOffsetOf(ddtrace_span_data, std.properties_table));
}
#if PHP_VERSION_ID < 80000
static zend_object *ddtrace_span_data_clone_obj(zval *old_zv) {
zend_object *old_obj = Z_OBJ_P(old_zv);
#else
static zend_object *ddtrace_span_data_clone_obj(zend_object *old_obj) {
#endif
zend_object *new_obj = ddtrace_span_data_create(old_obj->ce);
zend_objects_clone_members(new_obj, old_obj);
return new_obj;
}
#if PHP_VERSION_ID < 80000
static zend_object *ddtrace_root_span_data_clone_obj(zval *old_zv) {
zend_object *old_obj = Z_OBJ_P(old_zv);
#else
static zend_object *ddtrace_root_span_data_clone_obj(zend_object *old_obj) {
#endif
zend_object *new_obj = ddtrace_root_span_data_create(old_obj->ce);
zend_objects_clone_members(new_obj, old_obj);
return new_obj;
}
#if PHP_VERSION_ID < 80000
#if PHP_VERSION_ID >= 70400
static zval *ddtrace_span_data_readonly(zval *object, zval *member, zval *value, void **cache_slot) {
#else
static void ddtrace_span_data_readonly(zval *object, zval *member, zval *value, void **cache_slot) {
#endif
zend_object *obj = Z_OBJ_P(object);
zend_string *prop_name = Z_TYPE_P(member) == IS_STRING ? Z_STR_P(member) : ZSTR_EMPTY_ALLOC();
#else
static zval *ddtrace_span_data_readonly(zend_object *object, zend_string *member, zval *value, void **cache_slot) {
zend_object *obj = object;
zend_string *prop_name = member;
#endif
if (zend_string_equals_literal(prop_name, "parent")
|| zend_string_equals_literal(prop_name, "id")
|| zend_string_equals_literal(prop_name, "stack")) {
zend_throw_error(zend_ce_error, "Cannot modify readonly property %s::$%s", ZSTR_VAL(obj->ce->name), ZSTR_VAL(prop_name));
#if PHP_VERSION_ID >= 70400
return &EG(uninitialized_zval);
#else
return;
#endif
}
#if PHP_VERSION_ID >= 70400
return zend_std_write_property(object, member, value, cache_slot);
#else
zend_std_write_property(object, member, value, cache_slot);
#endif
}
#if PHP_VERSION_ID < 80000
#if PHP_VERSION_ID >= 70400
static zval *ddtrace_root_span_data_write(zval *object, zval *member, zval *value, void **cache_slot) {
#else
static void ddtrace_root_span_data_write(zval *object, zval *member, zval *value, void **cache_slot) {
#endif
zend_object *obj = Z_OBJ_P(object);
zend_string *prop_name = Z_TYPE_P(member) == IS_STRING ? Z_STR_P(member) : ZSTR_EMPTY_ALLOC();
#else
static zval *ddtrace_root_span_data_write(zend_object *object, zend_string *member, zval *value, void **cache_slot) {
zend_object *obj = object;
zend_string *prop_name = member;
#endif
ddtrace_root_span_data *span = ROOTSPANDATA(obj);
zval zv;
if (zend_string_equals_literal(prop_name, "parentId")) {
if (Z_TYPE_P(value) == IS_LONG && Z_LVAL_P(value)) {
span->parent_id = (uint64_t) Z_LVAL_P(value);
ZVAL_STR(&zv, zend_strpprintf(0, "%" PRIu64, span->parent_id));
value = &zv;
} else {
span->parent_id = ddtrace_parse_userland_span_id(value);
if (!span->parent_id) {
ZVAL_EMPTY_STRING(&zv);
value = &zv;
}
}
} else if (zend_string_equals_literal(prop_name, "traceId")) {
span->trace_id = Z_TYPE_P(value) == IS_STRING ? ddtrace_parse_hex_trace_id(Z_STRVAL_P(value), Z_STRLEN_P(value)) : (ddtrace_trace_id){ 0 };
if (!span->trace_id.low && !span->trace_id.high) {
span->trace_id = (ddtrace_trace_id) {
.low = span->span_id,
.time = get_DD_TRACE_128_BIT_TRACEID_GENERATION_ENABLED() ? span->start / ZEND_NANO_IN_SEC : 0,
};
value = &span->property_id;
}
} else if (zend_string_equals_literal(prop_name, "samplingPriority")) {
span->explicit_sampling_priority = zval_get_long(value) != DDTRACE_PRIORITY_SAMPLING_UNKNOWN;
}
#if PHP_VERSION_ID >= 70400
return ddtrace_span_data_readonly(object, member, value, cache_slot);
#else
ddtrace_span_data_readonly(object, member, value, cache_slot);
#endif
}
#if PHP_VERSION_ID < 80000
#if PHP_VERSION_ID >= 70400
static zval *ddtrace_span_stack_readonly(zval *object, zval *member, zval *value, void **cache_slot) {
#else
static void ddtrace_span_stack_readonly(zval *object, zval *member, zval *value, void **cache_slot) {
#endif
zend_object *obj = Z_OBJ_P(object);
zend_string *prop_name = Z_TYPE_P(member) == IS_STRING ? Z_STR_P(member) : ZSTR_EMPTY_ALLOC();
#else
static zval *ddtrace_span_stack_readonly(zend_object *object, zend_string *member, zval *value, void **cache_slot) {
zend_object *obj = object;
zend_string *prop_name = member;
#endif
if (zend_string_equals_literal(prop_name, "parent")) {
zend_throw_error(zend_ce_error, "Cannot modify readonly property %s::$%s", ZSTR_VAL(obj->ce->name), ZSTR_VAL(prop_name));
#if PHP_VERSION_ID >= 70400
return &EG(uninitialized_zval);
#else
return;
#endif
}
#if PHP_VERSION_ID >= 70400
return zend_std_write_property(object, member, value, cache_slot);
#else
zend_std_write_property(object, member, value, cache_slot);
#endif
}
PHP_METHOD(DDTrace_SpanData, getDuration) {
ddtrace_span_data *span = OBJ_SPANDATA(Z_OBJ_P(ZEND_THIS));
RETURN_LONG(span->duration);
}
PHP_METHOD(DDTrace_SpanData, getStartTime) {
ddtrace_span_data *span = OBJ_SPANDATA(Z_OBJ_P(ZEND_THIS));
RETURN_LONG(span->start);
}
PHP_METHOD(DDTrace_SpanData, getLink) {
ddtrace_span_data *span = OBJ_SPANDATA(Z_OBJ_P(ZEND_THIS));
zval fci_zv;
object_init_ex(&fci_zv, ddtrace_ce_span_link);
ddtrace_span_link *link = (ddtrace_span_link *)Z_OBJ_P(&fci_zv);
ZVAL_STR(&link->property_trace_id, ddtrace_trace_id_as_hex_string(span->root ? span->root->trace_id : (ddtrace_trace_id){ .low = span->span_id, .high = 0 }));
ZVAL_STR(&link->property_span_id, ddtrace_span_id_as_hex_string(span->span_id));
RETURN_OBJ(Z_OBJ(fci_zv));
}
PHP_METHOD(DDTrace_SpanData, hexId) {
ddtrace_span_data *span = OBJ_SPANDATA(Z_OBJ_P(ZEND_THIS));
RETURN_STR(ddtrace_span_id_as_hex_string(span->span_id));
}
static void dd_register_span_data_ce(void) {
ddtrace_ce_span_data = register_class_DDTrace_SpanData();
ddtrace_ce_span_data->create_object = ddtrace_span_data_create;
memcpy(&ddtrace_span_data_handlers, &std_object_handlers, sizeof(zend_object_handlers));
ddtrace_span_data_handlers.offset = XtOffsetOf(ddtrace_span_data, std);
ddtrace_span_data_handlers.clone_obj = ddtrace_span_data_clone_obj;
ddtrace_span_data_handlers.free_obj = ddtrace_span_data_free_storage;
ddtrace_span_data_handlers.write_property = ddtrace_span_data_readonly;
ddtrace_span_data_handlers.get_constructor = ddtrace_span_data_get_constructor;
ddtrace_ce_root_span_data = register_class_DDTrace_RootSpanData(ddtrace_ce_span_data);
ddtrace_ce_root_span_data->create_object = ddtrace_root_span_data_create;
#if PHP_VERSION_ID >= 80000 && PHP_VERSION_ID < 80100
// Work around wrong reference source for typed internal properties by preventing duplication of them
// php -d extension=zend_test -r '$c = new _ZendTestChildClass; $i = &$c->intProp;'
// php: /usr/local/src/php/Zend/zend_execute.c:3390: zend_ref_del_type_source: Assertion `source_list->ptr == prop' failed.
zend_hash_init(&dd_root_span_data_duplicated_properties_table, zend_hash_num_elements(&ddtrace_ce_span_data->properties_info), NULL, NULL, true);
for (uint32_t i = 0; i < zend_hash_num_elements(&ddtrace_ce_span_data->properties_info); ++i) {
Bucket *bucket = &ddtrace_ce_root_span_data->properties_info.arData[i];
zend_hash_add_ptr(&dd_root_span_data_duplicated_properties_table, bucket->key, Z_PTR(bucket->val));
Z_PTR(bucket->val) = ddtrace_ce_root_span_data->properties_info_table[i] = Z_PTR(ddtrace_ce_span_data->properties_info.arData[i].val);
}
#endif
memcpy(&ddtrace_root_span_data_handlers, &ddtrace_span_data_handlers, sizeof(zend_object_handlers));
ddtrace_root_span_data_handlers.offset = XtOffsetOf(ddtrace_root_span_data, std);
ddtrace_root_span_data_handlers.clone_obj = ddtrace_root_span_data_clone_obj;
ddtrace_root_span_data_handlers.write_property = ddtrace_root_span_data_write;
ddtrace_ce_span_stack = register_class_DDTrace_SpanStack();
ddtrace_ce_span_stack->create_object = ddtrace_span_stack_create;
memcpy(&ddtrace_span_stack_handlers, &std_object_handlers, sizeof(zend_object_handlers));
ddtrace_span_stack_handlers.clone_obj = ddtrace_span_stack_clone_obj;
ddtrace_span_stack_handlers.dtor_obj = ddtrace_span_stack_dtor_obj;
ddtrace_span_stack_handlers.write_property = ddtrace_span_stack_readonly;
}
/* DDTrace\FatalError */
zend_class_entry *ddtrace_ce_fatal_error;
static void dd_register_fatal_error_ce(void) {
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "DDTrace", "FatalError", NULL);
ddtrace_ce_fatal_error = zend_register_internal_class_ex(&ce, zend_ce_exception);
}
static bool dd_is_compatible_sapi() {
switch (ddtrace_active_sapi) {
case DATADOG_PHP_SAPI_APACHE2HANDLER:
case DATADOG_PHP_SAPI_CGI_FCGI: