Debian Codegraph @

3rdparty/tracy/import-chrome/src/import-chrome.cpp

raw
1 #ifdef _WIN32
2 # include <windows.h>
3 #endif
4
5 #include <fstream>
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unordered_map>
11
12 #include <sys/stat.h>
13
14 #ifdef _MSC_VER
15 # define stat64 _stat64
16 #endif
17 #if defined __APPLE__
18 # define stat64 stat
19 #endif
20
21 #include "json.hpp"
22
23 #include "../../server/TracyFileWrite.hpp"
24 #include "../../server/TracyMmap.hpp"
25 #include "../../server/TracyWorker.hpp"
26 #include "../../zstd/zstd.h"
27
28 using json = nlohmann::json;
29
30 void Usage()
31 {
32 printf( "Usage: import-chrome input.json output.tracy\n\n" );
33 printf( "The following chrome-tracing phases are supported:\n\n" );
34 printf( " b/B/e/E - Timeline events such as ZoneNamed\n" );
35 printf( " X - Timeline events such as ZoneNamed\n" );
36 printf( " i/I - Message events such as TracyMessage\n" );
37 printf( " * Messages containing the word \"frame\" are interpreted as frame events such as FrameMarkNamed\n" );
38 printf( " C - Plot events such as TracyPlot\n" );
39 printf( " M - Metadata of type \"thread_name\" is used to name threads\n" );
40 exit( 1 );
41 }
42
43 int main( int argc, char** argv )
44 {
45 #ifdef _WIN32
46 if( !AttachConsole( ATTACH_PARENT_PROCESS ) )
47 {
48 AllocConsole();
49 SetConsoleMode( GetStdHandle( STD_OUTPUT_HANDLE ), 0x07 );
50 }
51 #endif
52
53 tracy::FileWrite::Compression clev = tracy::FileWrite::Compression::Fast;
54
55 if( argc != 3 ) Usage();
56
57 const char* input = argv[1];
58 const char* output = argv[2];
59
60 printf( "Loading...\r" );
61 fflush( stdout );
62
63 json j;
64
65 const auto fnsz = strlen( input );
66 if( fnsz > 4 && memcmp( input+fnsz-4, ".zst", 4 ) == 0 )
67 {
68 FILE* f = fopen( input, "rb" );
69 if( !f )
70 {
71 fprintf( stderr, "Cannot open input file!\n" );
72 exit( 1 );
73 }
74 struct stat64 sb;
75 if( stat64( input, &sb ) != 0 )
76 {
77 fprintf( stderr, "Cannot open input file!\n" );
78 fclose( f );
79 exit( 1 );
80 }
81
82 const auto zsz = sb.st_size;
83 auto zbuf = (char*)mmap( nullptr, zsz, PROT_READ, MAP_SHARED, fileno( f ), 0 );
84 fclose( f );
85 if( !zbuf )
86 {
87 fprintf( stderr, "Cannot mmap input file!\n" );
88 exit( 1 );
89 }
90
91 auto zctx = ZSTD_createDStream();
92 ZSTD_initDStream( zctx );
93
94 enum { tmpSize = 64*1024 };
95 auto tmp = new char[tmpSize];
96
97 ZSTD_inBuffer_s zin = { zbuf, (size_t)zsz };
98 ZSTD_outBuffer_s zout = { tmp, (size_t)tmpSize };
99
100 std::vector<uint8_t> buf;
101 buf.reserve( 1024*1024 );
102
103 while( zin.pos < zin.size )
104 {
105 const auto res = ZSTD_decompressStream( zctx, &zout, &zin );
106 if( ZSTD_isError( res ) )
107 {
108 ZSTD_freeDStream( zctx );
109 delete[] tmp;
110 fprintf( stderr, "Couldn't decompress input file (%s)!\n", ZSTD_getErrorName( res ) );
111 exit( 1 );
112 }
113 if( zout.pos > 0 )
114 {
115 const auto bsz = buf.size();
116 buf.resize( bsz + zout.pos );
117 memcpy( buf.data() + bsz, tmp, zout.pos );
118 zout.pos = 0;
119 }
120 }
121
122 ZSTD_freeDStream( zctx );
123 delete[] tmp;
124 munmap( zbuf, zsz );
125
126 j = json::parse( buf.begin(), buf.end() );
127 }
128 else
129 {
130 std::ifstream is( input );
131 if( !is.is_open() )
132 {
133 fprintf( stderr, "Cannot open input file!\n" );
134 exit( 1 );
135 }
136 is >> j;
137 is.close();
138 }
139
140 printf( "\33[2KParsing...\r" );
141 fflush( stdout );
142
143 // encode a pair of "real pid, real tid" from a trace into a
144 // pseudo thread ID living in the single namespace of Tracy threads.
145 struct PidTidEncoder
146 {
147 uint64_t tid;
148 uint64_t pid;
149 uint64_t pseudo_tid; // fake thread id, unique within Tracy
150 };
151
152 std::vector<PidTidEncoder> tid_encoders;
153 std::vector<tracy::Worker::ImportEventTimeline> timeline;
154 std::vector<tracy::Worker::ImportEventMessages> messages;
155 std::vector<tracy::Worker::ImportEventPlots> plots;
156 std::unordered_map<uint64_t, std::string> threadNames;
157
158 const auto getPseudoTid = [&](json& val) -> uint64_t {
159 const auto real_tid = val["tid"].get<uint64_t>();
160
161 if( val.contains( "pid" ) )
162 {
163 // there might be multiple processes so we allocate a pseudo-tid
164 // for each pair (pid, real_tid)
165 const auto pid = val["pid"].get<uint64_t>();
166
167 for ( auto &pair : tid_encoders)
168 {
169 if( pair.pid == pid && pair.tid == real_tid ) return pair.pseudo_tid;
170 }
171
172 assert( pid <= std::numeric_limits<uint32_t>::max() );
173 assert( real_tid <= std::numeric_limits<uint32_t>::max() );
174
175 const auto pseudo_tid = ( real_tid & 0xFFFFFFFF ) | ( pid << 32 );
176 tid_encoders.emplace_back(PidTidEncoder {real_tid, pid, pseudo_tid});
177 return pseudo_tid;
178 }
179 else
180 {
181 return real_tid;
182 }
183 };
184
185 if( j.is_object() && j.contains( "traceEvents" ) )
186 {
187 j = j["traceEvents"];
188 }
189
190 if( !j.is_array() )
191 {
192 fprintf( stderr, "Input must be either an array of events or an object containing an array of events under \"traceEvents\" key.\n" );
193 exit( 1 );
194 }
195
196 for( auto& v : j )
197 {
198 const auto type = v["ph"].get<std::string>();
199
200 std::string zoneText = "";
201 if( v.contains( "args" ) )
202 {
203 for( auto& kv : v["args"].items() )
204 {
205 const auto val = kv.value();
206 const std::string s = val.is_string() ? val.get<std::string>() : val.dump();
207 zoneText += kv.key() + ": " + s + "\n";
208 }
209 }
210
211 std::string locFile;
212 uint32_t locLine = 0;
213 if( v.contains( "loc" ) )
214 {
215 auto loc = v["loc"].get<std::string>();
216 const auto lpos = loc.find_last_of( ':' );
217 if( lpos == std::string::npos )
218 {
219 std::swap( loc, locFile );
220 }
221 else
222 {
223 locFile = loc.substr( 0, lpos );
224 locLine = atoi( loc.c_str() + lpos + 1 );
225 }
226 }
227
228 if( type == "b" || type == "B" )
229 {
230 timeline.emplace_back( tracy::Worker::ImportEventTimeline {
231 getPseudoTid(v),
232 uint64_t( v["ts"].get<double>() * 1000. ),
233 v["name"].get<std::string>(),
234 std::move(zoneText),
235 false,
236 std::move(locFile),
237 locLine
238 } );
239 }
240 else if( type == "e" || type == "E" )
241 {
242 timeline.emplace_back( tracy::Worker::ImportEventTimeline {
243 getPseudoTid(v),
244 uint64_t( v["ts"].get<double>() * 1000. ),
245 "",
246 std::move(zoneText),
247 true
248 } );
249 }
250 else if( type == "X" )
251 {
252 const auto tid = getPseudoTid(v);
253 const auto ts0 = uint64_t( v["ts"].get<double>() * 1000. );
254 const auto ts1 = ts0 + uint64_t( v["dur"].get<double>() * 1000. );
255 const auto name = v["name"].get<std::string>();
256 timeline.emplace_back( tracy::Worker::ImportEventTimeline { tid, ts0, name, std::move(zoneText), false, std::move(locFile), locLine } );
257 timeline.emplace_back( tracy::Worker::ImportEventTimeline { tid, ts1, "", "", true } );
258 }
259 else if( type == "i" || type == "I" )
260 {
261 messages.emplace_back( tracy::Worker::ImportEventMessages {
262 getPseudoTid(v),
263 uint64_t( v["ts"].get<double>() * 1000. ),
264 v["name"].get<std::string>()
265 } );
266 }
267 else if( type == "C" )
268 {
269 auto timestamp = int64_t( v["ts"].get<double>() * 1000 );
270 for( auto& kv : v["args"].items() )
271 {
272 bool plotFound = false;
273 auto& metricName = kv.key();
274 auto dataPoint = std::make_pair( timestamp, kv.value().get<double>() );
275
276 // The input file is assumed to have only very few metrics,
277 // so iterating through plots is not a problem.
278 for( auto& plot : plots )
279 {
280 if( plot.name == metricName )
281 {
282 plot.data.emplace_back( dataPoint );
283 plotFound = true;
284 break;
285 }
286 }
287 if( !plotFound )
288 {
289 auto formatting = tracy::PlotValueFormatting::Number;
290
291 // NOTE: With C++20 one could say metricName.ends_with( "_bytes" ) instead of rfind
292 auto metricNameLen = metricName.size();
293 if ( metricNameLen >= 6 && metricName.rfind( "_bytes" ) == metricNameLen - 6 ) {
294 formatting = tracy::PlotValueFormatting::Memory;
295 }
296
297 plots.emplace_back( tracy::Worker::ImportEventPlots {
298 std::move( metricName ),
299 formatting,
300 { dataPoint }
301 } );
302 }
303 }
304 }
305 else if (type == "M")
306 {
307 if (v.contains("name") && v["name"] == "thread_name" && v.contains("args") && v["args"].is_object() && v["args"].contains("name"))
308 {
309 const auto tid = getPseudoTid(v);
310 threadNames[tid] = v["args"]["name"].get<std::string>();
311 }
312 }
313 }
314
315 std::stable_sort( timeline.begin(), timeline.end(), [] ( const auto& l, const auto& r ) { return l.timestamp < r.timestamp; } );
316 std::stable_sort( messages.begin(), messages.end(), [] ( const auto& l, const auto& r ) { return l.timestamp < r.timestamp; } );
317 for( auto& v : plots ) std::stable_sort( v.data.begin(), v.data.end(), [] ( const auto& l, const auto& r ) { return l.first < r.first; } );
318
319 uint64_t mts = 0;
320 if( !timeline.empty() )
321 {
322 mts = timeline[0].timestamp;
323 }
324 if( !messages.empty() )
325 {
326 if( mts > messages[0].timestamp ) mts = messages[0].timestamp;
327 }
328 for( auto& plot : plots )
329 {
330 if( mts > plot.data[0].first ) mts = plot.data[0].first;
331 }
332 for( auto& v : timeline ) v.timestamp -= mts;
333 for( auto& v : messages ) v.timestamp -= mts;
334 for( auto& plot : plots )
335 {
336 for( auto& v : plot.data ) v.first -= mts;
337 }
338
339 printf( "\33[2KProcessing...\r" );
340 fflush( stdout );
341
342 auto&& getFilename = [](const char* in) {
343 auto out = in;
344 while (*out) ++out;
345 --out;
346 while (out > in && (*out != '/' || *out != '\\')) out--;
347 return out;
348 };
349
350 tracy::Worker worker( getFilename(output), getFilename(input), timeline, messages, plots, threadNames );
351
352 auto w = std::unique_ptr<tracy::FileWrite>( tracy::FileWrite::Open( output, clev ) );
353 if( !w )
354 {
355 fprintf( stderr, "Cannot open output file!\n" );
356 exit( 1 );
357 }
358 printf( "\33[2KSaving...\r" );
359 fflush( stdout );
360 worker.Write( *w, false );
361
362 printf( "\33[2KCleanup...\n" );
363 fflush( stdout );
364
365 return 0;
366 }