Debian Codegraph @

js/src/builtin/Profilers.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* Profiling-related API */
8
9 #include "builtin/Profilers.h"
10
11 #include "mozilla/Compiler.h"
12 #include "mozilla/Sprintf.h"
13
14 #include <iterator>
15 #include <stdarg.h>
16
17 #include "util/GetPidProvider.h" // getpid()
18
19 #ifdef MOZ_CALLGRIND
20 # include <valgrind/callgrind.h>
21 #endif
22
23 #ifdef __APPLE__
24 # ifdef MOZ_INSTRUMENTS
25 # include "devtools/Instruments.h"
26 # endif
27 #endif
28
29 #include "js/CharacterEncoding.h"
30 #include "js/PropertyAndElement.h" // JS_DefineFunctions
31 #include "js/PropertySpec.h"
32 #include "js/Utility.h"
33 #include "util/Text.h"
34 #include "vm/Probes.h"
35
36 #include "vm/JSContext-inl.h"
37
38 using namespace js;
39
40 /* Thread-unsafe error management */
41
42 static char gLastError[2000];
43
44 #if defined(__APPLE__) || defined(__linux__) || defined(MOZ_CALLGRIND)
45 static void MOZ_FORMAT_PRINTF(1, 2) UnsafeError(const char* format, ...) {
46 va_list args;
47 va_start(args, format);
48 (void)VsprintfLiteral(gLastError, format, args);
49 va_end(args);
50 }
51 #endif
52
53 JS_PUBLIC_API const char* JS_UnsafeGetLastProfilingError() {
54 return gLastError;
55 }
56
57 #ifdef __APPLE__
58 static bool StartOSXProfiling(const char* profileName, pid_t pid) {
59 bool ok = true;
60 const char* profiler = nullptr;
61 # ifdef MOZ_INSTRUMENTS
62 ok = Instruments::Start(pid);
63 profiler = "Instruments";
64 # endif
65 if (!ok) {
66 if (profileName) {
67 UnsafeError("Failed to start %s for %s", profiler, profileName);
68 } else {
69 UnsafeError("Failed to start %s", profiler);
70 }
71 return false;
72 }
73 return true;
74 }
75 #endif
76
77 JS_PUBLIC_API bool JS_StartProfiling(const char* profileName, pid_t pid) {
78 bool ok = true;
79 #ifdef __APPLE__
80 ok = StartOSXProfiling(profileName, pid);
81 #endif
82 #ifdef __linux__
83 if (!js_StartPerf(profileName)) {
84 ok = false;
85 }
86 #endif
87 return ok;
88 }
89
90 JS_PUBLIC_API bool JS_StopProfiling(const char* profileName) {
91 bool ok = true;
92 #ifdef __APPLE__
93 # ifdef MOZ_INSTRUMENTS
94 Instruments::Stop(profileName);
95 # endif
96 #endif
97 #ifdef __linux__
98 if (!js_StopPerf()) {
99 ok = false;
100 }
101 #endif
102 return ok;
103 }
104
105 /*
106 * Start or stop whatever platform- and configuration-specific profiling
107 * backends are available.
108 */
109 static bool ControlProfilers(bool toState) {
110 bool ok = true;
111
112 if (!probes::ProfilingActive && toState) {
113 #ifdef __APPLE__
114 # if defined(MOZ_INSTRUMENTS)
115 const char* profiler;
116 # ifdef MOZ_INSTRUMENTS
117 ok = Instruments::Resume();
118 profiler = "Instruments";
119 # endif
120 if (!ok) {
121 UnsafeError("Failed to start %s", profiler);
122 }
123 # endif
124 #endif
125 #ifdef MOZ_CALLGRIND
126 if (!js_StartCallgrind()) {
127 UnsafeError("Failed to start Callgrind");
128 ok = false;
129 }
130 #endif
131 } else if (probes::ProfilingActive && !toState) {
132 #ifdef __APPLE__
133 # ifdef MOZ_INSTRUMENTS
134 Instruments::Pause();
135 # endif
136 #endif
137 #ifdef MOZ_CALLGRIND
138 if (!js_StopCallgrind()) {
139 UnsafeError("failed to stop Callgrind");
140 ok = false;
141 }
142 #endif
143 }
144
145 probes::ProfilingActive = toState;
146
147 return ok;
148 }
149
150 /*
151 * Pause/resume whatever profiling mechanism is currently compiled
152 * in, if applicable. This will not affect things like dtrace.
153 *
154 * Do not mix calls to these APIs with calls to the individual
155 * profilers' pause/resume functions, because only overall state is
156 * tracked, not the state of each profiler.
157 */
158 JS_PUBLIC_API bool JS_PauseProfilers(const char* profileName) {
159 return ControlProfilers(false);
160 }
161
162 JS_PUBLIC_API bool JS_ResumeProfilers(const char* profileName) {
163 return ControlProfilers(true);
164 }
165
166 JS_PUBLIC_API bool JS_DumpProfile(const char* outfile,
167 const char* profileName) {
168 bool ok = true;
169 #ifdef MOZ_CALLGRIND
170 ok = js_DumpCallgrind(outfile);
171 #endif
172 return ok;
173 }
174
175 #ifdef MOZ_PROFILING
176
177 static UniqueChars RequiredStringArg(JSContext* cx, const CallArgs& args,
178 size_t argi, const char* caller) {
179 if (args.length() <= argi) {
180 JS_ReportErrorASCII(cx, "%s: not enough arguments", caller);
181 return nullptr;
182 }
183
184 if (!args[argi].isString()) {
185 JS_ReportErrorASCII(cx, "%s: invalid arguments (string expected)", caller);
186 return nullptr;
187 }
188
189 return JS_EncodeStringToLatin1(cx, args[argi].toString());
190 }
191
192 static bool StartProfiling(JSContext* cx, unsigned argc, Value* vp) {
193 CallArgs args = CallArgsFromVp(argc, vp);
194 if (args.length() == 0) {
195 args.rval().setBoolean(JS_StartProfiling(nullptr, getpid()));
196 return true;
197 }
198
199 UniqueChars profileName = RequiredStringArg(cx, args, 0, "startProfiling");
200 if (!profileName) {
201 return false;
202 }
203
204 if (args.length() == 1) {
205 args.rval().setBoolean(JS_StartProfiling(profileName.get(), getpid()));
206 return true;
207 }
208
209 if (!args[1].isInt32()) {
210 JS_ReportErrorASCII(cx, "startProfiling: invalid arguments (int expected)");
211 return false;
212 }
213 pid_t pid = static_cast<pid_t>(args[1].toInt32());
214 args.rval().setBoolean(JS_StartProfiling(profileName.get(), pid));
215 return true;
216 }
217
218 static bool StopProfiling(JSContext* cx, unsigned argc, Value* vp) {
219 CallArgs args = CallArgsFromVp(argc, vp);
220 if (args.length() == 0) {
221 args.rval().setBoolean(JS_StopProfiling(nullptr));
222 return true;
223 }
224
225 UniqueChars profileName = RequiredStringArg(cx, args, 0, "stopProfiling");
226 if (!profileName) {
227 return false;
228 }
229 args.rval().setBoolean(JS_StopProfiling(profileName.get()));
230 return true;
231 }
232
233 static bool PauseProfilers(JSContext* cx, unsigned argc, Value* vp) {
234 CallArgs args = CallArgsFromVp(argc, vp);
235 if (args.length() == 0) {
236 args.rval().setBoolean(JS_PauseProfilers(nullptr));
237 return true;
238 }
239
240 UniqueChars profileName = RequiredStringArg(cx, args, 0, "pauseProfiling");
241 if (!profileName) {
242 return false;
243 }
244 args.rval().setBoolean(JS_PauseProfilers(profileName.get()));
245 return true;
246 }
247
248 static bool ResumeProfilers(JSContext* cx, unsigned argc, Value* vp) {
249 CallArgs args = CallArgsFromVp(argc, vp);
250 if (args.length() == 0) {
251 args.rval().setBoolean(JS_ResumeProfilers(nullptr));
252 return true;
253 }
254
255 UniqueChars profileName = RequiredStringArg(cx, args, 0, "resumeProfiling");
256 if (!profileName) {
257 return false;
258 }
259 args.rval().setBoolean(JS_ResumeProfilers(profileName.get()));
260 return true;
261 }
262
263 /* Usage: DumpProfile([filename[, profileName]]) */
264 static bool DumpProfile(JSContext* cx, unsigned argc, Value* vp) {
265 bool ret;
266 CallArgs args = CallArgsFromVp(argc, vp);
267 if (args.length() == 0) {
268 ret = JS_DumpProfile(nullptr, nullptr);
269 } else {
270 UniqueChars filename = RequiredStringArg(cx, args, 0, "dumpProfile");
271 if (!filename) {
272 return false;
273 }
274
275 if (args.length() == 1) {
276 ret = JS_DumpProfile(filename.get(), nullptr);
277 } else {
278 UniqueChars profileName = RequiredStringArg(cx, args, 1, "dumpProfile");
279 if (!profileName) {
280 return false;
281 }
282
283 ret = JS_DumpProfile(filename.get(), profileName.get());
284 }
285 }
286
287 args.rval().setBoolean(ret);
288 return true;
289 }
290
291 static bool GetMaxGCPauseSinceClear(JSContext* cx, unsigned argc, Value* vp) {
292 CallArgs args = CallArgsFromVp(argc, vp);
293 args.rval().setNumber(
294 cx->runtime()->gc.stats().getMaxGCPauseSinceClear().ToMicroseconds());
295 return true;
296 }
297
298 static bool ClearMaxGCPauseAccumulator(JSContext* cx, unsigned argc,
299 Value* vp) {
300 CallArgs args = CallArgsFromVp(argc, vp);
301 args.rval().setNumber(
302 cx->runtime()->gc.stats().clearMaxGCPauseAccumulator().ToMicroseconds());
303 return true;
304 }
305
306 # if defined(MOZ_INSTRUMENTS)
307
308 static bool IgnoreAndReturnTrue(JSContext* cx, unsigned argc, Value* vp) {
309 CallArgs args = CallArgsFromVp(argc, vp);
310 args.rval().setBoolean(true);
311 return true;
312 }
313
314 # endif
315
316 # ifdef MOZ_CALLGRIND
317 static bool StartCallgrind(JSContext* cx, unsigned argc, Value* vp) {
318 CallArgs args = CallArgsFromVp(argc, vp);
319 args.rval().setBoolean(js_StartCallgrind());
320 return true;
321 }
322
323 static bool StopCallgrind(JSContext* cx, unsigned argc, Value* vp) {
324 CallArgs args = CallArgsFromVp(argc, vp);
325 args.rval().setBoolean(js_StopCallgrind());
326 return true;
327 }
328
329 static bool DumpCallgrind(JSContext* cx, unsigned argc, Value* vp) {
330 CallArgs args = CallArgsFromVp(argc, vp);
331 if (args.length() == 0) {
332 args.rval().setBoolean(js_DumpCallgrind(nullptr));
333 return true;
334 }
335
336 UniqueChars outFile = RequiredStringArg(cx, args, 0, "dumpCallgrind");
337 if (!outFile) {
338 return false;
339 }
340
341 args.rval().setBoolean(js_DumpCallgrind(outFile.get()));
342 return true;
343 }
344 # endif
345
346 static const JSFunctionSpec profiling_functions[] = {
347 JS_FN("startProfiling", StartProfiling, 1, 0),
348 JS_FN("stopProfiling", StopProfiling, 1, 0),
349 JS_FN("pauseProfilers", PauseProfilers, 1, 0),
350 JS_FN("resumeProfilers", ResumeProfilers, 1, 0),
351 JS_FN("dumpProfile", DumpProfile, 2, 0),
352 JS_FN("getMaxGCPauseSinceClear", GetMaxGCPauseSinceClear, 0, 0),
353 JS_FN("clearMaxGCPauseAccumulator", ClearMaxGCPauseAccumulator, 0, 0),
354 # if defined(MOZ_INSTRUMENTS)
355 /* Keep users of the old shark API happy. */
356 JS_FN("connectShark", IgnoreAndReturnTrue, 0, 0),
357 JS_FN("disconnectShark", IgnoreAndReturnTrue, 0, 0),
358 JS_FN("startShark", StartProfiling, 0, 0),
359 JS_FN("stopShark", StopProfiling, 0, 0),
360 # endif
361 # ifdef MOZ_CALLGRIND
362 JS_FN("startCallgrind", StartCallgrind, 0, 0),
363 JS_FN("stopCallgrind", StopCallgrind, 0, 0),
364 JS_FN("dumpCallgrind", DumpCallgrind, 1, 0),
365 # endif
366 JS_FS_END,
367 };
368
369 #endif
370
371 JS_PUBLIC_API bool JS_DefineProfilingFunctions(JSContext* cx,
372 HandleObject obj) {
373 cx->check(obj);
374 #ifdef MOZ_PROFILING
375 return JS_DefineFunctions(cx, obj, profiling_functions);
376 #else
377 return true;
378 #endif
379 }
380
381 #ifdef MOZ_CALLGRIND
382
383 /* Wrapper for various macros to stop warnings coming from their expansions. */
384 # if defined(__clang__)
385 # define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \
386 JS_BEGIN_MACRO \
387 _Pragma("clang diagnostic push") /* If these _Pragmas cause warnings \
388 for you, try disabling ccache. */ \
389 _Pragma("clang diagnostic ignored \"-Wunused-value\"") { \
390 expr; \
391 } \
392 _Pragma("clang diagnostic pop") \
393 JS_END_MACRO
394 # elif MOZ_IS_GCC
395
396 # define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \
397 JS_BEGIN_MACRO \
398 _Pragma("GCC diagnostic push") \
399 _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") \
400 expr; \
401 _Pragma("GCC diagnostic pop") \
402 JS_END_MACRO
403 # endif
404
405 # if !defined(JS_SILENCE_UNUSED_VALUE_IN_EXPR)
406 # define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \
407 JS_BEGIN_MACRO \
408 expr; \
409 JS_END_MACRO
410 # endif
411
412 JS_PUBLIC_API bool js_StartCallgrind() {
413 JS_SILENCE_UNUSED_VALUE_IN_EXPR(CALLGRIND_START_INSTRUMENTATION);
414 JS_SILENCE_UNUSED_VALUE_IN_EXPR(CALLGRIND_ZERO_STATS);
415 return true;
416 }
417
418 JS_PUBLIC_API bool js_StopCallgrind() {
419 JS_SILENCE_UNUSED_VALUE_IN_EXPR(CALLGRIND_STOP_INSTRUMENTATION);
420 return true;
421 }
422
423 JS_PUBLIC_API bool js_DumpCallgrind(const char* outfile) {
424 if (outfile) {
425 JS_SILENCE_UNUSED_VALUE_IN_EXPR(CALLGRIND_DUMP_STATS_AT(outfile));
426 } else {
427 JS_SILENCE_UNUSED_VALUE_IN_EXPR(CALLGRIND_DUMP_STATS);
428 }
429
430 return true;
431 }
432
433 #endif /* MOZ_CALLGRIND */
434
435 #ifdef __linux__
436
437 /*
438 * Code for starting and stopping |perf|, the Linux profiler.
439 *
440 * Output from profiling is written to mozperf.data in your cwd.
441 *
442 * To enable, set MOZ_PROFILE_WITH_PERF=1 in your environment.
443 *
444 * To pass additional parameters to |perf record|, provide them in the
445 * MOZ_PROFILE_PERF_FLAGS environment variable. If this variable does not
446 * exist, we default it to "-g". (If you don't want -g but don't want to
447 * pass any other args, define MOZ_PROFILE_PERF_FLAGS to the empty string.)
448 *
449 * If you include --pid or --output in MOZ_PROFILE_PERF_FLAGS, you're just
450 * asking for trouble.
451 *
452 * Our split-on-spaces logic is lame, so don't expect MOZ_PROFILE_PERF_FLAGS to
453 * work if you pass an argument which includes a space (e.g.
454 * MOZ_PROFILE_PERF_FLAGS="-e 'foo bar'").
455 */
456
457 # include <signal.h>
458 # include <sys/wait.h>
459 # include <unistd.h>
460
461 static bool perfInitialized = false;
462 static pid_t perfPid = 0;
463
464 bool js_StartPerf(const char* profileName) {
465 const char* outfile =
466 (profileName && profileName[0]) ? profileName : "mozperf.data";
467
468 if (perfPid != 0) {
469 UnsafeError("js_StartPerf: called while perf was already running!\n");
470 return false;
471 }
472
473 // Bail if MOZ_PROFILE_WITH_PERF is empty or undefined.
474 if (!getenv("MOZ_PROFILE_WITH_PERF") ||
475 !strlen(getenv("MOZ_PROFILE_WITH_PERF"))) {
476 return true;
477 }
478
479 /*
480 * Delete mozperf.data the first time through -- we're going to append to it
481 * later on, so we want it to be clean when we start out.
482 */
483 if (!perfInitialized) {
484 perfInitialized = true;
485 unlink(outfile);
486 char cwd[4096];
487 printf("Writing perf profiling data to %s/%s\n", getcwd(cwd, sizeof(cwd)),
488 outfile);
489 }
490
491 pid_t mainPid = getpid();
492
493 pid_t childPid = fork();
494 if (childPid == 0) {
495 /* perf record --pid $mainPID --output=$outfile $MOZ_PROFILE_PERF_FLAGS */
496
497 char mainPidStr[16];
498 SprintfLiteral(mainPidStr, "%d", mainPid);
499 const char* defaultArgs[] = {"perf", "record", "--pid",
500 mainPidStr, "--output", outfile};
501
502 Vector<const char*, 0, SystemAllocPolicy> args;
503 if (!args.append(defaultArgs, std::size(defaultArgs))) {
504 return false;
505 }
506
507 const char* flags = getenv("MOZ_PROFILE_PERF_FLAGS");
508 if (!flags) {
509 flags = "-g";
510 }
511
512 UniqueChars flags2 = DuplicateString(flags);
513 if (!flags2) {
514 return false;
515 }
516
517 // Split |flags2| on spaces.
518 char* toksave;
519 char* tok = strtok_r(flags2.get(), " ", &toksave);
520 while (tok) {
521 if (!args.append(tok)) {
522 return false;
523 }
524 tok = strtok_r(nullptr, " ", &toksave);
525 }
526
527 if (!args.append((char*)nullptr)) {
528 return false;
529 }
530
531 execvp("perf", const_cast<char**>(args.begin()));
532
533 /* Reached only if execlp fails. */
534 fprintf(stderr, "Unable to start perf.\n");
535 exit(1);
536 }
537 if (childPid > 0) {
538 perfPid = childPid;
539
540 /* Give perf a chance to warm up. */
541 usleep(500 * 1000);
542 return true;
543 }
544 UnsafeError("js_StartPerf: fork() failed\n");
545 return false;
546 }
547
548 bool js_StopPerf() {
549 if (perfPid == 0) {
550 UnsafeError("js_StopPerf: perf is not running.\n");
551 return true;
552 }
553
554 if (kill(perfPid, SIGINT)) {
555 UnsafeError("js_StopPerf: kill failed\n");
556
557 // Try to reap the process anyway.
558 waitpid(perfPid, nullptr, WNOHANG);
559 } else {
560 waitpid(perfPid, nullptr, 0);
561 }
562
563 perfPid = 0;
564 return true;
565 }
566
567 #endif /* __linux__ */