-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathqafooprofiler.c
3401 lines (2815 loc) · 92.3 KB
/
qafooprofiler.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
/*
* Copyright (c) 2009 Facebook
* Copyright (c) 2014 Qafoo GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef linux
/* To enable CPU_ZERO and CPU_SET, etc. */
# define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/file.h"
#include "php_qafooprofiler.h"
#include "zend_extensions.h"
#include "zend_gc.h"
#include "ext/pcre/php_pcre.h"
#include "ext/standard/url.h"
#include "ext/pdo/php_pdo_driver.h"
#include "zend_exceptions.h"
#include "zend_stream.h"
#ifdef PHP_QAFOOPROFILER_HAVE_CURL
#if PHP_VERSION_ID > 50399
#include <curl/curl.h>
#include <curl/easy.h>
#endif
#endif
#ifdef __FreeBSD__
# if __FreeBSD_version >= 700110
# include <sys/cpuset.h>
# define cpu_set_t cpuset_t
# define SET_AFFINITY(pid, size, mask) \
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, size, mask)
# define GET_AFFINITY(pid, size, mask) \
cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, size, mask)
# else
# error "This version of FreeBSD does not support cpusets"
# endif /* __FreeBSD_version */
#elif __APPLE__
/*
* Patch for compiling in Mac OS X Leopard
* @author Svilen Spasov <[email protected]>
*/
# include <mach/mach_init.h>
# include <mach/thread_policy.h>
# include <mach/mach_time.h>
# define cpu_set_t thread_affinity_policy_data_t
# define CPU_SET(cpu_id, new_mask) \
(*(new_mask)).affinity_tag = (cpu_id + 1)
# define CPU_ZERO(new_mask) \
(*(new_mask)).affinity_tag = THREAD_AFFINITY_TAG_NULL
# define SET_AFFINITY(pid, size, mask) \
thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY, mask, \
THREAD_AFFINITY_POLICY_COUNT)
#else
/* For sched_getaffinity, sched_setaffinity */
# include <sched.h>
# define SET_AFFINITY(pid, size, mask) sched_setaffinity(0, size, mask)
# define GET_AFFINITY(pid, size, mask) sched_getaffinity(0, size, mask)
#endif /* __FreeBSD__ */
/**
* **********************
* GLOBAL MACRO CONSTANTS
* **********************
*/
/* Qafoo Profiler version */
#define QAFOOPROFILER_VERSION "1.3.7"
/* Fictitious function name to represent top of the call tree. The paranthesis
* in the name is to ensure we don't conflict with user function names. */
#define ROOT_SYMBOL "main()"
/* Size of a temp scratch buffer */
#define SCRATCH_BUF_LEN 512
/* Various QAFOOPROFILER modes. If you are adding a new mode, register the appropriate
* callbacks in hp_begin() */
#define QAFOOPROFILER_MODE_HIERARCHICAL 1
#define QAFOOPROFILER_MODE_SAMPLED 620002 /* Rockfort's zip code */
#define QAFOOPROFILER_MODE_LAYER 2
/* Hierarchical profiling flags.
*
* Note: Function call counts and wall (elapsed) time are always profiled.
* The following optional flags can be used to control other aspects of
* profiling.
*/
#define QAFOOPROFILER_FLAGS_NO_BUILTINS 0x0001 /* do not profile builtins */
#define QAFOOPROFILER_FLAGS_CPU 0x0002 /* gather CPU times for funcs */
#define QAFOOPROFILER_FLAGS_MEMORY 0x0004 /* gather memory usage for funcs */
#define QAFOOPROFILER_FLAGS_NO_USERLAND 0x0008 /* do not profile userland functions */
/* Constants for QAFOOPROFILER_MODE_SAMPLED */
#define QAFOOPROFILER_SAMPLING_INTERVAL 100000 /* In microsecs */
/* Constant for ignoring functions, transparent to hierarchical profile */
#define QAFOOPROFILER_MAX_FILTERED_FUNCTIONS 256
#define QAFOOPROFILER_FILTERED_FUNCTION_SIZE \
((QAFOOPROFILER_MAX_FILTERED_FUNCTIONS + 7)/8)
#define QAFOOPROFILER_MAX_ARGUMENT_LEN 256
#if !defined(uint64)
typedef unsigned long long uint64;
#endif
#if !defined(uint32)
typedef unsigned int uint32;
#endif
#if !defined(uint8)
typedef unsigned char uint8;
#endif
/**
* *****************************
* GLOBAL DATATYPES AND TYPEDEFS
* *****************************
*/
/* Qafoo Profiler maintains a stack of entries being profiled. The memory for the entry
* is passed by the layer that invokes BEGIN_PROFILING(), e.g. the hp_execute()
* function. Often, this is just C-stack memory.
*
* This structure is a convenient place to track start time of a particular
* profile operation, recursion depth, and the name of the function being
* profiled. */
typedef struct hp_entry_t {
char *name_hprof; /* function name */
int rlvl_hprof; /* recursion level for function */
uint64 tsc_start; /* start value for TSC counter */
long int mu_start_hprof; /* memory usage */
long int pmu_start_hprof; /* peak memory usage */
struct rusage ru_start_hprof; /* user/sys time start */
struct hp_entry_t *prev_hprof; /* ptr to prev entry being profiled */
uint8 hash_code; /* hash_code for the function name */
zend_uint gc_runs; /* number of garbage collection runs */
zend_uint gc_collected; /* number of collected items in garbage run */
} hp_entry_t;
/* Various types for QAFOOPROFILER callbacks */
typedef void (*hp_init_cb) (TSRMLS_D);
typedef void (*hp_exit_cb) (TSRMLS_D);
typedef void (*hp_begin_function_cb) (hp_entry_t **entries,
hp_entry_t *current TSRMLS_DC);
typedef void (*hp_end_function_cb) (hp_entry_t **entries TSRMLS_DC);
/* Struct to hold the various callbacks for a single profiling mode */
typedef struct hp_mode_cb {
hp_init_cb init_cb;
hp_exit_cb exit_cb;
hp_begin_function_cb begin_fn_cb;
hp_end_function_cb end_fn_cb;
} hp_mode_cb;
typedef struct hp_string {
char *value;
size_t length;
} hp_string;
/* Struct that defines caught errors or exceptions inside the engine. */
typedef struct hp_error {
unsigned int line;
hp_string *file;
hp_string *message;
hp_string *trace;
unsigned int type;
long code;
hp_string *class;
} hp_error;
typedef struct hp_function_map {
char **names;
uint8 filter[QAFOOPROFILER_FILTERED_FUNCTION_SIZE];
} hp_function_map;
/* Qafoo Profiler's global state.
*
* This structure is instantiated once. Initialize defaults for attributes in
* hp_init_profiler_state() Cleanup/free attributes in
* hp_clean_profiler_state() */
typedef struct hp_global_t {
/* ---------- Global attributes: ----------- */
/* Indicates if Qafoo Profiler is currently enabled */
int enabled;
/* Indicates if Qafoo Profiler was ever enabled during this request */
int ever_enabled;
/* Holds all information about layer profiling */
zval *layers_count;
/* A key=>value list of function calls to their respective layers. */
HashTable *layers_definition;
/* Holds all the Qafoo Profiler statistics */
zval *stats_count;
/* Holds all the information about last error. */
hp_error *last_error;
/* Holds the last exception */
hp_error *last_exception;
/* Indicates the current Qafoo Profiler mode or level */
int profiler_level;
/* Top of the profile stack */
hp_entry_t *entries;
/* freelist of hp_entry_t chunks for reuse... */
hp_entry_t *entry_free_list;
/* Callbacks for various Qafoo Profiler modes */
hp_mode_cb mode_cb;
/* Function that determines the transaction name and callback */
hp_string *transaction_function;
hp_string *transaction_name;
char *root;
/* ---------- Mode specific attributes: ----------- */
/* Global to track the time of the last sample in time and ticks */
struct timeval last_sample_time;
uint64 last_sample_tsc;
/* QAFOOPROFILER_SAMPLING_INTERVAL in ticks */
uint64 sampling_interval_tsc;
/* This array is used to store cpu frequencies for all available logical
* cpus. For now, we assume the cpu frequencies will not change for power
* saving or other reasons. If we need to worry about that in the future, we
* can use a periodical timer to re-calculate this arrary every once in a
* while (for example, every 1 or 5 seconds). */
double *cpu_frequencies;
/* The number of logical CPUs this machine has. */
uint32 cpu_num;
int invariant_tsc;
/* The saved cpu affinity. */
cpu_set_t prev_mask;
/* The cpu id current process is bound to. (default 0) */
uint32 cur_cpu_id;
/* Qafoo Profiler flags */
uint32 qafooprofiler_flags;
/* counter table indexed by hash value of function names. */
uint8 func_hash_counters[256];
/* Table of filtered function names and their filter */
int filtered_type; // 1 = blacklist, 2 = whitelist, 0 = nothing
hp_function_map *filtered_functions;
hp_function_map *argument_functions;
hp_function_map *trace_functions;
/* Table of functions which allow custom tracing */
char **trace_function_names;
uint8 trace_function_filter[QAFOOPROFILER_FILTERED_FUNCTION_SIZE];
} hp_global_t;
#ifdef PHP_QAFOOPROFILER_HAVE_CURL
#if PHP_VERSION_ID > 50399
typedef struct hp_curl_t {
struct {
char str[CURL_ERROR_SIZE + 1];
int no;
} err;
void *free;
struct {
char *str;
size_t str_len;
} hdr;
void ***thread_ctx;
CURL *cp;
} hp_curl_t;
#endif
#endif
/**
* ***********************
* GLOBAL STATIC VARIABLES
* ***********************
*/
/* Qafoo Profiler global state */
static hp_global_t hp_globals;
#if PHP_VERSION_ID < 50500
/* Pointer to the original execute function */
static ZEND_DLEXPORT void (*_zend_execute) (zend_op_array *ops TSRMLS_DC);
/* Pointer to the origianl execute_internal function */
static ZEND_DLEXPORT void (*_zend_execute_internal) (zend_execute_data *data,
int ret TSRMLS_DC);
#else
/* Pointer to the original execute function */
static void (*_zend_execute_ex) (zend_execute_data *execute_data TSRMLS_DC);
/* Pointer to the origianl execute_internal function */
static void (*_zend_execute_internal) (zend_execute_data *data,
struct _zend_fcall_info *fci, int ret TSRMLS_DC);
#endif
/* Pointer to the original compile function */
static zend_op_array * (*_zend_compile_file) (zend_file_handle *file_handle,
int type TSRMLS_DC);
/* Pointer to the original compile string function (used by eval) */
static zend_op_array * (*_zend_compile_string) (zval *source_string, char *filename TSRMLS_DC);
/* error callback replacement functions */
void (*qafooprofiler_original_error_cb)(int type, const char *error_filename, const uint error_lineno, const char *format, va_list args);
void qafooprofiler_error_cb(int type, const char *error_filename, const uint error_lineno, const char *format, va_list args);
static void qafooprofiler_throw_exception_hook(zval *exception TSRMLS_DC);
/* Bloom filter for function names to be ignored */
#define INDEX_2_BYTE(index) (index >> 3)
#define INDEX_2_BIT(index) (1 << (index & 0x7));
/**
* ****************************
* STATIC FUNCTION DECLARATIONS
* ****************************
*/
static void hp_register_constants(INIT_FUNC_ARGS);
static void hp_begin(long level, long qafooprofiler_flags TSRMLS_DC);
static void hp_stop(TSRMLS_D);
static void hp_end(TSRMLS_D);
static inline uint64 cycle_timer();
static double get_cpu_frequency();
static void clear_frequencies();
static int is_invariant_tsc();
static void hp_free_the_free_list();
static hp_entry_t *hp_fast_alloc_hprof_entry();
static void hp_fast_free_hprof_entry(hp_entry_t *p);
static inline uint8 hp_inline_hash(char * str);
static void get_all_cpu_frequencies();
static long get_us_interval(struct timeval *start, struct timeval *end);
static void incr_us_interval(struct timeval *start, uint64 incr);
static void hp_parse_options_from_arg(zval *args);
static void hp_parse_layers_options_from_arg(zval *layers);
static void hp_clean_profiler_options_state();
static void hp_transaction_function_clear();
static void hp_transaction_name_clear();
static inline zval *hp_zval_at_key(char *key, zval *values);
static inline char **hp_strings_in_zval(zval *values);
static inline void hp_array_del(char **name_array);
static inline int hp_argument_entry(uint8 hash_code, char *curr_func);
static inline hp_string *hp_create_string(const char *value, size_t length);
static inline long hp_zval_to_long(zval *z);
static inline hp_string *hp_zval_to_string(zval *z);
static inline zval *hp_string_to_zval(hp_string *str);
static inline void hp_string_clean(hp_string *str);
static inline hp_function_map *hp_function_map_create(char **names);
static inline void hp_function_map_clear(hp_function_map *map);
static inline int hp_function_map_exists(hp_function_map *map, uint8 hash_code, char *curr_func);
static inline int hp_function_map_filter_collision(hp_function_map *map, uint8 hash);
static hp_string *qafooprofiler_backtrace(TSRMLS_D);
static void hp_error_clean(hp_error *error);
static void hp_error_to_zval(hp_error *error, zval *z);
static hp_error *hp_error_create();
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_qafooprofiler_enable, 0, 0, 0)
ZEND_ARG_INFO(0, flags)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_disable, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_transaction_name, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_last_fatal_error, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_last_exception_data, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_sample_enable, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_qafooprofiler_layers_enable, 0)
ZEND_ARG_INFO(0, layers)
ZEND_ARG_INFO(0, transaction_function)
ZEND_END_ARG_INFO()
/* }}} */
/**
* *********************
* FUNCTION PROTOTYPES
* *********************
*/
int restore_cpu_affinity(cpu_set_t * prev_mask);
int bind_to_cpu(uint32 cpu_id);
/**
* *********************
* PHP EXTENSION GLOBALS
* *********************
*/
/* List of functions implemented/exposed by Qafoo Profiler */
zend_function_entry qafooprofiler_functions[] = {
PHP_FE(qafooprofiler_enable, arginfo_qafooprofiler_enable)
PHP_FE(qafooprofiler_disable, arginfo_qafooprofiler_disable)
PHP_FE(qafooprofiler_transaction_name, arginfo_qafooprofiler_transaction_name)
PHP_FE(qafooprofiler_last_fatal_error, arginfo_qafooprofiler_last_fatal_error)
PHP_FE(qafooprofiler_last_exception_data, arginfo_qafooprofiler_last_exception_data)
PHP_FE(qafooprofiler_sample_enable, arginfo_qafooprofiler_sample_enable)
PHP_FE(qafooprofiler_layers_enable, arginfo_qafooprofiler_layers_enable)
{NULL, NULL, NULL}
};
/* Callback functions for the Qafoo Profiler extension */
zend_module_entry qafooprofiler_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"qafooprofiler", /* Name of the extension */
qafooprofiler_functions, /* List of functions exposed */
PHP_MINIT(qafooprofiler), /* Module init callback */
PHP_MSHUTDOWN(qafooprofiler), /* Module shutdown callback */
PHP_RINIT(qafooprofiler), /* Request init callback */
PHP_RSHUTDOWN(qafooprofiler), /* Request shutdown callback */
PHP_MINFO(qafooprofiler), /* Module info callback */
#if ZEND_MODULE_API_NO >= 20010901
QAFOOPROFILER_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};
PHP_INI_BEGIN()
/**
* INI-Settings are always used by the extension, but by the PHP library.
*/
PHP_INI_ENTRY("qafooprofiler.connection", "unix:///tmp/qprofd.sock", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.udp_connection", "127.0.0.1:8135", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.auto_start", "1", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.api_key", "", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.transaction_function", "", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.sample_rate", "10", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("qafooprofiler.load_library", "1", PHP_INI_ALL, NULL)
PHP_INI_END()
/* Init module */
ZEND_GET_MODULE(qafooprofiler)
/**
* **********************************
* PHP EXTENSION FUNCTION DEFINITIONS
* **********************************
*/
/**
* Start Qafoo Profiler profiling in hierarchical mode.
*
* @param long $flags flags for hierarchical mode
* @return void
* @author kannan
*/
PHP_FUNCTION(qafooprofiler_enable)
{
long qafooprofiler_flags = 0; /* Qafoo PRofiler flags */
zval *optional_array = NULL; /* optional array arg: for future use */
if (hp_globals.enabled) {
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
"|lz", &qafooprofiler_flags, &optional_array) == FAILURE) {
return;
}
hp_parse_options_from_arg(optional_array);
hp_begin(QAFOOPROFILER_MODE_HIERARCHICAL, qafooprofiler_flags TSRMLS_CC);
}
PHP_FUNCTION(qafooprofiler_last_fatal_error)
{
if (hp_globals.enabled && hp_globals.last_error) {
hp_error_to_zval(hp_globals.last_error, return_value);
}
}
PHP_FUNCTION(qafooprofiler_last_exception_data)
{
if (hp_globals.enabled && hp_globals.last_exception) {
hp_error_to_zval(hp_globals.last_exception, return_value);
}
}
/**
* Start Qafoo Profiler in sampling mode.
*
* @return void
* @author cjiang
*/
PHP_FUNCTION(qafooprofiler_sample_enable)
{
long qafooprofiler_flags = 0; /* Qafoo Profiler flags */
hp_parse_options_from_arg(NULL);
hp_begin(QAFOOPROFILER_MODE_SAMPLED, qafooprofiler_flags TSRMLS_CC);
}
/**
* Start Qafoo Profiler profiling in layers mode.
*/
PHP_FUNCTION(qafooprofiler_layers_enable)
{
long qafooprofiler_flags = QAFOOPROFILER_FLAGS_NO_USERLAND;
zval *layers, *transaction_function = NULL;
if (hp_globals.enabled) {
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &layers, &transaction_function) == FAILURE) {
return;
}
if (layers == NULL || Z_TYPE_P(layers) != IS_ARRAY) {
zend_error(E_NOTICE, "qafooprofiler_layers_enable() requires first argument to be array");
return;
}
if (transaction_function != NULL && Z_TYPE_P(transaction_function) == IS_STRING) {
hp_globals.transaction_function = hp_zval_to_string(transaction_function);
}
if (zend_hash_num_elements(Z_ARRVAL_P(layers)) == 0) {
qafooprofiler_flags = QAFOOPROFILER_FLAGS_NO_USERLAND | QAFOOPROFILER_FLAGS_NO_BUILTINS;
}
hp_clean_profiler_options_state();
hp_parse_layers_options_from_arg(layers);
hp_globals.filtered_type = 2;
hp_globals.filtered_functions = hp_function_map_create(hp_strings_in_zval(layers));
hp_begin(QAFOOPROFILER_MODE_LAYER, qafooprofiler_flags TSRMLS_CC);
}
/**
* Stops Qafoo Profiler from profiling and returns the profile info.
*
* @param void
* @return array hash-array of Qafoo Profiler's profile info
* @author cjiang
*/
PHP_FUNCTION(qafooprofiler_disable)
{
zval *tmp, *value;
void *data;
if (!hp_globals.enabled) {
return;
}
hp_stop(TSRMLS_C);
if (hp_globals.profiler_level == QAFOOPROFILER_MODE_LAYER) {
if (zend_hash_find(Z_ARRVAL_P(hp_globals.stats_count), ROOT_SYMBOL, strlen(ROOT_SYMBOL) + 1, &data) == SUCCESS) {
tmp = *(zval **) data;
add_assoc_zval(hp_globals.layers_count, "main()", tmp);
}
RETURN_ZVAL(hp_globals.layers_count, 1, 0);
}
if (hp_globals.profiler_level == QAFOOPROFILER_MODE_HIERARCHICAL) {
if (hp_globals.layers_count) {
if (zend_hash_find(Z_ARRVAL_P(hp_globals.stats_count), ROOT_SYMBOL, strlen(ROOT_SYMBOL) + 1, &data) == SUCCESS) {
tmp = *(zval **) data;
MAKE_STD_ZVAL(value);
ZVAL_ZVAL(value, hp_globals.layers_count, 1, 0);
add_assoc_zval(tmp, "layers", value);
}
}
RETURN_ZVAL(hp_globals.stats_count, 1, 0);
}
if (hp_globals.profiler_level == QAFOOPROFILER_MODE_SAMPLED) {
RETURN_ZVAL(hp_globals.stats_count, 1, 0);
}
}
PHP_FUNCTION(qafooprofiler_transaction_name)
{
if (hp_globals.transaction_name) {
zval *ret = hp_string_to_zval(hp_globals.transaction_name);
RETURN_ZVAL(ret, 1, 1);
}
}
/**
* Module init callback.
*
* @author cjiang
*/
PHP_MINIT_FUNCTION(qafooprofiler)
{
int i;
REGISTER_INI_ENTRIES();
hp_register_constants(INIT_FUNC_ARGS_PASSTHRU);
/* Get the number of available logical CPUs. */
hp_globals.cpu_num = sysconf(_SC_NPROCESSORS_CONF);
hp_globals.invariant_tsc = is_invariant_tsc();
/* Get the cpu affinity mask. */
#ifndef __APPLE__
if (GET_AFFINITY(0, sizeof(cpu_set_t), &hp_globals.prev_mask) < 0) {
perror("getaffinity");
return FAILURE;
}
#else
CPU_ZERO(&(hp_globals.prev_mask));
#endif
/* Initialize cpu_frequencies and cur_cpu_id. */
hp_globals.cpu_frequencies = NULL;
hp_globals.cur_cpu_id = 0;
hp_globals.stats_count = NULL;
hp_globals.last_error = NULL;
hp_globals.last_exception = NULL;
/* no free hp_entry_t structures to start with */
hp_globals.entry_free_list = NULL;
for (i = 0; i < 256; i++) {
hp_globals.func_hash_counters[i] = 0;
}
hp_transaction_function_clear();
#if defined(DEBUG)
/* To make it random number generator repeatable to ease testing. */
srand(0);
#endif
return SUCCESS;
}
/**
* Module shutdown callback.
*/
PHP_MSHUTDOWN_FUNCTION(qafooprofiler)
{
/* Make sure cpu_frequencies is free'ed. */
clear_frequencies();
/* free any remaining items in the free list */
hp_free_the_free_list();
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/**
* Request init callback.
*
* Check if QafooProfiler.php exists in extension_dir and load it
* in request init. This makes class \QafooLabs\Profiler available
* for usage.
*/
PHP_RINIT_FUNCTION(qafooprofiler)
{
if (INI_INT("qafooprofiler.load_library") == 0) {
return SUCCESS;
}
// See https://github.com/xdebug/xdebug/pull/131
const char *version = zend_get_module_version("xdebug");
if (version != NULL && php_version_compare(version, "2.2.7") < 0) {
return SUCCESS;
}
zend_file_handle file_handle;
zend_op_array *new_op_array;
zval *result = NULL;
int ret;
int dummy = 1;
char *extension_dir = INI_STR("extension_dir");
char *profiler_file;
int profiler_file_len;
profiler_file_len = strlen(extension_dir) + strlen("QafooProfiler.php") + 2;
profiler_file = emalloc(profiler_file_len);
snprintf(profiler_file, profiler_file_len, "%s/%s", extension_dir, "QafooProfiler.php");
ret = php_stream_open_for_zend_ex(profiler_file, &file_handle, STREAM_OPEN_FOR_INCLUDE TSRMLS_CC);
if (ret == SUCCESS) {
// This code is partially copied from php_execute_script
if (PG(max_input_time) != -1) {
#ifdef PHP_WIN32
zend_unset_timeout(TSRMLS_C);
#endif
zend_set_timeout(INI_INT("max_execution_time"), 0);
}
zend_try {
zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 1, &file_handle);
} zend_catch {
php_log_err("qafooprofiler.so: Error during execution of auto start script QafooProfiler.php - Skipping" TSRMLS_CC);
} zend_end_try();
}
efree(profiler_file);
return SUCCESS;
}
/**
* Request shutdown callback. Stop profiling and return.
*/
PHP_RSHUTDOWN_FUNCTION(qafooprofiler)
{
hp_end(TSRMLS_C);
return SUCCESS;
}
/**
* Module info callback. Returns the Qafoo Profiler version.
*/
PHP_MINFO_FUNCTION(qafooprofiler)
{
char buf[SCRATCH_BUF_LEN];
char tmp[SCRATCH_BUF_LEN];
int i;
int len;
int found = 0;
php_info_print_table_start();
php_info_print_table_header(2, "qafooprofiler", QAFOOPROFILER_VERSION);
php_info_print_table_row(2, "TSC Invariant", is_invariant_tsc() ? "Yes" : "No");
len = snprintf(buf, SCRATCH_BUF_LEN, "%d", hp_globals.cpu_num);
buf[len] = 0;
php_info_print_table_header(2, "CPU num", buf);
if (hp_globals.cpu_frequencies) {
/* Print available cpu frequencies here. */
php_info_print_table_header(2, "CPU logical id", " Clock Rate (MHz) ");
for (i = 0; i < hp_globals.cpu_num; ++i) {
len = snprintf(buf, SCRATCH_BUF_LEN, " CPU %d ", i);
buf[len] = 0;
len = snprintf(tmp, SCRATCH_BUF_LEN, "%f", hp_globals.cpu_frequencies[i]);
tmp[len] = 0;
php_info_print_table_row(2, buf, tmp);
}
}
php_info_print_table_row(2, "Connection (qafooprofiler.connection)", INI_STR("qafooprofiler.connection"));
php_info_print_table_row(2, "UDP Connection (qafooprofiler.udp_connection)", INI_STR("qafooprofiler.udp_connection"));
php_info_print_table_row(2, "Default API Key (qafooprofiler.api_key)", INI_STR("qafooprofiler.api_key"));
php_info_print_table_row(2, "Default Sample-Rate (qafooprofiler.sample_rate)", INI_STR("qafooprofiler.sample_rate"));
php_info_print_table_row(2, "Default Transaction Function (qafooprofiler.transaction_function)", INI_STR("qafooprofiler.transaction_function"));
php_info_print_table_row(2, "Automatically Start (qafooprofiler.auto_start)", INI_INT("qafooprofiler.auto_start") ? "Yes": "No");
php_info_print_table_row(2, "Load PHP Library (qafooprofiler.load_library)", INI_INT("qafooprofiler.load_library") ? "Yes": "No");
const char *version = zend_get_module_version("xdebug");
if (found != 0 && version != NULL && php_version_compare(version, "2.2.7") < 0 && INI_INT("qafooprofiler.load_library") != 0) {
php_info_print_table_row(1, "Incompatible Xdebug version prevents loading library automatically! At least Xdebug version 2.2.7 required.");
}
php_info_print_table_end();
}
/**
* ***************************************************
* COMMON HELPER FUNCTION DEFINITIONS AND LOCAL MACROS
* ***************************************************
*/
static void hp_register_constants(INIT_FUNC_ARGS)
{
REGISTER_LONG_CONSTANT("QAFOOPROFILER_FLAGS_NO_BUILTINS",
QAFOOPROFILER_FLAGS_NO_BUILTINS,
CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("QAFOOPROFILER_FLAGS_CPU",
QAFOOPROFILER_FLAGS_CPU,
CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("QAFOOPROFILER_FLAGS_MEMORY",
QAFOOPROFILER_FLAGS_MEMORY,
CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("QAFOOPROFILER_FLAGS_NO_USERLAND",
QAFOOPROFILER_FLAGS_NO_USERLAND,
CONST_CS | CONST_PERSISTENT);
}
/**
* A hash function to calculate a 8-bit hash code for a function name.
* This is based on a small modification to 'zend_inline_hash_func' by summing
* up all bytes of the ulong returned by 'zend_inline_hash_func'.
*
* @param str, char *, string to be calculated hash code for.
*
* @author cjiang
*/
static inline uint8 hp_inline_hash(char * arKey)
{
size_t nKeyLength = strlen(arKey);
register uint8 hash = 0;
/* variant with the hash unrolled eight times */
for (; nKeyLength >= 8; nKeyLength -= 8) {
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
}
switch (nKeyLength) {
case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 5: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 2: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
case 1: hash = ((hash << 5) + hash) + *arKey++; break;
case 0: break;
EMPTY_SWITCH_DEFAULT_CASE()
}
return hash;
}
static void hp_parse_layers_options_from_arg(zval *layers)
{
if (layers == NULL || Z_TYPE_P(layers) != IS_ARRAY) {
return;
}
HashTable *ht;
zval *tmp;
ALLOC_HASHTABLE(hp_globals.layers_definition);
zend_hash_init(hp_globals.layers_definition, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_copy(
hp_globals.layers_definition,
Z_ARRVAL_P(layers),
(copy_ctor_func_t)zval_add_ref,
(void*)&tmp,
sizeof(zval *)
);
}
/**
* Parse the list of ignored functions from the zval argument.
*
* @author mpal
*/
static void hp_parse_options_from_arg(zval *args)
{
hp_clean_profiler_options_state();
if (args == NULL) {
return;
}
zval *zresult = NULL;
zresult = hp_zval_at_key("ignored_functions", args);
if (zresult == NULL) {
zresult = hp_zval_at_key("functions", args);
if (zresult != NULL) {
hp_globals.filtered_type = 2;
}
} else {
hp_globals.filtered_type = 1;
}
hp_globals.filtered_functions = hp_function_map_create(hp_strings_in_zval(zresult));
zresult = hp_zval_at_key("argument_functions", args);
hp_globals.argument_functions = hp_function_map_create(hp_strings_in_zval(zresult));
zresult = hp_zval_at_key("layers", args);
hp_parse_layers_options_from_arg(zresult);
zresult = hp_zval_at_key("transaction_function", args);
if (zresult != NULL) {
hp_globals.transaction_function = hp_zval_to_string(zresult);
}
}
static void hp_transaction_function_clear() {
if (hp_globals.transaction_function) {
hp_string_clean(hp_globals.transaction_function);
efree(hp_globals.transaction_function);
hp_globals.transaction_function = NULL;
}
}
static inline hp_function_map *hp_function_map_create(char **names)
{
if (names == NULL) {
return NULL;
}
hp_function_map *map;
map = emalloc(sizeof(hp_function_map));
map->names = names;
memset(map->filter, 0, QAFOOPROFILER_FILTERED_FUNCTION_SIZE);
int i = 0;
for(; names[i] != NULL; i++) {
char *str = names[i];
uint8 hash = hp_inline_hash(str);
int idx = INDEX_2_BYTE(hash);
map->filter[idx] |= INDEX_2_BIT(hash);
}
return map;
}
static inline void hp_function_map_clear(hp_function_map *map) {
if (map == NULL) {
return;
}
hp_array_del(map->names);
map->names = NULL;
memset(map->filter, 0, QAFOOPROFILER_FILTERED_FUNCTION_SIZE);
efree(map);
}
static inline int hp_function_map_exists(hp_function_map *map, uint8 hash_code, char *curr_func)
{