-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathBunCPUProfiler.cpp
More file actions
1258 lines (1094 loc) · 50.6 KB
/
BunCPUProfiler.cpp
File metadata and controls
1258 lines (1094 loc) · 50.6 KB
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
#include "root.h"
#include "BunCPUProfiler.h"
#include "ZigGlobalObject.h"
#include "helpers.h"
#include "BunString.h"
#include <JavaScriptCore/SamplingProfiler.h>
#include <JavaScriptCore/VM.h>
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/ScriptExecutable.h>
#include <JavaScriptCore/FunctionExecutable.h>
#include <JavaScriptCore/SourceProvider.h>
#include <wtf/Stopwatch.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/JSONValues.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/URL.h>
#include <algorithm>
#include <limits>
extern "C" void Bun__startCPUProfiler(JSC::VM* vm);
extern "C" void Bun__stopCPUProfiler(JSC::VM* vm, BunString* outJSON, BunString* outText);
extern "C" void Bun__setSamplingInterval(int intervalMicroseconds);
void Bun__setSamplingInterval(int intervalMicroseconds)
{
Bun::setSamplingInterval(intervalMicroseconds);
}
namespace Bun {
// Store the profiling start time in microseconds since Unix epoch
static double s_profilingStartTime = 0.0;
// Set sampling interval to 1ms (1000 microseconds) to match Node.js
static int s_samplingInterval = 1000;
static bool s_isProfilerRunning = false;
void setSamplingInterval(int intervalMicroseconds)
{
s_samplingInterval = intervalMicroseconds;
}
bool isCPUProfilerRunning()
{
return s_isProfilerRunning;
}
void startCPUProfiler(JSC::VM& vm)
{
// Capture the wall clock time when profiling starts (before creating stopwatch)
// This will be used as the profile's startTime
s_profilingStartTime = MonotonicTime::now().approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
// Create a stopwatch and start it
auto stopwatch = WTF::Stopwatch::create();
stopwatch->start();
JSC::SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(WTF::move(stopwatch));
samplingProfiler.setTimingInterval(WTF::Seconds::fromMicroseconds(s_samplingInterval));
samplingProfiler.noticeCurrentThreadAsJSCExecutionThread();
samplingProfiler.start();
s_isProfilerRunning = true;
}
struct ProfileNode {
int id;
WTF::String functionName;
WTF::String url;
int scriptId;
// lineNumber/columnNumber are the location where the function is DEFINED
// (matching Node/Deno/Chrome DevTools), stored as 0-indexed values ready
// for JSON emission. -1 means "unknown".
int lineNumber;
int columnNumber;
int hitCount;
WTF::Vector<int> children;
// Per-line sample counts for this node, keyed by 1-indexed source line.
// Emitted as `positionTicks` in the JSON output when non-empty, matching
// the Chrome DevTools CPU profile format used by Node and Deno.
// Lines are guaranteed non-zero, so the default IntHashTraits (which reserve
// 0 and -1 as empty/deleted sentinels) are safe here.
WTF::HashMap<int, int, WTF::IntHash<int>> positionTicks;
};
WTF::String stopCPUProfilerAndGetJSON(JSC::VM& vm)
{
s_isProfilerRunning = false;
JSC::SamplingProfiler* profiler = vm.samplingProfiler();
if (!profiler)
return WTF::String();
// JSLock is re-entrant, so always acquiring it handles both JS and shutdown contexts
JSC::JSLockHolder locker(vm);
// Defer GC while we're working with stack traces
JSC::DeferGC deferGC(vm);
// Pause the profiler while holding the lock - this is critical for thread safety.
// The sampling thread holds this lock while modifying traces, so holding it here
// ensures no concurrent modifications. We use pause() instead of shutdown() to
// allow the profiler to be restarted for the inspector API.
auto& lock = profiler->getLock();
WTF::Locker profilerLocker { lock };
profiler->pause();
// releaseStackTraces() calls processUnverifiedStackTraces() internally
auto stackTraces = profiler->releaseStackTraces();
profiler->clearData();
// Build Chrome CPU Profiler format
// Map from stack frame signature to node ID
WTF::HashMap<WTF::String, int> nodeMap;
WTF::Vector<ProfileNode> nodes;
// Create root node
ProfileNode rootNode;
rootNode.id = 1;
rootNode.functionName = "(root)"_s;
rootNode.url = ""_s;
rootNode.scriptId = 0;
rootNode.lineNumber = -1;
rootNode.columnNumber = -1;
rootNode.hitCount = 0;
nodes.append(WTF::move(rootNode));
int nextNodeId = 2;
WTF::Vector<int> samples;
WTF::Vector<long long> timeDeltas;
// Create an index array to process stack traces in chronological order
// We can't sort stackTraces directly because StackTrace has deleted copy assignment
WTF::Vector<size_t> sortedIndices;
sortedIndices.reserveInitialCapacity(stackTraces.size());
for (size_t i = 0; i < stackTraces.size(); i++) {
sortedIndices.append(i);
}
// Sort indices by monotonic timestamp to ensure chronological order
// Use timestamp instead of stopwatchTimestamp for better resolution
// This is critical for calculating correct timeDeltas between samples
std::sort(sortedIndices.begin(), sortedIndices.end(), [&stackTraces](size_t a, size_t b) {
return stackTraces[a].timestamp < stackTraces[b].timestamp;
});
// Use the profiling start time that was captured when profiling began
// This ensures the first timeDelta represents the time from profiling start to first sample
double startTime = s_profilingStartTime;
double lastTime = s_profilingStartTime;
// Process each stack trace in chronological order
for (size_t idx : sortedIndices) {
auto& stackTrace = stackTraces[idx];
if (stackTrace.frames.isEmpty()) {
samples.append(1); // Root node
// Use monotonic timestamp converted to wall clock time
double currentTime = stackTrace.timestamp.approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
double delta = std::max(0.0, currentTime - lastTime);
timeDeltas.append(static_cast<long long>(delta));
lastTime = currentTime;
continue;
}
int currentParentId = 1; // Start from root
// Process frames from bottom to top (reverse order for Chrome format)
for (int i = stackTrace.frames.size() - 1; i >= 0; i--) {
auto& frame = stackTrace.frames[i];
WTF::String functionName;
WTF::String url;
int scriptId = 0;
// Function-definition line/column (0-indexed for JSON emit, matching
// Node/Deno/Chrome DevTools). -1 means "unknown".
int functionDefLine = -1;
int functionDefColumn = -1;
// Current-sample line (1-indexed) — fed to positionTicks when this
// frame is the top of the stack. 0 means "unknown".
int sampleLine = 0;
// Get function name - displayName works for all frame types
functionName = frame.displayName(vm);
if (frame.frameType == JSC::SamplingProfiler::FrameType::Executable && frame.executable) {
auto sourceProviderAndID = frame.sourceProviderAndID();
auto* provider = std::get<0>(sourceProviderAndID);
if (provider) {
url = provider->sourceURL();
scriptId = static_cast<int>(provider->asID());
// Convert absolute paths to file:// URLs
// Check for:
// - Unix absolute path: /path/to/file
// - Windows drive letter: C:\path or C:/path
// - Windows UNC path: \\server\share
bool isAbsolutePath = false;
if (!url.isEmpty()) {
if (url[0] == '/') {
// Unix absolute path
isAbsolutePath = true;
} else if (url.length() >= 2 && url[1] == ':') {
// Windows drive letter (e.g., C:\)
char firstChar = url[0];
if ((firstChar >= 'A' && firstChar <= 'Z') || (firstChar >= 'a' && firstChar <= 'z')) {
isAbsolutePath = true;
}
} else if (url.length() >= 2 && url[0] == '\\' && url[1] == '\\') {
// Windows UNC path (e.g., \\server\share)
isAbsolutePath = true;
}
}
if (isAbsolutePath) {
url = WTF::URL::fileURLWithFileSystemPath(url).string();
}
}
// Function definition location. JSC returns these 1-based;
// Node/Deno/Chrome DevTools emit them 0-based in the JSON.
// We remap this (not the sample position) through the
// sourcemap callback so callFrame.url/line/column all agree
// on the function's DEFINITION site — bundled/transpiled
// scripts then report the original source for the node while
// positionTicks reports original-source sample lines.
int rawFunctionStartLine = frame.functionStartLine();
unsigned rawFunctionStartColumn = frame.functionStartColumn();
if (rawFunctionStartLine > 0 && rawFunctionStartColumn != std::numeric_limits<unsigned>::max()) {
JSC::LineColumn functionStartLineColumn {
static_cast<unsigned>(rawFunctionStartLine),
rawFunctionStartColumn,
};
if (provider) {
#if USE(BUN_JSC_ADDITIONS)
auto& fn = vm.computeLineColumnWithSourcemap();
if (fn) {
// `url` is the out-param — on a successful remap
// it becomes the original-source URL, matching
// the line/column we're emitting.
fn(vm, provider, functionStartLineColumn, url);
}
#endif
}
// Emit 0-indexed, clamping at 0 so we never underflow.
functionDefLine = functionStartLineColumn.line > 0
? static_cast<int>(functionStartLineColumn.line) - 1
: 0;
functionDefColumn = functionStartLineColumn.column > 0
? static_cast<int>(functionStartLineColumn.column) - 1
: 0;
}
if (frame.hasExpressionInfo()) {
// Current sample position (what line inside the function
// was executing). Apply sourcemap if available, but keep
// the URL we already resolved for the function definition
// — a throwaway out-param ensures the sample remap can't
// clobber `url` with the sample's source file (which, for
// inlined helpers, may differ from the function's).
JSC::LineColumn sourceMappedLineColumn = frame.semanticLocation.lineColumn;
if (provider) {
#if USE(BUN_JSC_ADDITIONS)
auto& fn = vm.computeLineColumnWithSourcemap();
if (fn) {
WTF::String scratchURL = url;
fn(vm, provider, sourceMappedLineColumn, scratchURL);
}
#endif
}
// positionTicks lines are 1-indexed in the Chrome format;
// semanticLocation.line is already 1-based.
if (sourceMappedLineColumn.line > 0)
sampleLine = static_cast<int>(sourceMappedLineColumn.line);
}
}
// Create a unique key for this frame based on parent + callFrame.
// line/column here identify the function's DEFINITION, so all samples
// of the same function under the same parent collapse to one node.
WTF::StringBuilder keyBuilder;
keyBuilder.append(currentParentId);
keyBuilder.append(':');
keyBuilder.append(functionName);
keyBuilder.append(':');
keyBuilder.append(url);
keyBuilder.append(':');
keyBuilder.append(scriptId);
keyBuilder.append(':');
keyBuilder.append(functionDefLine);
keyBuilder.append(':');
keyBuilder.append(functionDefColumn);
WTF::String key = keyBuilder.toString();
int nodeId;
auto it = nodeMap.find(key);
if (it == nodeMap.end()) {
// Create new node
nodeId = nextNodeId++;
nodeMap.add(key, nodeId);
ProfileNode node;
node.id = nodeId;
node.functionName = functionName;
node.url = url;
node.scriptId = scriptId;
node.lineNumber = functionDefLine;
node.columnNumber = functionDefColumn;
node.hitCount = 0;
nodes.append(WTF::move(node));
// Add this node as child of parent
if (currentParentId > 0) {
nodes[currentParentId - 1].children.append(nodeId);
}
} else {
// Node already exists with this parent+callFrame combination
nodeId = it->value;
}
currentParentId = nodeId;
// If this is the top frame, increment hit count and record the
// sample line in positionTicks (matching Node/Deno/Chrome DevTools).
if (i == 0) {
nodes[nodeId - 1].hitCount++;
if (sampleLine > 0) {
nodes[nodeId - 1].positionTicks.add(sampleLine, 0).iterator->value++;
}
}
}
// Add sample pointing to the top frame
samples.append(currentParentId);
// Add time delta
// Use monotonic timestamp converted to wall clock time
double currentTime = stackTrace.timestamp.approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
double delta = std::max(0.0, currentTime - lastTime);
timeDeltas.append(static_cast<long long>(delta));
lastTime = currentTime;
}
// endTime is the wall clock time of the last sample
double endTime = lastTime;
// Build JSON using WTF::JSON
using namespace WTF;
auto json = JSON::Object::create();
// Add nodes array
auto nodesArray = JSON::Array::create();
for (const auto& node : nodes) {
auto nodeObj = JSON::Object::create();
nodeObj->setInteger("id"_s, node.id);
auto callFrame = JSON::Object::create();
callFrame->setString("functionName"_s, node.functionName);
callFrame->setString("scriptId"_s, WTF::String::number(node.scriptId));
callFrame->setString("url"_s, node.url);
callFrame->setInteger("lineNumber"_s, node.lineNumber);
callFrame->setInteger("columnNumber"_s, node.columnNumber);
nodeObj->setValue("callFrame"_s, callFrame);
nodeObj->setInteger("hitCount"_s, node.hitCount);
if (!node.children.isEmpty()) {
auto childrenArray = JSON::Array::create();
WTF::HashSet<int> seenChildren;
for (int childId : node.children) {
if (seenChildren.add(childId).isNewEntry) {
childrenArray->pushInteger(childId);
}
}
nodeObj->setValue("children"_s, childrenArray);
}
// Per-line sample counts (Chrome DevTools format). Emit sorted by line
// for deterministic output.
if (!node.positionTicks.isEmpty()) {
WTF::Vector<std::pair<int, int>> sortedTicks;
sortedTicks.reserveInitialCapacity(node.positionTicks.size());
for (auto& entry : node.positionTicks)
sortedTicks.append({ entry.key, entry.value });
std::sort(sortedTicks.begin(), sortedTicks.end(), [](const auto& a, const auto& b) {
return a.first < b.first;
});
auto positionTicksArray = JSON::Array::create();
for (auto& [line, ticks] : sortedTicks) {
auto tickObj = JSON::Object::create();
tickObj->setInteger("line"_s, line);
tickObj->setInteger("ticks"_s, ticks);
positionTicksArray->pushValue(tickObj);
}
nodeObj->setValue("positionTicks"_s, positionTicksArray);
}
nodesArray->pushValue(nodeObj);
}
json->setValue("nodes"_s, nodesArray);
// Add timing info in microseconds
// Note: Using setDouble() instead of setInteger() because setInteger() has precision
// issues with large values (> 2^31). Chrome DevTools expects microseconds since Unix epoch,
// which are typically 16-digit numbers. JSON numbers can represent these precisely.
json->setDouble("startTime"_s, startTime);
json->setDouble("endTime"_s, endTime);
// Add samples array
auto samplesArray = JSON::Array::create();
for (int sample : samples) {
samplesArray->pushInteger(sample);
}
json->setValue("samples"_s, samplesArray);
// Add timeDeltas array
auto timeDeltasArray = JSON::Array::create();
for (long long delta : timeDeltas) {
timeDeltasArray->pushInteger(delta);
}
json->setValue("timeDeltas"_s, timeDeltasArray);
return json->toJSONString();
}
// ============================================================================
// TEXT FORMAT OUTPUT (grep-friendly, designed for LLM analysis)
// ============================================================================
// Structure to hold aggregated function statistics for text output
struct FunctionStats {
WTF::String functionName;
WTF::String location; // file:line format
long long selfTimeUs = 0; // microseconds where this function was at top of stack
long long totalTimeUs = 0; // microseconds including children
int selfSamples = 0; // samples where this function was at top
int totalSamples = 0; // samples where this function appeared anywhere
WTF::HashMap<WTF::String, int> callers; // caller location -> count
WTF::HashMap<WTF::String, int> callees; // callee location -> count
};
// Helper to format a function name properly
// - Empty names become "(anonymous)"
// - Async functions get "async " prefix
static WTF::String formatFunctionName(const WTF::String& name, const JSC::SamplingProfiler::StackFrame& frame)
{
WTF::String displayName = name.isEmpty() ? "(anonymous)"_s : name;
// Check if this is an async function and add prefix if needed
if (frame.frameType == JSC::SamplingProfiler::FrameType::Executable && frame.executable) {
if (auto* functionExecutable = jsDynamicCast<JSC::FunctionExecutable*>(frame.executable)) {
if (JSC::isAsyncFunctionParseMode(functionExecutable->parseMode())) {
if (!displayName.startsWith("async "_s)) {
return makeString("async "_s, displayName);
}
}
}
}
return displayName;
}
// Helper to format a location string from URL and line number
static WTF::String formatLocation(const WTF::String& url, int lineNumber)
{
if (url.isEmpty())
return "[native code]"_s;
// Extract path from file:// URL using WTF::URL
WTF::String path = url;
WTF::URL parsedUrl { url };
if (parsedUrl.isValid() && parsedUrl.protocolIsFile())
path = parsedUrl.fileSystemPath();
if (lineNumber >= 0) {
WTF::StringBuilder sb;
sb.append(path);
sb.append(':');
sb.append(lineNumber);
return sb.toString();
}
return path;
}
// Helper to format time in human-readable form
static WTF::String formatTime(double microseconds)
{
WTF::StringBuilder sb;
if (microseconds >= 1000000.0) {
// Format as seconds with 2 decimal places
double seconds = microseconds / 1000000.0;
sb.append(static_cast<int>(seconds));
sb.append('.');
int frac = static_cast<int>((seconds - static_cast<int>(seconds)) * 100);
if (frac < 10) sb.append('0');
sb.append(frac);
sb.append('s');
return sb.toString();
}
if (microseconds >= 1000.0) {
// Format as milliseconds with 1 decimal place
double ms = microseconds / 1000.0;
sb.append(static_cast<int>(ms));
sb.append('.');
int frac = static_cast<int>((ms - static_cast<int>(ms)) * 10);
sb.append(frac);
sb.append("ms"_s);
return sb.toString();
}
sb.append(static_cast<int>(microseconds));
sb.append("us"_s);
return sb.toString();
}
// Helper to format percentage
static WTF::String formatPercent(double value, double total)
{
if (total <= 0)
return "0.0%"_s;
double pct = (value / total) * 100.0;
// Cap at 100% for display purposes (can exceed 100% due to rounding or overlapping time accounting)
if (pct > 100.0)
pct = 100.0;
WTF::StringBuilder sb;
// Format as XX.X% with 1 decimal place
sb.append(static_cast<int>(pct));
sb.append('.');
int frac = static_cast<int>((pct - static_cast<int>(pct)) * 10);
sb.append(frac);
sb.append('%');
return sb.toString();
}
// Key separator for building composite keys (function name + location)
// Using ASCII control character SOH (0x01) which won't appear in function names or URLs
static constexpr auto kKeySeparator = "\x01"_s;
// Helper to escape pipe characters for markdown table cells (non-code cells)
static WTF::String escapeMarkdownTableCell(const WTF::String& str)
{
bool needsEscape = false;
for (unsigned i = 0; i < str.length(); i++) {
if (str[i] == '|') {
needsEscape = true;
break;
}
}
if (!needsEscape)
return str;
WTF::StringBuilder sb;
for (unsigned i = 0; i < str.length(); i++) {
UChar c = str[i];
if (c == '|')
sb.append("\\|"_s);
else
sb.append(c);
}
return sb.toString();
}
// Helper to format a string as an inline code span that handles backticks properly
// Uses the CommonMark spec: use N+1 backticks as delimiter where N is the longest run of backticks in the string
static WTF::String formatCodeSpan(const WTF::String& str)
{
// Also escape pipes since this will be used in table cells
WTF::String escaped = escapeMarkdownTableCell(str);
// Find the longest run of backticks in the string
int maxBackticks = 0;
int currentRun = 0;
for (unsigned i = 0; i < escaped.length(); i++) {
if (escaped[i] == '`') {
currentRun++;
if (currentRun > maxBackticks)
maxBackticks = currentRun;
} else {
currentRun = 0;
}
}
// If no backticks, use simple single backtick delimiters
if (maxBackticks == 0) {
WTF::StringBuilder sb;
sb.append('`');
sb.append(escaped);
sb.append('`');
return sb.toString();
}
// Use N+1 backticks as delimiter
int delimiterLength = maxBackticks + 1;
WTF::StringBuilder sb;
for (int i = 0; i < delimiterLength; i++)
sb.append('`');
// Add space padding if content starts or ends with backtick (CommonMark requirement)
bool startsWithBacktick = !escaped.isEmpty() && escaped[0] == '`';
bool endsWithBacktick = !escaped.isEmpty() && escaped[escaped.length() - 1] == '`';
if (startsWithBacktick || endsWithBacktick)
sb.append(' ');
sb.append(escaped);
if (startsWithBacktick || endsWithBacktick)
sb.append(' ');
for (int i = 0; i < delimiterLength; i++)
sb.append('`');
return sb.toString();
}
// Helper to generate a minimal valid cpuprofile JSON with no samples
static WTF::String generateEmptyProfileJSON()
{
// Return a minimal valid Chrome DevTools CPU profile format
// Use s_profilingStartTime if available, otherwise fall back to current time
long long timestamp;
if (s_profilingStartTime > 0)
timestamp = static_cast<long long>(s_profilingStartTime);
else
timestamp = static_cast<long long>(WTF::WallTime::now().secondsSinceEpoch().value() * 1000000.0);
WTF::StringBuilder sb;
sb.append("{\"nodes\":[{\"id\":1,\"callFrame\":{\"functionName\":\"(root)\",\"scriptId\":\"0\",\"url\":\"\",\"lineNumber\":-1,\"columnNumber\":-1},\"hitCount\":0,\"children\":[]}],\"startTime\":"_s);
sb.append(timestamp);
sb.append(",\"endTime\":"_s);
sb.append(timestamp);
sb.append(",\"samples\":[],\"timeDeltas\":[]}"_s);
return sb.toString();
}
// Unified function that stops the profiler and generates requested output formats
void stopCPUProfiler(JSC::VM& vm, WTF::String* outJSON, WTF::String* outText)
{
s_isProfilerRunning = false;
JSC::SamplingProfiler* profiler = vm.samplingProfiler();
if (!profiler) {
if (outJSON) *outJSON = WTF::String();
if (outText) *outText = WTF::String();
return;
}
// JSLock is re-entrant, so always acquiring it handles both JS and shutdown contexts
JSC::JSLockHolder locker(vm);
// Defer GC while we're working with stack traces
JSC::DeferGC deferGC(vm);
// Pause the profiler while holding the lock
auto& lock = profiler->getLock();
WTF::Locker profilerLocker { lock };
profiler->pause();
// releaseStackTraces() calls processUnverifiedStackTraces() internally
auto stackTraces = profiler->releaseStackTraces();
profiler->clearData();
// If neither output is requested, we're done
if (!outJSON && !outText)
return;
if (stackTraces.isEmpty()) {
if (outJSON) *outJSON = generateEmptyProfileJSON();
if (outText) *outText = "No samples collected.\n"_s;
return;
}
// Sort traces by timestamp once for both formats
WTF::Vector<size_t> sortedIndices;
sortedIndices.reserveInitialCapacity(stackTraces.size());
for (size_t i = 0; i < stackTraces.size(); i++) {
sortedIndices.append(i);
}
std::sort(sortedIndices.begin(), sortedIndices.end(), [&stackTraces](size_t a, size_t b) {
return stackTraces[a].timestamp < stackTraces[b].timestamp;
});
// Generate JSON format if requested
if (outJSON) {
// Map from stack frame signature to node ID
WTF::HashMap<WTF::String, int> nodeMap;
WTF::Vector<ProfileNode> nodes;
// Create root node
ProfileNode rootNode;
rootNode.id = 1;
rootNode.functionName = "(root)"_s;
rootNode.url = ""_s;
rootNode.scriptId = 0;
rootNode.lineNumber = -1;
rootNode.columnNumber = -1;
rootNode.hitCount = 0;
nodes.append(WTF::move(rootNode));
int nextNodeId = 2;
WTF::Vector<int> samples;
WTF::Vector<long long> timeDeltas;
double startTime = s_profilingStartTime;
double lastTime = s_profilingStartTime;
for (size_t idx : sortedIndices) {
auto& stackTrace = stackTraces[idx];
if (stackTrace.frames.isEmpty()) {
samples.append(1);
double currentTime = stackTrace.timestamp.approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
double delta = std::max(0.0, currentTime - lastTime);
timeDeltas.append(static_cast<long long>(delta));
lastTime = currentTime;
continue;
}
int currentParentId = 1;
for (int i = stackTrace.frames.size() - 1; i >= 0; i--) {
auto& frame = stackTrace.frames[i];
WTF::String functionName = frame.displayName(vm);
WTF::String url;
int scriptId = 0;
// Function-definition line/column (0-indexed) for callFrame.
int functionDefLine = -1;
int functionDefColumn = -1;
// Current-sample line (1-indexed) for positionTicks.
int sampleLine = 0;
if (frame.frameType == JSC::SamplingProfiler::FrameType::Executable && frame.executable) {
auto sourceProviderAndID = frame.sourceProviderAndID();
auto* provider = std::get<0>(sourceProviderAndID);
if (provider) {
url = provider->sourceURL();
scriptId = static_cast<int>(provider->asID());
bool isAbsolutePath = false;
if (!url.isEmpty()) {
if (url[0] == '/')
isAbsolutePath = true;
else if (url.length() >= 2 && url[1] == ':') {
char firstChar = url[0];
if ((firstChar >= 'A' && firstChar <= 'Z') || (firstChar >= 'a' && firstChar <= 'z'))
isAbsolutePath = true;
} else if (url.length() >= 2 && url[0] == '\\' && url[1] == '\\')
isAbsolutePath = true;
}
if (isAbsolutePath)
url = WTF::URL::fileURLWithFileSystemPath(url).string();
}
// Function definition location. JSC returns these 1-based;
// Node/Deno/Chrome DevTools emit them 0-based in the JSON.
// The definition (not the sample position) is remapped
// through the sourcemap callback so callFrame.url and
// callFrame.line/column agree on the function's source.
int rawFunctionStartLine = frame.functionStartLine();
unsigned rawFunctionStartColumn = frame.functionStartColumn();
if (rawFunctionStartLine > 0 && rawFunctionStartColumn != std::numeric_limits<unsigned>::max()) {
JSC::LineColumn functionStartLineColumn {
static_cast<unsigned>(rawFunctionStartLine),
rawFunctionStartColumn,
};
if (provider) {
#if USE(BUN_JSC_ADDITIONS)
auto& fn = vm.computeLineColumnWithSourcemap();
if (fn) {
// `url` is the out-param — on a successful
// remap it becomes the original-source URL.
fn(vm, provider, functionStartLineColumn, url);
}
#endif
}
functionDefLine = functionStartLineColumn.line > 0
? static_cast<int>(functionStartLineColumn.line) - 1
: 0;
functionDefColumn = functionStartLineColumn.column > 0
? static_cast<int>(functionStartLineColumn.column) - 1
: 0;
}
if (frame.hasExpressionInfo()) {
// Sample position for positionTicks — a throwaway
// out-param ensures the sample remap can't clobber
// `url` with a different file than the definition.
JSC::LineColumn sourceMappedLineColumn = frame.semanticLocation.lineColumn;
if (provider) {
#if USE(BUN_JSC_ADDITIONS)
auto& fn = vm.computeLineColumnWithSourcemap();
if (fn) {
WTF::String scratchURL = url;
fn(vm, provider, sourceMappedLineColumn, scratchURL);
}
#endif
}
if (sourceMappedLineColumn.line > 0)
sampleLine = static_cast<int>(sourceMappedLineColumn.line);
}
}
// line/column here identify the function's DEFINITION, so all
// samples of the same function under the same parent collapse.
WTF::StringBuilder keyBuilder;
keyBuilder.append(currentParentId);
keyBuilder.append(':');
keyBuilder.append(functionName);
keyBuilder.append(':');
keyBuilder.append(url);
keyBuilder.append(':');
keyBuilder.append(scriptId);
keyBuilder.append(':');
keyBuilder.append(functionDefLine);
keyBuilder.append(':');
keyBuilder.append(functionDefColumn);
WTF::String key = keyBuilder.toString();
int nodeId;
auto it = nodeMap.find(key);
if (it == nodeMap.end()) {
nodeId = nextNodeId++;
nodeMap.add(key, nodeId);
ProfileNode node;
node.id = nodeId;
node.functionName = functionName;
node.url = url;
node.scriptId = scriptId;
node.lineNumber = functionDefLine;
node.columnNumber = functionDefColumn;
node.hitCount = 0;
nodes.append(WTF::move(node));
if (currentParentId > 0)
nodes[currentParentId - 1].children.append(nodeId);
} else {
nodeId = it->value;
}
currentParentId = nodeId;
if (i == 0) {
nodes[nodeId - 1].hitCount++;
if (sampleLine > 0)
nodes[nodeId - 1].positionTicks.add(sampleLine, 0).iterator->value++;
}
}
samples.append(currentParentId);
double currentTime = stackTrace.timestamp.approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
double delta = std::max(0.0, currentTime - lastTime);
timeDeltas.append(static_cast<long long>(delta));
lastTime = currentTime;
}
double endTime = lastTime;
// Build JSON
using namespace WTF;
auto json = JSON::Object::create();
auto nodesArray = JSON::Array::create();
for (const auto& node : nodes) {
auto nodeObj = JSON::Object::create();
nodeObj->setInteger("id"_s, node.id);
auto callFrame = JSON::Object::create();
callFrame->setString("functionName"_s, node.functionName);
callFrame->setString("scriptId"_s, WTF::String::number(node.scriptId));
callFrame->setString("url"_s, node.url);
callFrame->setInteger("lineNumber"_s, node.lineNumber);
callFrame->setInteger("columnNumber"_s, node.columnNumber);
nodeObj->setValue("callFrame"_s, callFrame);
nodeObj->setInteger("hitCount"_s, node.hitCount);
if (!node.children.isEmpty()) {
auto childrenArray = JSON::Array::create();
WTF::HashSet<int> seenChildren;
for (int childId : node.children) {
if (seenChildren.add(childId).isNewEntry)
childrenArray->pushInteger(childId);
}
nodeObj->setValue("children"_s, childrenArray);
}
// Per-line sample counts (Chrome DevTools format). Emit sorted by
// line for deterministic output.
if (!node.positionTicks.isEmpty()) {
WTF::Vector<std::pair<int, int>> sortedTicks;
sortedTicks.reserveInitialCapacity(node.positionTicks.size());
for (auto& entry : node.positionTicks)
sortedTicks.append({ entry.key, entry.value });
std::sort(sortedTicks.begin(), sortedTicks.end(), [](const auto& a, const auto& b) {
return a.first < b.first;
});
auto positionTicksArray = JSON::Array::create();
for (auto& [line, ticks] : sortedTicks) {
auto tickObj = JSON::Object::create();
tickObj->setInteger("line"_s, line);
tickObj->setInteger("ticks"_s, ticks);
positionTicksArray->pushValue(tickObj);
}
nodeObj->setValue("positionTicks"_s, positionTicksArray);
}
nodesArray->pushValue(nodeObj);
}
json->setValue("nodes"_s, nodesArray);
json->setDouble("startTime"_s, startTime);
json->setDouble("endTime"_s, endTime);
auto samplesArray = JSON::Array::create();
for (int sample : samples)
samplesArray->pushInteger(sample);
json->setValue("samples"_s, samplesArray);
auto timeDeltasArray = JSON::Array::create();
for (long long delta : timeDeltas)
timeDeltasArray->pushInteger(delta);
json->setValue("timeDeltas"_s, timeDeltasArray);
*outJSON = json->toJSONString();
}
// Generate text format if requested
if (outText) {
double startTime = s_profilingStartTime;
double lastTime = s_profilingStartTime;
double endTime = startTime;
WTF::HashMap<WTF::String, FunctionStats> functionStatsMap;
long long totalTimeUs = 0;
int totalSamples = static_cast<int>(stackTraces.size());
for (size_t idx : sortedIndices) {
auto& stackTrace = stackTraces[idx];
double currentTime = stackTrace.timestamp.approximateWallTime().secondsSinceEpoch().value() * 1000000.0;
long long deltaUs = static_cast<long long>(std::max(0.0, currentTime - lastTime));
totalTimeUs += deltaUs;
lastTime = currentTime;
endTime = currentTime;
if (stackTrace.frames.isEmpty())
continue;
WTF::String previousKey;
for (int i = stackTrace.frames.size() - 1; i >= 0; i--) {
auto& frame = stackTrace.frames[i];
WTF::String rawFunctionName = frame.displayName(vm);
WTF::String functionName = formatFunctionName(rawFunctionName, frame);
WTF::String url;
int lineNumber = -1;
if (frame.frameType == JSC::SamplingProfiler::FrameType::Executable && frame.executable) {
auto sourceProviderAndID = frame.sourceProviderAndID();
auto* provider = std::get<0>(sourceProviderAndID);
if (provider) {
url = provider->sourceURL();
bool isAbsolutePath = false;
if (!url.isEmpty()) {
if (url[0] == '/')
isAbsolutePath = true;
else if (url.length() >= 2 && url[1] == ':') {
char firstChar = url[0];
if ((firstChar >= 'A' && firstChar <= 'Z') || (firstChar >= 'a' && firstChar <= 'z'))
isAbsolutePath = true;
} else if (url.length() >= 2 && url[0] == '\\' && url[1] == '\\')
isAbsolutePath = true;
}
if (isAbsolutePath)
url = WTF::URL::fileURLWithFileSystemPath(url).string();
}
if (frame.hasExpressionInfo()) {
JSC::LineColumn sourceMappedLineColumn = frame.semanticLocation.lineColumn;
if (provider) {
#if USE(BUN_JSC_ADDITIONS)
auto& fn = vm.computeLineColumnWithSourcemap();
if (fn)
fn(vm, provider, sourceMappedLineColumn, url);
#endif
}
lineNumber = static_cast<int>(sourceMappedLineColumn.line);
}
}
WTF::String location = formatLocation(url, lineNumber);
// Key uses zero-width space separator internally (not shown in output)
WTF::StringBuilder keyBuilder;
keyBuilder.append(functionName);
keyBuilder.append(kKeySeparator);