-
Notifications
You must be signed in to change notification settings - Fork 315
/
Copy patheval.c
9412 lines (8453 loc) · 270 KB
/
eval.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
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1998--2024 The R Core Team.
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#define R_USE_SIGNALS 1
#include <Defn.h>
#include <Internal.h>
#include <Rinterface.h>
#include <Fileio.h>
#include <R_ext/Print.h>
#include <errno.h>
#include <math.h>
static SEXP bcEval(SEXP, SEXP);
static void bcEval_init(void);
/* BC_PROFILING needs to be enabled at build time. It is not enabled
by default as enabling it disables the more efficient threaded code
implementation of the byte code interpreter. */
#ifdef BC_PROFILING
static Rboolean bc_profiling = FALSE;
#endif
static int R_Profiling = 0;
#ifdef R_PROFILING
/* BDR 2000-07-15
Profiling is now controlled by the R function Rprof(), and should
have negligible cost when not enabled.
*/
/* A simple mechanism for profiling R code. When R_PROFILING is
enabled, eval will write out the call stack every PROFSAMPLE
microseconds using the SIGPROF handler triggered by timer signals
from the ITIMER_PROF timer. Since this is the same timer used by C
profiling, the two cannot be used together. Output is written to
the file PROFOUTNAME. This is a plain text file. The first line
of the file contains the value of PROFSAMPLE. The remaining lines
each give the call stack found at a sampling point with the inner
most function first.
To enable profiling, recompile eval.c with R_PROFILING defined. It
would be possible to selectively turn profiling on and off from R
and to specify the file name from R as well, but for now I won't
bother.
The stack is traced by walking back along the context stack, just
like the traceback creation in jump_to_toplevel. One drawback of
this approach is that it does not show BUILTIN's since they don't
get a context. With recent changes to pos.to.env it seems possible
to insert a context around BUILTIN calls to that they show up in
the trace. Since there is a cost in establishing these contexts,
they are only inserted when profiling is enabled. [BDR: we have since
also added contexts for the BUILTIN calls to foreign code.]
One possible advantage of not tracing BUILTIN's is that then
profiling adds no cost when the timer is turned off. This would be
useful if we want to allow profiling to be turned on and off from
within R.
One thing that makes interpreting profiling output tricky is lazy
evaluation. When an expression f(g(x)) is profiled, lazy
evaluation will cause g to be called inside the call to f, so it
will appear as if g is called by f.
L. T. */
#ifdef Win32
# define WIN32_LEAN_AND_MEAN 1
# include <windows.h> /* for CreateEvent, SetEvent */
# include <process.h> /* for _beginthread, _endthread */
#else
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# endif
# include <signal.h>
# ifdef HAVE_FCNTL_H
# include <fcntl.h> /* for open */
# endif
# ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
# endif
# ifdef HAVE_UNISTD_H
# include <unistd.h> /* for write */
# endif
#endif /* not Win32 */
#if !defined(Win32) && defined(HAVE_PTHREAD)
// <signal.h> is needed for pthread_kill on most platforms (and by POSIX
// but apparently not FreeBSD): it is included above.
# include <pthread.h>
# ifdef HAVE_SCHED_H
# include <sched.h>
# endif
static pthread_t R_profiled_thread;
#endif
#ifdef Win32
static FILE *R_ProfileOutfile = NULL;
#else
static int R_ProfileOutfile = -1;
#endif
static int R_Mem_Profiling=0;
static int R_GC_Profiling = 0; /* indicates GC profiling */
static int R_Line_Profiling = 0; /* indicates line profiling, and also counts the filenames seen (+1) */
static char **R_Srcfiles; /* an array of pointers into the filename buffer */
static size_t R_Srcfile_bufcount; /* how big is the array above? */
static SEXP R_Srcfiles_buffer = NULL; /* a big RAWSXP to use as a buffer for filenames and pointers to them */
static int R_Profiling_Error; /* record errors here */
static int R_Filter_Callframes = 0; /* whether to record only the trailing branch of call trees */
typedef enum { RPE_CPU, RPE_ELAPSED } rpe_type; /* profiling event, CPU time or elapsed time */
static rpe_type R_Profiling_Event;
#ifdef Win32
HANDLE MainThread;
HANDLE ProfileEvent;
#else
# ifdef HAVE_PTHREAD
typedef struct {
pthread_t thread;
pthread_mutex_t terminate_mu;
pthread_cond_t terminate_cv;
int should_terminate;
int interval_us;
} R_profile_thread_info_t;
static R_profile_thread_info_t R_Profile_Thread_Info;
# endif
#endif
/* Careful here! These functions are called asynchronously, maybe in the
middle of GC, so don't do any allocations. They get called in a signal
handler on Unix, so they are only allowed to call library functions
that are async-signal-safe. They get called while the main R thread
is suspended on Windows, and hence they cannot call into any C runtime
function which may possibly include synchronization.
Note that snprintf() is not safe on Unix nor on Windows. On Windows 10
it has been seen to deadlock when the main thread has been suspended
in a locale-specific operation. */
/* This does a linear search through the previously recorded filenames. If
this one is new, we try to add it. FIXME: if there are eventually
too many files for an efficient linear search, do hashing. */
static int getFilenum(const char* filename) {
int fnum;
for (fnum = 0; fnum < R_Line_Profiling-1
&& strcmp(filename, R_Srcfiles[fnum]); fnum++);
if (fnum == R_Line_Profiling-1) {
size_t len = strlen(filename);
if (fnum >= R_Srcfile_bufcount) { /* too many files */
R_Profiling_Error = 1;
return 0;
}
if (R_Srcfiles[fnum] - (char*)RAW(R_Srcfiles_buffer) + len + 1 >
length(R_Srcfiles_buffer)) {
/* out of space in the buffer */
R_Profiling_Error = 2;
return 0;
}
strcpy(R_Srcfiles[fnum], filename);
R_Srcfiles[fnum+1] = R_Srcfiles[fnum] + len + 1;
*(R_Srcfiles[fnum+1]) = '\0';
R_Line_Profiling++;
}
return fnum + 1;
}
#define PROFBUFSIZ 10500
/* It would also be better to flush the buffer when it gets full,
even if the line isn't complete. But this isn't possible if we rely
on writing all line profiling files first. In addition, while on Unix
we could use write() (not fprintf) to flush, it is not guaranteed we
could do this on Windows with the main thread suspended.
With this size hitting the limit is fairly unlikely, but if we do then
the output file will miss some entries. Maybe writing an overflow marker
of some sort would be better. LT, TK */
/* The pb_* functions write to profiling buffer, advancing the "ptr" and
maintaining "left". If the write wouldn't fit leaving one more byte
available for the terminator, "left" is set to zero. They do not
terminate the string. */
typedef struct {
char *ptr;
size_t left;
} profbuf;
/* If a string fits with terminator to the buffer, add it, excluding
the terminator. If it doesn't fit, set left to 0. */
static void pb_str(profbuf *pb, const char *str)
{
size_t len = strlen(str);
if (len < pb->left) {
size_t i;
for(i = 0; i < len; i++)
pb->ptr[i] = str[i];
pb->ptr += len;
pb->left -= len;
} else
pb->left = 0;
}
static void pb_uint(profbuf *pb, uint64_t num)
{
char digits[20]; /* 64-bit unsigned integers */
int i, j;
for (i = 0;;) {
digits[i++] = num % 10 + '0';
num /= 10;
if (num == 0)
break;
}
if (i < pb->left) {
j = 0;
for (i--; i >= 0;)
pb->ptr[j++] = digits[i--];
pb->ptr += j;
pb->left -= j;
} else
pb->left = 0;
}
static void pb_int(profbuf *pb, int64_t num)
{
char digits[19]; /* 64-bit signed integers */
int i, j, negative;
if (num < 0) {
negative = 1;
num *= -1;
} else
negative = 0;
for (i = 0;;) {
digits[i++] = num % 10 + '0';
num /= 10;
if (num == 0)
break;
}
if (negative + i < pb->left) {
if (negative) {
pb->ptr[0] = '-';
pb->ptr++;
pb->left--;
}
j = 0;
for (i--; i >= 0;)
pb->ptr[j++] = digits[i--];
pb->ptr += j;
pb->left -= j;
} else
pb->left = 0;
}
/* IEEE doubles */
#define PB_MAX_DBL_DIGITS 309
/* Careful: this is very simplistic printing of the integer parts of doubles
(like %0.f) used only (in a special case) for stack trace in profiling data.
Not suitable for re-use. */
static void pb_dbl(profbuf *pb, double num)
{
char digits[PB_MAX_DBL_DIGITS];
int i, j, negative;
if (!R_FINITE(num)) {
if (ISNA(num))
pb_str(pb, "NA");
else if (ISNAN(num))
pb_str(pb, "NaN");
else if (num > 0)
pb_str(pb, "Inf");
else
pb_str(pb, "-Inf");
return;
}
if (num < 0) {
negative = 1;
num *= -1.0;
} else
negative = 0;
for (i = 0;;) {
digits[i++] = (char) ((int) fmod(num, 10.0) + '0');
num /= 10.0;
if (num < 1)
break;
if (i >= PB_MAX_DBL_DIGITS)
/* This cannot happen with IEEE double */
return;
}
if (negative + i < pb->left) {
if (negative) {
pb->ptr[0] = '-';
pb->ptr++;
pb->left--;
}
j = 0;
for (i--; i >= 0;)
pb->ptr[j++] = digits[i--];
pb->ptr += j;
pb->left -= j;
} else
pb->left = 0;
}
static void lineprof(profbuf* pb, SEXP srcref)
{
if (srcref && !isNull(srcref)) {
int fnum, line = asInteger(srcref);
SEXP srcfile = getAttrib(srcref, R_SrcfileSymbol);
const char *filename;
if (!srcfile || TYPEOF(srcfile) != ENVSXP) return;
srcfile = R_findVar(install("filename"), srcfile);
if (TYPEOF(srcfile) != STRSXP || !length(srcfile)) return;
filename = CHAR(STRING_ELT(srcfile, 0));
if ((fnum = getFilenum(filename))) {
pb_int(pb, fnum); /* %d */
pb_str(pb, "#");
pb_int(pb, line); /* %d */
pb_str(pb, " " );
}
}
}
#if defined(__APPLE__)
#include <mach/mach_init.h>
#include <mach/mach_port.h>
static mach_port_t R_profiled_thread_id;
#endif
static RCNTXT * findProfContext(RCNTXT *cptr)
{
if (! R_Filter_Callframes)
return cptr->nextcontext;
if (cptr == R_ToplevelContext)
return NULL;
/* Find parent context, same algorithm as in `parent.frame()`. */
RCNTXT * parent = R_findParentContext(cptr, 1);
/* If we're in a frame called by `eval()`, find the evaluation
environment higher up the stack, if any. */
if (parent && parent->callfun == INTERNAL(R_EvalSymbol))
parent = R_findExecContext(parent->nextcontext, cptr->sysparent);
if (parent)
return parent;
/* Base case, this interrupts the iteration over context frames */
if (cptr->nextcontext == R_ToplevelContext)
return NULL;
/* There is no parent frame and we haven't reached the top level
context. Find the very first context on the stack which should
always be included in the profiles. */
while (cptr->nextcontext != R_ToplevelContext)
cptr = cptr->nextcontext;
return cptr;
}
/* Write string to the profile file.
On Unix, pf_* functions are called from a signal handler, hence avoid
calling fprintf. */
static ssize_t pf_str(const char *s)
{
#ifdef Win32
return fprintf(R_ProfileOutfile, "%s", s);
#else
size_t wbyte = 0;
size_t nbyte = strlen(s);
for(;;) {
ssize_t w = write(R_ProfileOutfile, s + wbyte, nbyte - wbyte);
if (w == -1) {
if (errno == EINTR)
continue;
else
return -1;
}
wbyte += w;
if (wbyte == nbyte || w == 0)
return wbyte;
}
#endif
}
static void pf_int(int num)
{
#ifdef Win32
fprintf(R_ProfileOutfile, "%d", num);
#else
char buf[32];
profbuf nb;
nb.ptr = buf;
nb.left = sizeof(buf);
pb_int(&nb, num);
nb.ptr[0] = '\0';
pf_str(buf);
#endif
}
static void doprof(int sig) /* sig is ignored in Windows */
{
char buf[PROFBUFSIZ];
size_t bigv, smallv, nodes;
int prevnum = R_Line_Profiling;
int old_errno = errno;
profbuf pb;
pb.ptr = buf;
pb.left = PROFBUFSIZ;
#ifdef Win32
SuspendThread(MainThread);
#elif defined(__APPLE__)
if (R_Profiling_Event == RPE_CPU) {
/* Using Mach thread API to detect whether we are on the main thread,
because pthread_self() sometimes crashes R due to a page fault when
the signal handler runs just after the new thread is created, but
before pthread initialization has been finished. */
mach_port_t id = mach_thread_self();
mach_port_deallocate(mach_task_self(), id);
if (id != R_profiled_thread_id) {
pthread_kill(R_profiled_thread, sig);
errno = old_errno;
return;
}
}
#elif defined(HAVE_PTHREAD)
if (R_Profiling_Event == RPE_CPU) {
if (! pthread_equal(pthread_self(), R_profiled_thread)) {
pthread_kill(R_profiled_thread, sig);
errno = old_errno;
return;
}
}
#endif /* Win32 */
if (R_Mem_Profiling) {
get_current_mem(&smallv, &bigv, &nodes);
pb_str(&pb, ":");
pb_uint(&pb, (uint64_t) smallv);
pb_str(&pb, ":");
pb_uint(&pb, (uint64_t) bigv);
pb_str(&pb, ":");
pb_uint(&pb, (uint64_t) nodes);
pb_str(&pb, ":");
pb_uint(&pb, (uint64_t) get_duplicate_counter());
pb_str(&pb, ":");
reset_duplicate_counter();
}
if (R_GC_Profiling && R_gc_running())
pb_str(&pb, "\"<GC>\" ");
if (R_Line_Profiling)
lineprof(&pb, R_getCurrentSrcref());
for (RCNTXT *cptr = R_GlobalContext;
cptr != NULL;
cptr = findProfContext(cptr)) {
if ((cptr->callflag & (CTXT_FUNCTION | CTXT_BUILTIN))
&& TYPEOF(cptr->call) == LANGSXP) {
SEXP fun = CAR(cptr->call);
pb_str(&pb, "\"");
if (TYPEOF(fun) == SYMSXP) {
pb_str(&pb, CHAR(PRINTNAME(fun)));
} else if ((CAR(fun) == R_DoubleColonSymbol ||
CAR(fun) == R_TripleColonSymbol ||
CAR(fun) == R_DollarSymbol) &&
TYPEOF(CADR(fun)) == SYMSXP &&
TYPEOF(CADDR(fun)) == SYMSXP) {
/* Function accessed via ::, :::, or $. Both args must be
symbols. It is possible to use strings with these
functions, as in "base"::"list", but that's a very rare
case so we won't bother handling it. */
pb_str(&pb, CHAR(PRINTNAME(CADR(fun))));
pb_str(&pb, CHAR(PRINTNAME(CAR(fun))));
pb_str(&pb, CHAR(PRINTNAME(CADDR(fun))));
} else if (CAR(fun) == R_Bracket2Symbol &&
TYPEOF(CADR(fun)) == SYMSXP &&
((TYPEOF(CADDR(fun)) == SYMSXP ||
TYPEOF(CADDR(fun)) == STRSXP ||
TYPEOF(CADDR(fun)) == INTSXP ||
TYPEOF(CADDR(fun)) == REALSXP) &&
length(CADDR(fun)) > 0)) {
/* Function accessed via [[. The first arg must be a symbol
and the second can be a symbol, string, integer, or
real. */
SEXP arg1 = CADR(fun);
SEXP arg2 = CADDR(fun);
pb_str(&pb, CHAR(PRINTNAME(arg1)));
pb_str(&pb, "[[");
if (TYPEOF(arg2) == SYMSXP) {
pb_str(&pb, CHAR(PRINTNAME(arg2)));
} else if (TYPEOF(arg2) == STRSXP) {
pb_str(&pb, "\"");
pb_str(&pb, CHAR(STRING_ELT(arg2, 0)));
pb_str(&pb, "\"");
} else if (TYPEOF(arg2) == INTSXP) {
pb_int(&pb, INTEGER(arg2)[0]);
} else if (TYPEOF(arg2) == REALSXP) {
pb_dbl(&pb, REAL(arg2)[0]); /* %0.f */
}
pb_str(&pb, "]]");
} else {
pb_str(&pb, "<Anonymous>");
}
pb_str(&pb, "\" ");
if (R_Line_Profiling) {
if (cptr->srcref == R_InBCInterpreter)
lineprof(&pb, R_findBCInterpreterSrcref(cptr));
else
lineprof(&pb, cptr->srcref);
}
}
}
if (pb.left)
pb.ptr[0] = '\0';
else {
/* overflow */
buf[0] = '\0';
R_Profiling_Error = 3;
}
#ifdef Win32
/* resume before calling pf_* functions to avoid deadlock */
ResumeThread(MainThread);
#endif
for (int i = prevnum; i < R_Line_Profiling; i++) {
pf_str("#File ");
pf_int(i); /* %d */
pf_str(": ");
pf_str(R_Srcfiles[i-1]);
pf_str("\n");
}
if(strlen(buf)) {
pf_str(buf);
pf_str("\n");
}
#ifndef Win32
signal(SIGPROF, doprof);
#endif /* not Win32 */
errno = old_errno;
}
#ifdef Win32
/* Profiling thread main function */
static void __cdecl ProfileThread(void *pwait)
{
int wait = *((int *)pwait); /* milliseconds */
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
while(WaitForSingleObject(ProfileEvent, wait) != WAIT_OBJECT_0) {
doprof(0);
}
}
#else /* not Win32 */
/* Profiling thread main function */
static void *ProfileThread(void *pinfo)
{
#ifdef HAVE_PTHREAD
R_profile_thread_info_t *nfo = pinfo;
pthread_mutex_lock(&nfo->terminate_mu);
while(!nfo->should_terminate) {
struct timespec until;
double duntil_s = currentTime() + nfo->interval_us / 1e6;
until.tv_sec = (time_t) duntil_s;
until.tv_nsec = (long) (1e9 * (duntil_s - until.tv_sec));
for(;;) {
int res = pthread_cond_timedwait(&nfo->terminate_cv,
&nfo->terminate_mu, &until);
if (nfo->should_terminate)
break;
if (res == ETIMEDOUT) {
pthread_kill(R_profiled_thread, SIGPROF);
break;
}
}
}
pthread_mutex_unlock(&nfo->terminate_mu);
#endif
return NULL;
}
static void doprof_null(int sig)
{
signal(SIGPROF, doprof_null);
}
#endif /* not Win32 */
static void R_EndProfiling(void)
{
#ifdef Win32
SetEvent(ProfileEvent);
CloseHandle(MainThread);
if(R_ProfileOutfile) fclose(R_ProfileOutfile);
R_ProfileOutfile = NULL;
#else /* not Win32 */
if (R_Profiling_Event == RPE_CPU) {
struct itimerval itv;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
itv.it_value.tv_sec = 0;
itv.it_value.tv_usec = 0;
setitimer(ITIMER_PROF, &itv, NULL);
}
if (R_Profiling_Event == RPE_ELAPSED) {
R_profile_thread_info_t *nfo = &R_Profile_Thread_Info;
pthread_mutex_lock(&nfo->terminate_mu);
nfo->should_terminate = 1;
pthread_cond_signal(&nfo->terminate_cv);
pthread_mutex_unlock(&nfo->terminate_mu);
pthread_join(nfo->thread, NULL);
pthread_cond_destroy(&nfo->terminate_cv);
pthread_mutex_destroy(&nfo->terminate_mu);
}
signal(SIGPROF, doprof_null);
if(R_ProfileOutfile >= 0) close(R_ProfileOutfile);
R_ProfileOutfile = -1;
#endif /* not Win32 */
R_Profiling = 0;
if (R_Srcfiles_buffer) {
R_ReleaseObject(R_Srcfiles_buffer);
R_Srcfiles_buffer = NULL;
}
if (R_Profiling_Error) {
if (R_Profiling_Error == 3)
/* It is hard to imagine this could happen in practice, but
if needed, it could be configurable like numfiles/bufsize. */
warning(_("samples too large for I/O buffer skipped by Rprof"));
else
warning(_("source files skipped by Rprof; please increase '%s'"),
R_Profiling_Error == 1 ? "numfiles" : "bufsize");
}
}
static void R_InitProfiling(SEXP filename, int append, double dinterval,
int mem_profiling, int gc_profiling,
int line_profiling, int filter_callframes,
int numfiles, int bufsize, rpe_type event)
{
#ifndef Win32
const void *vmax = vmaxget();
if(R_ProfileOutfile >= 0) R_EndProfiling();
if (filename != NA_STRING && filename) {
const char *fn = R_ExpandFileName(translateCharFP(filename));
int flags = O_CREAT | O_WRONLY;
if (append)
flags |= O_APPEND;
else
flags |= O_TRUNC;
int mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
R_ProfileOutfile = open(fn, flags, mode);
if (R_ProfileOutfile < 0)
error(_("Rprof: cannot open profile file '%s'"), fn);
}
vmaxset(vmax);
#else
int wait;
HANDLE Proc = GetCurrentProcess();
if(R_ProfileOutfile != NULL) R_EndProfiling();
R_ProfileOutfile = RC_fopen(filename, append ? "a" : "w", TRUE);
if (R_ProfileOutfile == NULL)
error(_("Rprof: cannot open profile file '%s'"),
translateChar(filename));
#endif
int interval;
interval = (int)(1e6 * dinterval + 0.5);
if(mem_profiling)
pf_str("memory profiling: ");
if(gc_profiling)
pf_str("GC profiling: ");
if(line_profiling)
pf_str("line profiling: ");
pf_str("sample.interval=");
pf_int(interval); /* %d */
pf_str("\n");
R_Mem_Profiling=mem_profiling;
if (mem_profiling)
reset_duplicate_counter();
R_Profiling_Error = 0;
R_Line_Profiling = line_profiling;
R_GC_Profiling = gc_profiling;
R_Filter_Callframes = filter_callframes;
if (line_profiling) {
/* Allocate a big RAW vector to use as a buffer. The first len1 bytes are an array of pointers
to strings; the actual strings are stored in the second len2 bytes. */
R_Srcfile_bufcount = numfiles;
size_t len1 = R_Srcfile_bufcount*sizeof(char *), len2 = bufsize;
R_PreserveObject( R_Srcfiles_buffer = Rf_allocVector(RAWSXP, len1 + len2) );
// memset(RAW(R_Srcfiles_buffer), 0, len1+len2);
R_Srcfiles = (char **) RAW(R_Srcfiles_buffer);
R_Srcfiles[0] = (char *)RAW(R_Srcfiles_buffer) + len1;
*(R_Srcfiles[0]) = '\0';
}
R_Profiling_Event = event;
#ifdef Win32
/* need to duplicate to make a real handle */
DuplicateHandle(Proc, GetCurrentThread(), Proc, &MainThread,
0, FALSE, DUPLICATE_SAME_ACCESS);
wait = interval/1000;
if(!(ProfileEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) ||
(_beginthread(ProfileThread, 0, &wait) == -1))
R_Suicide("unable to create profiling thread");
Sleep(wait/2); /* suspend this thread to ensure that the other one starts */
#else /* not Win32 */
# ifdef HAVE_PTHREAD
R_profiled_thread = pthread_self();
# else
error("profiling requires 'pthread' support");
# endif
# if defined(__APPLE__)
if (R_Profiling_Event == RPE_CPU) {
/* see comment in doprof for why R_profiled_thread is not enough */
R_profiled_thread_id = mach_thread_self();
mach_port_deallocate(mach_task_self(), R_profiled_thread_id);
}
# endif
signal(SIGPROF, doprof);
if (R_Profiling_Event == RPE_ELAPSED) {
# ifdef HAVE_PTHREAD
R_profile_thread_info_t *nfo = &R_Profile_Thread_Info;
pthread_mutex_init(&nfo->terminate_mu, NULL);
pthread_cond_init(&nfo->terminate_cv, NULL);
nfo->should_terminate = 0;
nfo->interval_us = interval;
sigset_t all, old_set;
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, &old_set);
if (pthread_create(&nfo->thread, NULL, ProfileThread,
nfo))
R_Suicide("unable to create profiling thread");
pthread_sigmask(SIG_SETMASK, &old_set, NULL);
# ifdef HAVE_SCHED_H
/* attempt to set FIFO scheduling with maximum priority
at least on Linux it requires special permissions */
struct sched_param p;
p.sched_priority = sched_get_priority_max(SCHED_FIFO);
int res = -1;
if (p.sched_priority >= 0)
res = pthread_setschedparam(nfo->thread, SCHED_FIFO, &p);
if (res) {
/* attempt to set maximum priority at least with
the current scheduling policy */
int policy;
if (!pthread_getschedparam(nfo->thread, &policy, &p)) {
p.sched_priority = sched_get_priority_max(policy);
if (p.sched_priority >= 0)
pthread_setschedparam(nfo->thread, policy, &p);
}
}
# endif
# endif
} else if (R_Profiling_Event == RPE_CPU) {
/* The macOS implementation requires normalization here:
setitimer is obsolescent (POSIX >= 2008), replaced by
timer_create / timer_settime, but the supported clocks are
implementation-dependent.
Recent Linux has CLOCK_PROCESS_CPUTIME_ID
Solaris has CLOCK_PROF, in -lrt.
FreeBSD only supports CLOCK_{REALTIME,MONOTONIC}
Seems not to be supported at all on macOS.
*/
struct itimerval itv;
itv.it_interval.tv_sec = interval / 1000000;
itv.it_interval.tv_usec =
(suseconds_t)(interval - itv.it_interval.tv_sec * 1000000);
itv.it_value.tv_sec = interval / 1000000;
itv.it_value.tv_usec =
(suseconds_t)(interval - itv.it_value.tv_sec * 1000000);
if (setitimer(ITIMER_PROF, &itv, NULL) == -1)
R_Suicide("setting profile timer failed");
}
#endif /* not Win32 */
R_Profiling = 1;
}
SEXP do_Rprof(SEXP args)
{
SEXP filename;
int append_mode, mem_profiling, gc_profiling, line_profiling,
filter_callframes;
double dinterval;
int numfiles, bufsize;
const char *event_arg;
rpe_type event;
#ifdef BC_PROFILING
if (bc_profiling) {
warning("cannot use R profiling while byte code profiling");
return R_NilValue;
}
#endif
if (!isString(filename = CAR(args)) || (LENGTH(filename)) != 1)
error(_("invalid '%s' argument"), "filename");
args = CDR(args);
append_mode = asLogical(CAR(args)); args = CDR(args);
dinterval = asReal(CAR(args)); args = CDR(args);
mem_profiling = asLogical(CAR(args)); args = CDR(args);
gc_profiling = asLogical(CAR(args)); args = CDR(args);
line_profiling = asLogical(CAR(args)); args = CDR(args);
filter_callframes = asLogical(CAR(args)); args = CDR(args);
numfiles = asInteger(CAR(args)); args = CDR(args);
if (numfiles < 0)
error(_("invalid '%s' argument"), "numfiles");
bufsize = asInteger(CAR(args)); args = CDR(args);
if (bufsize < 0)
error(_("invalid '%s' argument"), "bufsize");
if (!isString(CAR(args)) || length(CAR(args)) != 1
|| STRING_ELT(CAR(args), 0) == NA_STRING)
error(_("invalid '%s' argument"), "event");
event_arg = translateChar(STRING_ELT(CAR(args), 0));
#ifdef Win32
if (streql(event_arg, "elapsed") || streql(event_arg, "default"))
event = RPE_ELAPSED;
else if (streql(event_arg, "cpu"))
error("event type '%s' not supported on this platform", event_arg);
else
error(_("invalid '%s' argument"), "event");
#else
if (streql(event_arg, "cpu") || streql(event_arg, "default"))
event = RPE_CPU;
else if (streql(event_arg, "elapsed"))
event = RPE_ELAPSED;
else
error(_("invalid '%s' argument"), "event");
#endif
#if defined(linux) || defined(__linux__)
if (dinterval < 0.01) {
dinterval = 0.01;
warning(_("interval too short for this platform, using '%f'"), dinterval);
}
#else
if (dinterval < 0.001) {
dinterval = 0.001;
warning(_("interval too short, using '%f'"), dinterval);
}
#endif
filename = STRING_ELT(filename, 0);
if (LENGTH(filename))
R_InitProfiling(filename, append_mode, dinterval, mem_profiling,
gc_profiling, line_profiling, filter_callframes,
numfiles, bufsize, event);
else
R_EndProfiling();
return R_NilValue;
}
#else /* not R_PROFILING */
SEXP do_Rprof(SEXP args)
{
error(_("R profiling is not available on this system"));
return R_NilValue; /* -Wall */
}
#endif /* not R_PROFILING */
/* NEEDED: A fixup is needed in browser, because it can trap errors,
* and currently does not reset the limit to the right value. */
attribute_hidden void check_stack_balance(SEXP op, int save)
{
if(save == R_PPStackTop) return;
REprintf("Warning: stack imbalance in '%s', %d then %d\n",
PRIMNAME(op), save, R_PPStackTop);
}
#define ENSURE_PROMISE_IS_EVALUATED(x) do { \
SEXP __x__ = (x); \
if (! PROMISE_IS_EVALUATED(__x__)) \
forcePromise(__x__); \
} while (0)
static R_INLINE void PUSH_PENDING_PROMISE(SEXP e, RPRSTACK *cellptr)
{
cellptr->promise = e;
cellptr->next = R_PendingPromises;
R_PendingPromises = cellptr;
}
static R_INLINE void POP_PENDING_PROMISE(RPRSTACK *cellptr)
{
R_PendingPromises = cellptr->next;
}
static void forcePromise(SEXP e)
{
if (! PROMISE_IS_EVALUATED(e)) {
PROTECT(e);
if(PRSEEN(e)) {
if (PRSEEN(e) == 1)
errorcall(R_GlobalContext->call,
_("promise already under evaluation: recursive default argument reference or earlier problems?"));
else {
/* set PRSEEN to 1 to avoid infinite recursion */
SET_PRSEEN(e, 1);
warningcall(R_GlobalContext->call,
_("restarting interrupted promise evaluation"));
}
}
/* Mark the promise as under evaluation and push it on a stack
that can be used to unmark pending promises if a jump out
of the evaluation occurs. */
SET_PRSEEN(e, 1);
RPRSTACK prstack;
PUSH_PENDING_PROMISE(e, &prstack);
SEXP val = eval(PRCODE(e), PRENV(e));
SET_PRVALUE(e, val);
ENSURE_NAMEDMAX(val);
/* Pop the stack, unmark the promise and set its value field.
Also set the environment to R_NilValue to allow GC to
reclaim the promise environment; this is also useful for
fancy games with delayedAssign() */
POP_PENDING_PROMISE(&prstack);
SET_PRSEEN(e, 0);
SET_PRENV(e, R_NilValue);
UNPROTECT(1); /* e */
}
}
/*
* Protecting the Stack During Possibly Mutating Operations
*
* Values below R_BCProtTop should be protected during a mutating
* operation by incrementing their link counts. Actual incrementing is
* deferred until a call to INCLNK_stack_commit, which should happen
* before a mutation that might affect stack values. (applydefine() in
* the AST interpreter, STARTASSIGN/STARTASSIGN2 and INCLNK/INCLNKSTK
* in the byte code interpreter. Deferring until needed avoids the