Debian Codegraph @

src/prof.c

raw
1 /*
2 * prof.c - profiler
3 *
4 * Copyright (c) 2005-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/vm.h"
38 #include "gauche/code.h"
39 #include "gauche/vminsn.h"
40 #include "gauche/prof.h"
41
42 #ifdef GAUCHE_PROFILE
43
44 /* WARNING: duplicated code - see signal.c; we should integrate them later */
45 #ifdef GAUCHE_USE_PTHREADS
46 #define SIGPROCMASK pthread_sigmask
47 #else /* windows doesn't care signals, so we don't check WTHREADS. */
48 #define SIGPROCMASK sigprocmask
49 #endif
50
51 /*=============================================================
52 * Interval timer operation
53 */
54
55 #define SAMPLING_PERIOD 10000
56
57 #if defined(GAUCHE_WINDOWS)
58
59 static void sampler_sample(ScmVM*);
60
61 static unsigned __stdcall observer_thread(void *arg)
62 {
63 ScmVM *vm = (ScmVM*)arg;
64 CONTEXT ctx;
65 DWORD sleep_time;
66 int suspend_flag = 0;
67
68 /* NB: We can't use Scm_SysError in this thread. */
69 /* NB: GetThreadContext might be required to make the target thread
70 certainly suspended. */
71 sleep_time = SAMPLING_PERIOD / 1000;
72 if (sleep_time <= 0) sleep_time = 1;
73 do {
74 if (!suspend_flag &&
75 SuspendThread(vm->prof->hTargetThread) != (DWORD)-1) {
76 ctx.ContextFlags = CONTEXT_CONTROL;
77 while (!GetThreadContext(vm->prof->hTargetThread, &ctx));
78 suspend_flag = 1;
79 sampler_sample(vm);
80 }
81 if (suspend_flag &&
82 ResumeThread(vm->prof->hTargetThread) != (DWORD)-1) {
83 suspend_flag = 0;
84 }
85 } while (WAIT_OBJECT_0 != WaitForSingleObject(vm->prof->hTimerEvent,
86 sleep_time));
87 return 0;
88 }
89
90 static void ITIMER_START(void)
91 {
92 ScmVM *vm = Scm_VM();
93
94 vm->prof->hTimerEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
95 if (vm->prof->hTimerEvent == NULL) {
96 Scm_SysError("CreateEvent failed");
97 }
98 /* NB: Prevent to use GC_beginthreadex here. */
99 #if defined(_beginthreadex)
100 #define _beginthreadex_orig _beginthreadex
101 #undef _beginthreadex
102 #endif
103 vm->prof->hObserverThread = (HANDLE)_beginthreadex(NULL, 0,
104 observer_thread,
105 (void*)vm, 0, NULL);
106 #if defined(_beginthreadex_orig)
107 #define _beginthreadex _beginthreadex_orig
108 #undef _beginthreadex_orig
109 #endif
110 if (vm->prof->hObserverThread == NULL) {
111 CloseHandle(vm->prof->hTimerEvent);
112 vm->prof->hTimerEvent = NULL;
113 Scm_SysError("_beginthreadex failed");
114 }
115 }
116
117 static void ITIMER_STOP(void)
118 {
119 ScmVM *vm = Scm_VM();
120
121 if (vm->prof->hTimerEvent != NULL && vm->prof->hObserverThread !=NULL) {
122 SetEvent(vm->prof->hTimerEvent);
123 WaitForSingleObject(vm->prof->hObserverThread, INFINITE);
124 }
125 if (vm->prof->hObserverThread != NULL) {
126 CloseHandle(vm->prof->hObserverThread);
127 vm->prof->hObserverThread = NULL;
128 }
129 if (vm->prof->hTimerEvent != NULL) {
130 CloseHandle(vm->prof->hTimerEvent);
131 vm->prof->hTimerEvent = NULL;
132 }
133 }
134
135 #else /* !GAUCHE_WINDOWS */
136
137 #define ITIMER_START() \
138 do { \
139 struct itimerval tval, oval; \
140 tval.it_interval.tv_sec = 0; \
141 tval.it_interval.tv_usec = SAMPLING_PERIOD; \
142 tval.it_value.tv_sec = 0; \
143 tval.it_value.tv_usec = SAMPLING_PERIOD; \
144 setitimer(ITIMER_PROF, &tval, &oval); \
145 } while (0)
146
147 #define ITIMER_STOP() \
148 do { \
149 struct itimerval tval, oval; \
150 tval.it_interval.tv_sec = 0; \
151 tval.it_interval.tv_usec = 0; \
152 tval.it_value.tv_sec = 0; \
153 tval.it_value.tv_usec = 0; \
154 setitimer(ITIMER_PROF, &tval, &oval); \
155 } while (0)
156
157 #endif /* !GAUCHE_WINDOWS */
158
159 /*=============================================================
160 * Statistic sampler
161 */
162
163 /* Flush sample buffer to the file.
164 We save the address value to the file. The address should also be
165 recorded in the call counter, thus we don't need to worry about
166 the addressed object being GCed. */
167
168 #define CHK(exp) do { if (!(exp)) goto bad; } while (0)
169
170 static void sampler_flush(ScmVM *vm)
171 {
172 if (vm->prof == NULL) return; /* for safety */
173 if (vm->prof->samplerFd < 0 || vm->prof->currentSample == 0) return;
174
175 int nsamples = vm->prof->currentSample;
176 ssize_t r = write(vm->prof->samplerFd, vm->prof->samples,
177 nsamples * sizeof(ScmProfSample[1]));
178 if (r == (ssize_t)-1) {
179 vm->prof->errorOccurred++;
180 }
181 vm->prof->currentSample = 0;
182 return;
183 }
184
185 /* signal handler */
186 #if defined(GAUCHE_WINDOWS)
187 static void sampler_sample(ScmVM *vm)
188 #else /* !GAUCHE_WINDOWS */
189 static void sampler_sample(int sig SCM_UNUSED)
190 #endif /* !GAUCHE_WINDOWS */
191 {
192 #if !defined(GAUCHE_WINDOWS)
193 ScmVM *vm = Scm_VM();
194 #endif /* !GAUCHE_WINDOWS */
195 if (vm == NULL || vm->prof == NULL) return;
196 if (vm->prof->state != SCM_PROFILER_RUNNING) return;
197
198 if (vm->prof->currentSample >= SCM_PROF_SAMPLES_IN_BUFFER) {
199 #if !defined(GAUCHE_WINDOWS)
200 ITIMER_STOP();
201 #endif /* !GAUCHE_WINDOWS */
202 sampler_flush(vm);
203 #if !defined(GAUCHE_WINDOWS)
204 ITIMER_START();
205 #endif /* !GAUCHE_WINDOWS */
206 }
207
208 int i = vm->prof->currentSample++;
209 if (vm->base) {
210 /* If vm->pc is RET and val0 is a subr, it is pretty likely that
211 we're actually executing that subr. */
212 if (vm->pc && SCM_VM_INSN_CODE(*vm->pc) == SCM_VM_RET
213 && SCM_SUBRP(vm->val0)) {
214 vm->prof->samples[i].func = vm->val0;
215 vm->prof->samples[i].pc = NULL;
216 } else {
217 vm->prof->samples[i].func = SCM_OBJ(vm->base);
218 vm->prof->samples[i].pc = vm->pc;
219 }
220 } else {
221 vm->prof->samples[i].func = SCM_FALSE;
222 vm->prof->samples[i].pc = NULL;
223 }
224 vm->prof->totalSamples++;
225 }
226
227 /* register samples into the stat table. Called from Scm_ProfilerResult */
228 void collect_samples(ScmVMProfiler *prof)
229 {
230 for (int i=0; i<prof->currentSample; i++) {
231 ScmObj e = Scm_HashTableRef(prof->statHash,
232 prof->samples[i].func, SCM_UNBOUND);
233 if (SCM_UNBOUNDP(e)) {
234 /* NB: just for now */
235 Scm_Warn("profiler: uncounted object appeared in a sample: %p (%S)",
236 prof->samples[i].func, prof->samples[i].func);
237 } else {
238 SCM_ASSERT(SCM_PAIRP(e));
239 SCM_SET_CDR_UNCHECKED(e, Scm_Add(SCM_CDR(e), SCM_MAKE_INT(1)));
240 }
241 }
242 }
243
244 /*=============================================================
245 * Call Counter
246 */
247
248 /* Inserting data into array is done in a macro (prof.h). It calls
249 this flush routine when the array gets full. */
250
251 void Scm_ProfilerCountBufferFlush(ScmVM *vm)
252 {
253 if (vm->prof == NULL) return; /* for safety */
254 if (vm->prof->currentCount == 0) return;
255
256 /* suspend itimer during hash table operation */
257 #if !defined(GAUCHE_WINDOWS)
258 sigset_t set;
259 sigemptyset(&set);
260 sigaddset(&set, SIGPROF);
261 SIGPROCMASK(SIG_BLOCK, &set, NULL);
262 #endif /* !GAUCHE_WINDOWS */
263
264 int ncounts = vm->prof->currentCount;
265 for (int i=0; i<ncounts; i++) {
266 ScmObj e;
267
268 ScmObj func = vm->prof->counts[i].func;
269 if (SCM_METHODP(func) && SCM_METHOD(func)->func == NULL) {
270 /* func is Scheme-defined method. Record the code of
271 method body, so that we can match it with sampling
272 profiler later. */
273 func = SCM_OBJ(SCM_METHOD(func)->data);
274 }
275
276 e = Scm_HashTableRef(vm->prof->statHash, func, SCM_UNBOUND);
277 if (SCM_UNBOUNDP(e)) {
278 e = Scm_Cons(SCM_MAKE_INT(0), SCM_MAKE_INT(0));
279 Scm_HashTableSet(vm->prof->statHash, func, e, 0);
280 }
281 SCM_ASSERT(SCM_PAIRP(e));
282 SCM_SET_CAR_UNCHECKED(e, Scm_Add(SCM_CAR(e), SCM_MAKE_INT(1)));
283 }
284 vm->prof->currentCount = 0;
285
286 /* resume itimer */
287 #if !defined(GAUCHE_WINDOWS)
288 SIGPROCMASK(SIG_UNBLOCK, &set, NULL);
289 #endif /* !GAUCHE_WINDOWS */
290 }
291
292 /*=============================================================
293 * External API
294 */
295 void Scm_ProfilerStart(void)
296 {
297 ScmVM *vm = Scm_VM();
298 ScmObj templat = Scm_StringAppendC(SCM_STRING(Scm_TmpDir()),
299 "/gauche-profXXXXXX", -1, -1);
300 char *templat_buf = Scm_GetString(SCM_STRING(templat)); /*mutable copy*/
301
302 if (!vm->prof) {
303 vm->prof = SCM_NEW(ScmVMProfiler);
304 vm->prof->state = SCM_PROFILER_INACTIVE;
305 vm->prof->samplerFd = Scm_Mkstemp(templat_buf);
306 vm->prof->currentSample = 0;
307 vm->prof->totalSamples = 0;
308 vm->prof->errorOccurred = 0;
309 vm->prof->currentCount = 0;
310 vm->prof->statHash =
311 SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_EQ, 0));
312 #if defined(GAUCHE_WINDOWS)
313 vm->prof->hTargetThread = NULL;
314 vm->prof->hObserverThread = NULL;
315 vm->prof->hTimerEvent = NULL;
316 vm->prof->samplerFileName = templat_buf;
317 #else /* !GAUCHE_WINDOWS */
318 unlink(templat_buf); /* keep anonymous tmpfile */
319 #endif /* !GAUCHE_WINDOWS */
320 } else if (vm->prof->samplerFd < 0) {
321 vm->prof->samplerFd = Scm_Mkstemp(templat_buf);
322 #if defined(GAUCHE_WINDOWS)
323 vm->prof->samplerFileName = templat_buf;
324 #else /* !GAUCHE_WINDOWS */
325 unlink(templat_buf);
326 #endif /* !GAUCHE_WINDOWS */
327 }
328
329 if (vm->prof->state == SCM_PROFILER_RUNNING) return;
330 vm->prof->state = SCM_PROFILER_RUNNING;
331 vm->profilerRunning = TRUE;
332
333 /* NB: this should be done globally!!! */
334 #if defined(GAUCHE_WINDOWS)
335 if (!DuplicateHandle(GetCurrentProcess(),
336 GetCurrentThread(),
337 GetCurrentProcess(),
338 &vm->prof->hTargetThread,
339 0, FALSE, DUPLICATE_SAME_ACCESS)) {
340 vm->prof->hTargetThread = NULL;
341 Scm_SysError("DuplicateHandle failed");
342 }
343 #else /* !GAUCHE_WINDOWS */
344 struct sigaction act;
345 act.sa_handler = sampler_sample;
346 sigfillset(&act.sa_mask);
347 act.sa_flags = SA_RESTART;
348 if (sigaction(SIGPROF, &act, NULL) < 0) {
349 Scm_SysError("sigaction failed");
350 }
351 #endif /* !GAUCHE_WINDOWS */
352
353 ITIMER_START();
354 }
355
356 int Scm_ProfilerStop(void)
357 {
358 ScmVM *vm = Scm_VM();
359 if (vm->prof == NULL) return 0;
360 if (vm->prof->state != SCM_PROFILER_RUNNING) return 0;
361 ITIMER_STOP();
362 #if defined(GAUCHE_WINDOWS)
363 if (vm->prof->hTargetThread != NULL) {
364 CloseHandle(vm->prof->hTargetThread);
365 vm->prof->hTargetThread = NULL;
366 }
367 #endif /* GAUCHE_WINDOWS */
368 vm->prof->state = SCM_PROFILER_PAUSING;
369 vm->profilerRunning = FALSE;
370 return vm->prof->totalSamples;
371 }
372
373 void Scm_ProfilerReset(void)
374 {
375 ScmVM *vm = Scm_VM();
376
377 if (vm->prof == NULL) return;
378 if (vm->prof->state == SCM_PROFILER_INACTIVE) return;
379 if (vm->prof->state == SCM_PROFILER_RUNNING) Scm_ProfilerStop();
380
381 if (vm->prof->samplerFd >= 0) {
382 close(vm->prof->samplerFd);
383 vm->prof->samplerFd = -1;
384 #if defined(GAUCHE_WINDOWS)
385 unlink(vm->prof->samplerFileName);
386 #endif /* GAUCHE_WINDOWS */
387 }
388 vm->prof->totalSamples = 0;
389 vm->prof->currentSample = 0;
390 vm->prof->errorOccurred = 0;
391 vm->prof->currentCount = 0;
392 vm->prof->statHash =
393 SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_EQ, 0));
394 vm->prof->state = SCM_PROFILER_INACTIVE;
395 }
396
397 /* Returns the statHash */
398 ScmObj Scm_ProfilerRawResult(void)
399 {
400 ScmVM *vm = Scm_VM();
401
402 if (vm->prof == NULL) return SCM_FALSE;
403 if (vm->prof->state == SCM_PROFILER_INACTIVE) return SCM_FALSE;
404 if (vm->prof->state == SCM_PROFILER_RUNNING) Scm_ProfilerStop();
405
406 if (vm->prof->errorOccurred > 0) {
407 Scm_Warn("profiler: An error has been occurred during saving profiling samples. The result may not be accurate");
408 }
409
410 Scm_ProfilerCountBufferFlush(vm);
411
412 /* collect samples in the current buffer */
413 collect_samples(vm->prof);
414
415 /* collect samples in the saved file */
416 off_t off;
417 SCM_SYSCALL(off, lseek(vm->prof->samplerFd, 0, SEEK_SET));
418 if (off == (off_t)-1) {
419 Scm_ProfilerReset();
420 Scm_Error("profiler: seek failed in retrieving sample data");
421 }
422 for (;;) {
423 ssize_t r = read(vm->prof->samplerFd, vm->prof->samples,
424 sizeof(ScmProfSample[1]) * SCM_PROF_SAMPLES_IN_BUFFER);
425 if (r <= 0) break;
426 vm->prof->currentSample = r / sizeof(ScmProfSample[1]);
427 collect_samples(vm->prof);
428 }
429 vm->prof->currentSample = 0;
430 #if defined(GAUCHE_WINDOWS)
431 if (vm->prof->samplerFd >= 0) {
432 close(vm->prof->samplerFd);
433 vm->prof->samplerFd = -1;
434 unlink(vm->prof->samplerFileName);
435 }
436 #else /* !GAUCHE_WINDOWS */
437 if (ftruncate(vm->prof->samplerFd, 0) < 0) {
438 Scm_SysError("profiler: failed to truncate temporary file");
439 }
440 #endif /* !GAUCHE_WINDOWS */
441
442 return SCM_OBJ(vm->prof->statHash);
443 }
444
445 #else /* !GAUCHE_PROFILE */
446 void Scm_ProfilerStart(void)
447 {
448 Scm_Error("profiler is not supported.");
449 }
450
451 int Scm_ProfilerStop(void)
452 {
453 Scm_Error("profiler is not supported.");
454 return 0;
455 }
456
457 void Scm_ProfilerReset(void)
458 {
459 Scm_Error("profiler is not supported.");
460 }
461
462 ScmObj Scm_ProfilerRawResult(void)
463 {
464 Scm_Error("profiler is not supported.");
465 return SCM_FALSE;
466 }
467 #endif /* !GAUCHE_PROFILE */