/
00-dtrace.patch
2045 lines (1999 loc) · 63.2 KB
/
00-dtrace.patch
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
This patch comes from upstream:
http://www.jcea.es/artic/python_dtrace-3_4_0_0de6441eedb7.txt
http://www.jcea.es/artic/python_dtrace.htm
Follow http://bugs.python.org/issue13405 for plans to get it
integrated into the main tree.
--- Python-3.5.6/Doc/library/debug.rst 2018-08-02 02:19:12.000000000 +0000
+++ Python-3.5.6/Doc/library/debug.rst 2019-01-07 04:41:11.643829820 +0000
@@ -15,4 +15,5 @@ allowing you to identify bottlenecks in
profile.rst
timeit.rst
trace.rst
+ dtrace.rst
tracemalloc.rst
--- Python-3.5.6/Doc/library/dtrace.rst 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Doc/library/dtrace.rst 2019-01-07 04:41:11.645202501 +0000
@@ -0,0 +1,183 @@
+:mod:`dtrace` --- DTrace probes for Python
+===============================================
+
+.. module:: dtrace
+ :synopsis: DTrace probes for Python.
+
+**Source code:** :source:`Lib/dtrace.py`
+
+--------------
+
+The :mod:`dtrace` module indicates if the CPython executable currently
+running has been compiled with DTrace probes support.
+
+.. impl-detail::
+
+ DTrace probes are implementation details of the CPython interpreter!
+ No garantees are made about probe compatibility between versions of
+ CPython. DTrace scripts can stop working or work incorrectly without
+ warning when changing CPython versions.
+
+The :mod:`dtrace` module defines the following variable:
+
+
+.. data:: available
+
+ The variable will be ``True`` if the current CPython interpreter was
+ compiled with DTrace probe support. ``False`` if not.
+
+
+DTrace probes
+-------------
+
+DTrace scripts are run externally to CPython. DTrace probes export
+selected events inside CPython interpreter in order to make them
+accessible to external scripts.
+
+The probes are exported through the "python" provider. The available
+probes are defined in the file :file:`Include/pydtrace.d`.
+
+To learn how to use DTrace, read `DTrace User Guide
+<http://docs.oracle.com/cd/E19253-01/819-5488/>`_.
+
+.. opcode:: function-entry (arg0, arg1, arg2)
+
+ Fires when python code enters a new function. *arg0* is sourcecode
+ file path, *arg1* is the name of the funcion called, and *arg2* is
+ line number.
+
+ The probe is not fired if Python code calls C functions.
+
+.. opcode:: function-return (arg0, arg1, arg2)
+
+ Fires when Python code finishes execution of a function. Parameters
+ are the same as in ``function-entry``.
+
+ The probe is not fired if the finishing function is written in C.
+
+.. opcode:: line (arg0, arg1, arg2)
+
+ Fires when Python code changes the execution line. Parameters are the
+ same as in ``function-entry``.
+
+ The probe is not fired in C functions.
+
+.. opcode:: gc-start (arg0)
+
+ Fires when the Python interpreter starts a garbage collection cycle.
+ *arg0* is the generation to scan, like :func:`gc.collect()`.
+
+.. opcode:: gc-done (arg0)
+
+ Fires when the Python interpreter finishes a garbage collection
+ cycle. *arg0* is the number of collected objects.
+
+.. opcode:: instance-new-start (arg0, arg1)
+
+ Fires when an object instanciation starts. *arg0* is the class name,
+ *arg1* is the filename where the class is defined.
+
+ The probe is not fired for most C code object creations.
+
+.. opcode:: instance-new-done (arg0, arg1)
+
+ Fires when an object instanciation finishes. Parameters are the same
+ as in ``instance-new-done``.
+
+ The probe is not fired for most C code object creations.
+
+.. opcode:: instance-delete-start (arg0, arg1)
+
+ Fires when an object instance is going to be destroyed. Parameters
+ are the same as in ``instance-new-done``.
+
+ The probe is not fired for most C code object destructions.
+
+.. opcode:: instance-delete-done (arg0, arg1)
+
+ Fires when an object instance has been destroyed. parameters are the
+ same as in ``instance-new-done``.
+
+ Between an ``instance-delete-start`` and corresponding
+ ``instance-delete-done`` others probes can fire if, for instance,
+ deletion of an instance creates a deletion cascade.
+
+ The probe is not fired for most C code object destructions.
+
+
+Python stack
+------------
+
+When a DTrace probe is fired, the DTrace script can examine the stack.
+Since CPython is a Python interpreter coded in C, the stack will show C
+functions, with no direct relation to the Python code currently being
+executed.
+
+Using the special "jstack()" DTrace function, the user will be given
+hints about the python program stack, if possible. In particular, the
+augmented stack will show python function calls, filename, name
+of the function or method, and the line number.
+
+DTrace scripts examples
+-----------------------
+
+DTrace python provider is suffixed by the pid of the process to monitor.
+In the examples, the pid will be 9876.
+
+Show the time spent doing garbage collection (in nanoseconds)::
+
+ python9876:::gc-start
+ {
+ self->t = timestamp;
+ }
+
+ python9876:::gc-done
+ /self->t/
+ {
+ printf("%d", timestamp-self->t);
+ self->t = 0;
+ }
+
+Count how many instances are created of each class::
+
+ python9876:::instance-new-start
+ {
+ @v[copyinstr(arg1), copyinstr(arg0)] = count();
+ }
+
+Observe time spent in object destruction, useful if datastructures are
+complicated and deletion of an object can create a cascade effect::
+
+ python9876:::instance-delete-start
+ /self->t==0/
+ {
+ self->t = timestamp;
+ self->level = 0;
+ }
+
+ python9876:::instance-delete-start
+ /self->t/
+ {
+ self->level += 1;
+ }
+
+ python9876:::instance-delete-done
+ /(self->level) && (self->t)/
+ {
+ self->level -= 1;
+ }
+
+ python9876:::instance-delete-done
+ /(self->level==0) && (self->t)/
+ {
+ @time = quantize(timestamp-self->t);
+ self->t = 0;
+ }
+
+To know which python source code lines create new TCP/IP connections::
+
+ pid9876::sock_connect:entry
+ {
+ @conn[jstack()] = count();
+ }
+
--- Python-3.5.6/Include/code.h 2018-08-02 02:19:12.000000000 +0000
+++ Python-3.5.6/Include/code.h 2019-01-07 04:41:11.646741602 +0000
@@ -7,6 +7,8 @@
extern "C" {
#endif
+#include "pyconfig.h"
+
/* Bytecode object */
typedef struct {
PyObject_HEAD
@@ -33,6 +35,9 @@ typedef struct {
int co_firstlineno; /* first source line number */
PyObject *co_lnotab; /* string (encoding addr<->lineno mapping) See
Objects/lnotab_notes.txt for details. */
+#ifdef WITH_DTRACE
+ unsigned short *co_linenos; /* dtrace stack helper */
+#endif
void *co_zombieframe; /* for optimization only (see frameobject.c) */
PyObject *co_weakreflist; /* to support weakrefs to code objects */
} PyCodeObject;
--- Python-3.5.6/Include/pydtrace.d 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Include/pydtrace.d 2019-01-07 04:41:11.647691317 +0000
@@ -0,0 +1,177 @@
+provider python {
+ probe function__entry(const char *, const char *, int);
+ probe function__return(const char *, const char *, int);
+ probe instance__new__start(const char *, const char *);
+ probe instance__new__done(const char *, const char *);
+ probe instance__delete__start(const char *, const char *);
+ probe instance__delete__done(const char *, const char *);
+ probe line(const char *, const char *, int);
+ probe gc__start(int);
+ probe gc__done(long);
+};
+
+#pragma D attributes Evolving/Evolving/Common provider python provider
+#pragma D attributes Private/Private/Common provider python module
+#pragma D attributes Private/Private/Common provider python function
+#pragma D attributes Evolving/Evolving/Common provider python name
+#pragma D attributes Evolving/Evolving/Common provider python args
+
+
+
+#ifdef PYDTRACE_STACK_HELPER
+/*
+ * Python ustack helper. This relies on the first argument (PyFrame *) being
+ * on the stack; see Python/ceval.c for the contortions we go through to ensure
+ * this is the case.
+ *
+ * On x86, the PyFrame * is two slots up from the frame pointer; on SPARC, it's
+ * eight.
+ *
+ * Some details about this in "Python and DTrace in build 65":
+ * http://blogs.oracle.com/levon/entry/python_and_dtrace_in_build
+ */
+
+/*
+ * Yes, this is as gross as it looks. DTrace cannot handle static functions,
+ * and our stat_impl.h has them in ILP32.
+ */
+#define _SYS_STAT_H
+
+/*
+** When compiling in 32 bits:
+** - Early inclusion to avoid problems with
+** _FILE_OFFSET_BITS redefined.
+** - Also, we must "undef" _POSIX_PTHREAD_SEMANTICS
+** to avoid error compiling this source.
+*/
+#include "pyconfig.h"
+#undef _POSIX_PTHREAD_SEMANTICS
+
+#include <stdio.h>
+#include <sys/types.h>
+
+#include "pyport.h"
+#include "pyatomic.h"
+/* "string" type is used in dtrace */
+#define string stringDTRACE
+#include "object.h"
+#include "pystate.h"
+#include "pyarena.h"
+#include "pythonrun.h"
+#include "compile.h"
+#include "frameobject.h"
+/* Avoid a compile error because a symbol (equivalent) redefinition */
+#undef __STDC__
+/* "self" has an special meaning for dtrace */
+#define self selfDTRACE
+#include "unicodeobject.h"
+#undef string
+#undef self
+
+#include "pydtrace_offsets.h"
+
+#if defined(__i386)
+#define startframe PyEval_EvalFrameEx
+#define endframe AFTER_PyEval_EvalFrameEx
+#elif defined(__amd64)
+#define startframe PyEval_EvalFrameExReal
+#define endframe AFTER_PyEval_EvalFrameExReal
+#elif defined(__sparc)
+#define startframe PyEval_EvalFrameExReal
+#define endframe AFTER_PyEval_EvalFrameExReal
+#endif
+
+#ifdef __sparcv9
+#define STACK_BIAS (2048-1)
+#else
+#define STACK_BIAS 0
+#endif
+
+#define at_evalframe(addr) \
+ ((uintptr_t)addr >= ((uintptr_t)&``startframe) && \
+ (uintptr_t)addr < ((uintptr_t)&``endframe))
+#define probe dtrace:helper:ustack:
+#define print_result(r) (r)
+
+#if defined(__i386) || defined(__amd64)
+#define frame_ptr_addr ((uintptr_t)arg1 + sizeof(uintptr_t) * 2)
+#elif defined(__sparc)
+#define frame_ptr_addr ((uintptr_t)arg1 + STACK_BIAS + sizeof(uintptr_t) * 8)
+#else
+#error unknown architecture
+#endif
+
+/* startframe and endframe are macro-expansions */
+extern uintptr_t startframe;
+extern uintptr_t endframe;
+
+
+#define copyin_obj(addr, obj) ((obj *)copyin((uintptr_t)(addr), sizeof(obj)))
+
+/*
+** Check if the string is ASCII. Don't use bitfields, because the
+** packing in GCC and D are different. BEWARE!!!.
+** The size of the structures are also different!. That is the reason for
+** the negative offset. BEWARE!!!
+*/
+#define pystr_len(addr) ((*(((char *)addr)+PYDTRACE_ASCII_OFFSET)) & PYDTRACE_ASCII_MASK ? \
+ (addr)->_base.length : \
+ *(Py_ssize_t *)(((char *)(addr)) + PYDTRACE_UTF8_LENGTH_OFFSET))
+#define pystr_addr(addr, addr2) ((*(((char *)addr)+PYDTRACE_ASCII_OFFSET)) & PYDTRACE_ASCII_MASK ? \
+ (char *)(((char *)(addr2)) + PYDTRACE_PyASCIIObject_SIZE) : \
+ (char *)*(uintptr_t *)(((char *)(addr)) + PYDTRACE_UTF8_OFFSET))
+
+#define add_digit(nr, div) (((nr) / div) ? \
+ (this->result[this->pos++] = '0' + (((nr) / div) % 10)) : \
+ (this->result[this->pos] = '\0'))
+#define add_char(c) (this->result[this->pos++] = c)
+
+probe /at_evalframe(arg0)/
+{
+ this->framep = *(uintptr_t *)copyin(frame_ptr_addr, sizeof(uintptr_t));
+ this->frameo = copyin_obj(this->framep, PyFrameObject);
+ this->codep = this->frameo->f_code;
+ this->codeo = copyin_obj(this->codep, PyCodeObject);
+ /* If we just enter a function, show the definition line */
+ this->lineno = this->codeo->co_firstlineno +
+ (this->frameo->f_lasti == -1 ? 0 :
+ *copyin_obj(this->codeo->co_linenos + this->frameo->f_lasti,
+ unsigned short));
+ this->filenameo = copyin_obj(this->codeo->co_filename, PyCompactUnicodeObject);
+ this->len_filename = pystr_len(this->filenameo);
+ this->nameo = copyin_obj(this->codeo->co_name, PyCompactUnicodeObject);
+ this->len_name = pystr_len(this->nameo);
+ this->len = 1 + (this->len_filename) + 1 + 5 + 2 +
+ (this->len_name) + 1 + 1;
+
+ this->result = (char *)alloca(this->len);
+ this->pos = 0;
+ add_char('@');
+
+ copyinto((uintptr_t)pystr_addr(this->filenameo, this->codeo->co_filename), this->len_filename, this->result+this->pos);
+ this->pos += this->len_filename;
+
+ add_char(':');
+ add_digit(this->lineno, 10000);
+ add_digit(this->lineno, 1000);
+ add_digit(this->lineno, 100);
+ add_digit(this->lineno, 10);
+ add_digit(this->lineno, 1);
+ add_char(' ');
+ add_char('(');
+
+ copyinto((uintptr_t)pystr_addr(this->nameo, this->codeo->co_name), this->len_name, this->result+this->pos);
+ this->pos += this->len_name;
+
+ add_char(')');
+ this->result[this->pos] = '\0';
+ print_result(stringof(this->result));
+}
+
+probe /!at_evalframe(arg0)/
+{
+ NULL;
+}
+
+#endif /* PYDTRACE_STACK_HELPER */
+
--- Python-3.5.6/Include/pydtrace_offsets.c 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Include/pydtrace_offsets.c 2019-01-07 04:41:11.648321979 +0000
@@ -0,0 +1,40 @@
+#include "Python.h"
+#include "unicodeobject.h"
+#include <stdlib.h>
+#include <stdio.h>
+
+int main(int argc, const char* argv[]) {
+ PyCompactUnicodeObject o;
+ unsigned char *p = (unsigned char *)(&o);
+
+ if (argc != 3) {
+ printf("Parameter number incorrect\n");
+ exit(1);
+ }
+
+ memset(&o, 0, sizeof(o));
+ o._base.state.ascii = 1;
+ while (!*p) p++;
+
+ printf("/* File autogenerated. DO NOT MODIFY MANUALLY */\n");
+ printf("\n");
+ printf("#ifndef PYDTRACE_OFFSETS_H\n");
+ printf("#define PYDTRACE_OFFSETS_H\n");
+ printf("\n");
+ printf("#define PYDTRACE_ASCII_OFFSET %d\n",
+ p-(unsigned char *)(&o));
+ printf("#define PYDTRACE_ASCII_MASK %d\n", *p);
+ printf("#define PYDTRACE_PyASCIIObject_SIZE %d\n",
+ sizeof(PyASCIIObject));
+ printf("#define PYDTRACE_UTF8_LENGTH_OFFSET %d\n",
+ offsetof(PyCompactUnicodeObject, utf8_length));
+ printf("#define PYDTRACE_UTF8_OFFSET %d\n",
+ offsetof(PyCompactUnicodeObject, utf8));
+ printf("\n");
+ printf("#define AFTER_PyEval_EvalFrameEx %s\n", argv[1]);
+ printf("#define AFTER_PyEval_EvalFrameExReal %s\n", argv[2]);
+ printf("\n");
+ printf("#endif\n");
+ return 0;
+}
+
--- Python-3.5.6/Include/pydtrace_offsets.sh 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Include/pydtrace_offsets.sh 2019-01-07 04:41:11.648956940 +0000
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+DTRACE_NM=$1
+CEVAL_O=$2
+PYDTRACE_OFFSETS=$3
+if test "$DTRACE_NM" = "OTHER" ; then
+ $PYDTRACE_OFFSETS \
+ "`nm -n $CEVAL_O | grep \" T \" | \
+ sed -n \"/ T PyEval_EvalFrameEx$/{n;p;}\" | \
+ sed \"s/.* T \(.*\)$/\1/\"`" \
+ "`nm -n $CEVAL_O | grep \" T \" | \
+ sed -n \"/ T PyEval_EvalFrameExReal$/{n;p;}\" | \
+ sed \"s/.* T \(.*\)$/\1/\"`"
+fi
+if test "$DTRACE_NM" = "SOLARIS" ; then
+ $PYDTRACE_OFFSETS \
+ "`/usr/ccs/bin/nm -n $CEVAL_O | \
+ /usr/bin/grep \"\\|FUNC \\|\" | \
+ /usr/bin/grep -v \"\\|IGNORE \\|\" | \
+ /usr/bin/grep -v \"\\|UNDEF \\|\" | \
+ /usr/bin/tr -d \"\\[\\]\\|\" | sort -n | \
+ sed -n \"/ PyEval_EvalFrameEx$/{n;p;}\" | \
+ sed \"s/.* \([a-zA-Z0-9_]*\)$/\1/\"`" \
+ "`/usr/ccs/bin/nm -n $CEVAL_O | \
+ /usr/bin/grep \"\\|FUNC \\|\" | \
+ /usr/bin/grep -v \"\\|UNDEF \\|\" | \
+ /usr/bin/grep -v \"\\|IGNORE \\|\" | \
+ /usr/bin/tr -d \"\\[\\]\\|\" | sort -n | \
+ sed -n \"/ PyEval_EvalFrameExReal$/{n;p;}\" | \
+ sed \"s/.* \([a-zA-Z0-9_]*\)$/\1/\"`"
+fi
+
--- Python-3.5.6/Lib/test/dtrace_sample.py 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Lib/test/dtrace_sample.py 2019-01-07 04:41:11.649754364 +0000
@@ -0,0 +1,80 @@
+# Sample script for use by test_dtrace.py
+# DO NOT MODIFY THIS FILE IN ANY WAY WITHOUT UPDATING test_dtrace.py!!!!!
+
+import gc
+
+def function_1() :
+ pass
+
+# Check stacktrace
+def function_2() :
+ function_1()
+
+# CALL_FUNCTION_VAR
+def function_3(dummy, dummy2) :
+ pass
+
+# CALL_FUNCTION_KW
+def function_4(**dummy) :
+ pass
+
+# CALL_FUNCTION_VAR_KW
+def function_5(dummy, dummy2, **dummy3) :
+ pass
+
+def test_entry_return_and_stack() :
+ function_1()
+ function_2()
+ function_3(*(1,2))
+ function_4(**{"test":42})
+ function_5(*(1,2), **{"test":42})
+
+def test_line() :
+ a = 1 # Preamble
+ for i in range(2) :
+ a = i
+ b = i+2
+ c = i+3
+ d = a + b +c
+ a = 1 # Epilogue
+
+def test_unicode_entry_return_and_stack() :
+ def únícódé() :
+ pass
+ únícódé()
+
+def test_instance_creation_destruction() :
+ class old_style_class() :
+ pass
+ class new_style_class(object) :
+ pass
+
+ a = old_style_class()
+ del a
+ gc.collect()
+ b = new_style_class()
+ del b
+ gc.collect()
+
+ a = old_style_class()
+ del old_style_class
+ gc.collect()
+ b = new_style_class()
+ del new_style_class
+ gc.collect()
+ del a
+ gc.collect()
+ del b
+ gc.collect()
+
+def test_garbage_collection() :
+ gc.collect()
+
+
+if __name__ == "__main__":
+ test_entry_return_and_stack()
+ test_line()
+ test_unicode_entry_return_and_stack()
+ test_instance_creation_destruction()
+ test_garbage_collection()
+
--- Python-3.5.6/Lib/test/test_dtrace.py 1969-12-31 16:00:00.000000000 +0000
+++ Python-3.5.6/Lib/test/test_dtrace.py 2019-01-07 04:41:11.652043227 +0000
@@ -0,0 +1,447 @@
+import sys, unittest, subprocess, os.path, dis, types, re
+import dtrace
+from test.support import TESTFN, run_unittest, findfile
+
+sample = os.path.abspath(findfile("dtrace_sample.py"))
+if not dtrace.available :
+ raise unittest.SkipTest("dtrace support not compiled in")
+
+def normalize(data) :
+ # DTRACE keeps a per-CPU buffer, and when showing the fired probes,
+ # buffers are concatenated. So if the operating system moves our
+ # thread around, the straight result can be "non causal".
+ # So we add timestamps to the probe firing, and sort by that field.
+
+ result = data if isinstance(data, str) else data.decode("ascii")
+ # When compiling with '--with-pydebug'
+ result = "".join(re.split("\[[0-9]+ refs\]", result))
+
+ try :
+ result = [i.split("\t") \
+ for i in result.replace("\r", "").split("\n") if len(i)]
+ result.sort(key = lambda i: int(i[0]))
+ result = "".join((i[1] for i in result))
+ result = result.replace(" ", "")
+ except :
+ # If something goes wrong, rebuild the value so we can see the
+ # real result when the assert fails.
+ result = data if isinstance(data, str) else data.decode("ascii")
+ result = result.replace("\r", "").replace("\n", "")
+ return result
+
+dscript = """
+pid$target::PyEval_EvalCode:entry
+"""
+dscript = dscript.replace("\r", "").replace("\n", "")
+result, _ = subprocess.Popen(["dtrace", "-q", "-l", "-n", dscript,
+ "-c", "%s %s" %(sys.executable, sample)], stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT).communicate()
+if result.decode("ascii").split("\n")[1].split()[-2:] != \
+ ["PyEval_EvalCode", "entry"] :
+ result2 = repr(result)
+ raise unittest.SkipTest("dtrace seems not to be working. " + \
+ "Please, check your privileges. " +
+ "Result: " +result2)
+
+class DTraceTestsNormal(unittest.TestCase) :
+ def setUp(self) :
+ self.optimize = False
+
+ def test_function_entry_return(self) :
+ dscript = """
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_entry_return_and_stack")/
+{
+ self->trace = 1;
+}
+python$target:::function-entry,python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") && (self->trace)/
+{
+ printf("%%d\t**%%s*%%s*%%s*%%d\\n", timestamp,
+ probename, copyinstr(arg0),
+ copyinstr(arg1), arg2);
+}
+python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_entry_return_and_stack")/
+{
+ self->trace = 0;
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ **function-entry*%(path)s*test_entry_return_and_stack*25
+ **function-entry*%(path)s*function_1*6
+ **function-return*%(path)s*function_1*7
+ **function-entry*%(path)s*function_2*10
+ **function-entry*%(path)s*function_1*6
+ **function-return*%(path)s*function_1*7
+ **function-return*%(path)s*function_2*11
+ **function-entry*%(path)s*function_3*14
+ **function-return*%(path)s*function_3*15
+ **function-entry*%(path)s*function_4*18
+ **function-return*%(path)s*function_4*19
+ **function-entry*%(path)s*function_5*22
+ **function-return*%(path)s*function_5*23
+ **function-return*%(path)s*test_entry_return_and_stack*30
+ """ %{"path":sample}
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = normalize(actual_result)
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+ @unittest.skipIf(sys.platform == 'darwin',
+ "MacOS X doesn't support jstack()")
+ def test_stack(self) :
+ dscript = """
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_entry_return_and_stack")/
+{
+ self->trace = 1;
+}
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") && (self->trace)/
+{
+ printf("[x]");
+ jstack();
+}
+python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_entry_return_and_stack")/
+{
+ self->trace = 0;
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ [x]
+ [%(path)s:25(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:6(function_1)]
+ [%(path)s:26(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:10(function_2)]
+ [%(path)s:27(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:6(function_1)]
+ [%(path)s:11(function_2)]
+ [%(path)s:27(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:14(function_3)]
+ [%(path)s:28(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:18(function_4)]
+ [%(path)s:29(test_entry_return_and_stack)]
+ [x]
+ [%(path)s:22(function_5)]
+ [%(path)s:30(test_entry_return_and_stack)]
+ """ %{"path":sample}
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = actual_result.decode("ascii")
+ # When compiling with '--with-pydebug'
+ actual_result = "".join(re.split("\[[0-9]+ refs\]", actual_result))
+
+ actual_result = [i for i in actual_result.split("\n") \
+ if (("[" in i) and not i.endswith(" (<module>) ]"))]
+ actual_result = "".join(actual_result)
+ actual_result = actual_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+ def test_garbage_collection(self) :
+ dscript = """
+python$target:::gc-start,python$target:::gc-done
+{
+ printf("%d\t**%s(%ld)\\n", timestamp, probename, arg0);
+}
+"""
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = normalize(actual_result)
+ for i in range(10) :
+ actual_result = actual_result.replace(str(i), "")
+ expected_result = "**gc-start()**gc-done()" * \
+ actual_result.count("**gc-start()**")
+
+ self.assertEqual(actual_result, expected_result)
+
+ def test_verify_opcodes(self) :
+ # Verify that we are checking:
+ opcodes = set(["CALL_FUNCTION", "CALL_FUNCTION_VAR",
+ "CALL_FUNCTION_KW", "CALL_FUNCTION_VAR_KW"])
+ with open(sample, encoding="utf-8") as f :
+ obj = compile(f.read(), "sample", "exec")
+ class dump() :
+ def __init__(self) :
+ self.buf = []
+ def write(self, v) :
+ self.buf.append(v)
+
+ dump = dump()
+ stdout = sys.stdout
+ sys.stdout = dump
+ for i in obj.co_consts :
+ if isinstance(i, types.CodeType) and \
+ (i.co_name == 'test_entry_return_and_stack') :
+ dis.dis(i)
+ sys.stdout = stdout
+ dump = "\n".join(dump.buf)
+ dump = dump.replace("\r", "").replace("\n", "").split()
+ for i in dump :
+ opcodes.discard(i)
+ # Are we verifying all the relevant opcodes?
+ self.assertEqual(set(), opcodes) # Are we verifying all opcodes?
+
+ def test_line(self) :
+ dscript = """
+python$target:::line
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_line")/
+{
+ printf("%%d\t**%%s*%%s*%%s*%%d\\n", timestamp,
+ probename, copyinstr(arg0),
+ copyinstr(arg1), arg2);
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ **line*%(path)s*test_line*33
+ **line*%(path)s*test_line*34
+ **line*%(path)s*test_line*35
+ **line*%(path)s*test_line*36
+ **line*%(path)s*test_line*37
+ **line*%(path)s*test_line*38
+ **line*%(path)s*test_line*34
+ **line*%(path)s*test_line*35
+ **line*%(path)s*test_line*36
+ **line*%(path)s*test_line*37
+ **line*%(path)s*test_line*38
+ **line*%(path)s*test_line*34
+ **line*%(path)s*test_line*39
+ """ %{"path":sample}
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = normalize(actual_result)
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+ def test_instance_creation_destruction(self) :
+ dscript = """
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_instance_creation_destruction")/
+{
+ self->trace = 1;
+}
+
+python$target:::instance-new-start,
+python$target:::instance-new-done,
+python$target:::instance-delete-start,
+python$target:::instance-delete-done
+/self->trace/
+{
+ printf("%%d\t**%%s* (%%s.%%s)\\n", timestamp,
+ probename, copyinstr(arg1), copyinstr(arg0));
+}
+
+python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_instance_creation_destruction")/
+{
+ self->trace = 0;
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ **instance-new-start*(__main__.old_style_class)
+ **instance-new-done*(__main__.old_style_class)
+ **instance-delete-start*(__main__.old_style_class)
+ **instance-delete-done*(__main__.old_style_class)
+ **instance-new-start*(__main__.new_style_class)
+ **instance-new-done*(__main__.new_style_class)
+ **instance-delete-start*(__main__.new_style_class)
+ **instance-delete-done*(__main__.new_style_class)
+ **instance-new-start*(__main__.old_style_class)
+ **instance-new-done*(__main__.old_style_class)
+ **instance-new-start*(__main__.new_style_class)
+ **instance-new-done*(__main__.new_style_class)
+ **instance-delete-start*(__main__.old_style_class)
+ **instance-delete-done*(__main__.old_style_class)
+ **instance-delete-start*(__main__.new_style_class)
+ **instance-delete-done*(__main__.new_style_class)
+ """
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = normalize(actual_result)
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+ def test_unicode_function_entry_return(self) :
+ dscript = """
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_unicode_entry_return_and_stack")/
+{
+ self->trace = 1;
+}
+python$target:::function-entry,python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") && (self->trace)/
+{
+ printf("%%d\t**%%s*%%s*%%s*%%d\\n", timestamp,
+ probename, copyinstr(arg0),
+ copyinstr(arg1), arg2);
+}
+python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_unicode_entry_return_and_stack")/
+{
+ self->trace = 0;
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ **function-entry*%(path)s*test_unicode_entry_return_and_stack*41
+ **function-entry*%(path)s*únícódé*42
+ **function-return*%(path)s*únícódé*43
+ **function-return*%(path)s*test_unicode_entry_return_and_stack*44
+ """ %{"path":sample}
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = actual_result.decode("utf8")
+ actual_result = normalize(actual_result)
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+ @unittest.skipIf(sys.platform == 'darwin',
+ "MacOS X doesn't support jstack()")
+ def test_unicode_stack(self) :
+ dscript = """
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_unicode_entry_return_and_stack")/
+{
+ self->trace = 1;
+}
+python$target:::function-entry
+/(copyinstr(arg0)=="%(path)s") && (self->trace)/
+{
+ printf("[x]");
+ jstack();
+}
+python$target:::function-return
+/(copyinstr(arg0)=="%(path)s") &&
+(copyinstr(arg1)=="test_unicode_entry_return_and_stack")/
+{
+ self->trace = 0;
+}
+""" %{"path":sample}
+
+ dscript = dscript.replace("\r", "").replace("\n", "")
+ expected_result = """
+ [x]
+ [%(path)s:41(test_unicode_entry_return_and_stack)]
+ [x]
+ [%(path)s:42(únícódé)]
+ [%(path)s:44(test_unicode_entry_return_and_stack)]
+ """ %{"path":sample}
+
+ command = "%s %s" %(sys.executable, sample)
+ if self.optimize :
+ command = "%s -OO %s" %(sys.executable, sample)
+ actual_result, _ = subprocess.Popen(["dtrace", "-q", "-n",
+ dscript,
+ "-c", command],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
+
+ actual_result = actual_result.decode("utf8")
+ # When compiling with '--with-pydebug'
+ actual_result = "".join(re.split("\[[0-9]+ refs\]", actual_result))
+
+ actual_result = [i for i in actual_result.split("\n") \
+ if (("[" in i) and not i.endswith(" (<module>) ]"))]
+ actual_result = "".join(actual_result)
+ actual_result = actual_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ expected_result = expected_result.replace("\r", "").replace("\n",
+ "").replace(" ", "")
+ self.assertEqual(actual_result, expected_result)
+
+
+
+# This class try to verify that dtrace probes
+# are still working with optimizations enabled in the bytecode.
+#
+# Some tests will not actually verify it. For instance,
+# source code compilation follows optimization status of
+# current working Python. So, you should run the test
+# both with an optimizing and a non optimizing Python.