1 /**************************************************************************
3 * Copyright 2010 VMware, Inc.
4 * Copyright 2011 Intel corporation
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 **************************************************************************/
29 #include <limits.h> // for CHAR_MAX
39 #include "os_string.hpp"
41 #include "trace_callset.hpp"
42 #include "trace_parser.hpp"
43 #include "trace_writer.hpp"
45 #define STRNCMP_LITERAL(var, literal) strncmp((var), (literal), sizeof (literal) -1)
47 static const char *synopsis = "Create a new trace by trimming an existing trace.";
53 << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
56 " -h, --help Show detailed help for trim options and exit\n"
57 " --calls=CALLSET Include specified calls in the trimmed output.\n"
58 " --deps Include additional calls to satisfy dependencies\n"
59 " --no-deps Do not include calls from dependency analysis\n"
60 " --prune Omit uninteresting calls from the trace output\n"
61 " --no-prune Do not prune uninteresting calls from the trace.\n"
62 " -x, --exact Include exactly the calls specified in --calls\n"
63 " Equivalent to both --no-deps and --no-prune\n"
64 " --thread=THREAD_ID Only retain calls from specified thread\n"
65 " -o, --output=TRACE_FILE Output trace file\n"
73 << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
76 " -h, --help Show this help message and exit\n"
78 " --calls=CALLSET Include specified calls in the trimmed output.\n"
79 " Note that due to dependency analysis and pruning\n"
80 " of uninteresting calls the resulting trace may\n"
81 " include more and less calls than specified.\n"
82 " See --no-deps, --no-prune, and --exact to change\n"
85 " --deps Perform dependency analysis and include dependent\n"
86 " calls as needed, (even if those calls were not\n"
87 " explicitly requested with --calls). This is the\n"
88 " default behavior. See --no-deps and --exact.\n"
90 " --no-deps Do not perform dependency analysis. In this mode\n"
91 " the trimmed trace will never include calls from\n"
92 " outside the range specified in --calls.\n"
94 " --prune Omit calls that have no side effects, even if the\n"
95 " call is within the range specified by --calls.\n"
96 " This is the default behavior. See --no-prune\n"
98 " --no-prune Do not prune uninteresting calls from the trace.\n"
99 " In this mode the trimmed trace will never omit\n"
100 " any calls within the range specified in --calls.\n"
102 " -x, --exact Trim the trace to exactly the calls specified in\n"
103 " --calls. This option is equivalent to passing\n"
104 " both --no-deps and --no-prune.\n"
106 " --thread=THREAD_ID Only retain calls from specified thread\n"
108 " -o, --output=TRACE_FILE Output trace file\n"
114 CALLS_OPT = CHAR_MAX + 1,
123 shortOptions = "ho:x";
125 const static struct option
127 {"help", no_argument, 0, 'h'},
128 {"calls", required_argument, 0, CALLS_OPT},
129 {"deps", no_argument, 0, DEPS_OPT},
130 {"no-deps", no_argument, 0, NO_DEPS_OPT},
131 {"prune", no_argument, 0, PRUNE_OPT},
132 {"no-prune", no_argument, 0, NO_PRUNE_OPT},
133 {"exact", no_argument, 0, 'x'},
134 {"thread", required_argument, 0, THREAD_OPT},
135 {"output", required_argument, 0, 'o'},
139 struct stringCompare {
140 bool operator() (const char *a, const char *b) const {
141 return strcmp(a, b) < 0;
145 class TraceAnalyzer {
146 /* Maps for tracking resource dependencies between calls. */
147 std::map<std::string, std::set<unsigned> > resources;
148 std::map<std::string, std::set<std::string> > dependencies;
150 /* Maps for tracking OpenGL state. */
151 std::map<GLenum, unsigned> texture_map;
153 /* The final set of calls required. This consists of calls added
154 * explicitly with the require() method as well as all calls
155 * implicitly required by those through resource dependencies. */
156 std::set<unsigned> required;
158 bool transformFeedbackActive;
159 bool framebufferObjectActive;
162 /* Rendering often has no side effects, but it can in some cases,
163 * (such as when transform feedback is active, or when rendering
164 * targets a framebuffer object). */
165 bool renderingHasSideEffect() {
166 return transformFeedbackActive || framebufferObjectActive;
169 /* Provide: Record that the given call affects the given resource
170 * as a side effect. */
171 void provide(std::string resource, trace::CallNo call_no) {
172 resources[resource].insert(call_no);
175 /* Link: Establish a dependency between resource 'resource' and
176 * resource 'dependency'. This dependency is captured by name so
177 * that if the list of calls that provide 'dependency' grows
178 * before 'resource' is consumed, those calls will still be
180 void link(std::string resource, std::string dependency) {
181 dependencies[resource].insert(dependency);
184 /* Unlink: Remove dependency from 'resource' on 'dependency'. */
185 void unlink(std::string resource, std::string dependency) {
186 dependencies[resource].erase(dependency);
187 if (dependencies[resource].size() == 0) {
188 dependencies.erase(resource);
192 /* Unlink all: Remove dependencies from 'resource' to all other
194 void unlinkAll(std::string resource) {
195 dependencies.erase(resource);
198 /* Resolve: Recursively compute all calls providing 'resource',
199 * (including linked dependencies of 'resource' on other
201 std::set<unsigned> resolve(std::string resource) {
202 std::set<std::string> *deps;
203 std::set<std::string>::iterator dep;
205 std::set<unsigned> *calls;
206 std::set<unsigned>::iterator call;
208 std::set<unsigned> result, deps_set;
210 /* Recursively chase dependencies. */
211 if (dependencies.count(resource)) {
212 deps = &dependencies[resource];
213 for (dep = deps->begin(); dep != deps->end(); dep++) {
214 deps_set = resolve(*dep);
215 for (call = deps_set.begin(); call != deps_set.end(); call++) {
216 result.insert(*call);
221 /* Also look for calls that directly provide 'resource' */
222 if (resources.count(resource)) {
223 calls = &resources[resource];
224 for (call = calls->begin(); call != calls->end(); call++) {
225 result.insert(*call);
232 /* Consume: Resolve all calls that provide the given resource, and
233 * add them to the required list. Then clear the call list for
234 * 'resource' along with any dependencies. */
235 void consume(std::string resource) {
237 std::set<unsigned> calls;
238 std::set<unsigned>::iterator call;
240 calls = resolve(resource);
242 dependencies.erase(resource);
243 resources.erase(resource);
245 for (call = calls.begin(); call != calls.end(); call++) {
246 required.insert(*call);
250 void stateTrackPreCall(trace::Call *call) {
252 const char *name = call->name();
254 if (strcmp(name, "glBegin") == 0) {
255 insideBeginEnd = true;
259 if (strcmp(name, "glBeginTransformFeedback") == 0) {
260 transformFeedbackActive = true;
264 if (strcmp(name, "glBindTexture") == 0) {
268 target = static_cast<GLenum>(call->arg(0).toSInt());
269 texture = call->arg(1).toUInt();
272 texture_map.erase(target);
274 texture_map[target] = texture;
280 if (strcmp(name, "glBindFramebuffer") == 0) {
284 target = static_cast<GLenum>(call->arg(0).toSInt());
285 framebuffer = call->arg(1).toUInt();
287 if (target == GL_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER) {
288 if (framebuffer == 0) {
289 framebufferObjectActive = false;
291 framebufferObjectActive = true;
298 void stateTrackPostCall(trace::Call *call) {
300 const char *name = call->name();
302 if (strcmp(name, "glEnd") == 0) {
303 insideBeginEnd = false;
307 if (strcmp(name, "glEndTransformFeedback") == 0) {
308 transformFeedbackActive = false;
312 /* If this swapbuffers was included in the trace then it will
313 * have already consumed all framebuffer dependencies. If not,
314 * then clear them now so that they don't carry over into the
316 if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
317 call->flags & trace::CALL_FLAG_END_FRAME) {
318 dependencies.erase("framebuffer");
319 resources.erase("framebuffer");
324 void recordSideEffects(trace::Call *call) {
326 const char *name = call->name();
328 /* If call is flagged as no side effects, then we are done here. */
329 if (call->flags & trace::CALL_FLAG_NO_SIDE_EFFECTS) {
333 /* Similarly, swap-buffers calls don't have interesting side effects. */
334 if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
335 call->flags & trace::CALL_FLAG_END_FRAME) {
339 if (strcmp(name, "glGenTextures") == 0) {
340 const trace::Array *textures = dynamic_cast<const trace::Array *>(&call->arg(1));
345 for (i = 0; i < textures->size(); i++) {
346 std::stringstream ss;
348 texture = textures->values[i]->toUInt();
349 ss << "texture-" << texture;
351 provide(ss.str(), call->no);
357 if (strcmp(name, "glBindTexture") == 0) {
361 std::stringstream ss_target, ss_texture;
363 target = static_cast<GLenum>(call->arg(0).toSInt());
364 texture = call->arg(1).toUInt();
366 ss_target << "texture-target-" << target;
367 ss_texture << "texture-" << texture;
369 resources.erase(ss_target.str());
370 provide(ss_target.str(), call->no);
372 unlinkAll(ss_target.str());
373 link(ss_target.str(), ss_texture.str());
378 /* FIXME: Need to handle glMultTexImage and friends. */
379 if (STRNCMP_LITERAL(name, "glTexImage") == 0 ||
380 STRNCMP_LITERAL(name, "glTexSubImage") == 0 ||
381 STRNCMP_LITERAL(name, "glCopyTexImage") == 0 ||
382 STRNCMP_LITERAL(name, "glCopyTexSubImage") == 0 ||
383 STRNCMP_LITERAL(name, "glCompressedTexImage") == 0 ||
384 STRNCMP_LITERAL(name, "glCompressedTexSubImage") == 0 ||
385 strcmp(name, "glInvalidateTexImage") == 0 ||
386 strcmp(name, "glInvalidateTexSubImage") == 0) {
388 std::set<unsigned> *calls;
389 std::set<unsigned>::iterator c;
390 std::stringstream ss_target, ss_texture;
392 GLenum target = static_cast<GLenum>(call->arg(0).toSInt());
394 ss_target << "texture-target-" << target;
395 ss_texture << "texture-" << texture_map[target];
397 /* The texture resource depends on this call and any calls
398 * providing the given texture target. */
399 provide(ss_texture.str(), call->no);
401 if (resources.count(ss_target.str())) {
402 calls = &resources[ss_target.str()];
403 for (c = calls->begin(); c != calls->end(); c++) {
404 provide(ss_texture.str(), *c);
411 if (strcmp(name, "glEnable") == 0) {
414 cap = static_cast<GLenum>(call->arg(0).toSInt());
416 if (cap == GL_TEXTURE_1D ||
417 cap == GL_TEXTURE_2D ||
418 cap == GL_TEXTURE_3D ||
419 cap == GL_TEXTURE_CUBE_MAP)
421 std::stringstream ss;
423 ss << "texture-target-" << cap;
425 link("render-state", ss.str());
428 provide("state", call->no);
433 if (strcmp(name, "glDisable") == 0) {
436 cap = static_cast<GLenum>(call->arg(0).toSInt());
438 if (cap == GL_TEXTURE_1D ||
439 cap == GL_TEXTURE_2D ||
440 cap == GL_TEXTURE_3D ||
441 cap == GL_TEXTURE_CUBE_MAP)
443 std::stringstream ss;
445 ss << "texture-target-" << cap;
447 unlink("render-state", ss.str());
450 provide("state", call->no);
455 /* Handle all rendering operations, (even though only glEnd is
456 * flagged as a rendering operation we treat everything from
457 * glBegin through glEnd as a rendering operation). */
458 if (call->flags & trace::CALL_FLAG_RENDER ||
461 std::set<unsigned> calls;
462 std::set<unsigned>::iterator c;
464 provide("framebuffer", call->no);
466 calls = resolve("render-state");
468 for (c = calls.begin(); c != calls.end(); c++) {
469 provide("framebuffer", *c);
472 /* In some cases, rendering has side effects beyond the
473 * framebuffer update. */
474 if (renderingHasSideEffect()) {
475 provide("state", call->no);
476 for (c = calls.begin(); c != calls.end(); c++) {
477 provide("state", *c);
484 /* By default, assume this call affects the state somehow. */
485 resources["state"].insert(call->no);
488 void requireDependencies(trace::Call *call) {
490 /* Swap-buffers calls depend on framebuffer state. */
491 if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
492 call->flags & trace::CALL_FLAG_END_FRAME) {
493 consume("framebuffer");
496 /* By default, just assume this call depends on generic state. */
502 TraceAnalyzer(): transformFeedbackActive(false),
503 framebufferObjectActive(false),
504 insideBeginEnd(false)
509 /* Analyze this call by tracking state and recording all the
510 * resources provided by this call as side effects.. */
511 void analyze(trace::Call *call) {
513 stateTrackPreCall(call);
515 recordSideEffects(call);
517 stateTrackPostCall(call);
520 /* Require this call and all of its dependencies to be included in
521 * the final trace. */
522 void require(trace::Call *call) {
524 /* First, find and insert all calls that this call depends on. */
525 requireDependencies(call);
527 /* Then insert this call itself. */
528 required.insert(call->no);
531 /* Return a set of all the required calls, (both those calls added
532 * explicitly with require() and those implicitly depended
534 std::set<unsigned> *get_required(void) {
539 struct trim_options {
540 /* Calls to be included in trace. */
541 trace::CallSet calls;
543 /* Whether dependency analysis should be performed. */
544 bool dependency_analysis;
546 /* Whether uninteresting calls should be pruned.. */
547 bool prune_uninteresting;
549 /* Output filename */
552 /* Emit only calls from this thread (-1 == all threads) */
557 trim_trace(const char *filename, struct trim_options *options)
559 trace::ParseBookmark beginning;
561 TraceAnalyzer analyzer;
562 std::set<unsigned> *required;
564 if (!p.open(filename)) {
565 std::cerr << "error: failed to open " << filename << "\n";
569 /* Mark the beginning so we can return here for pass 2. */
570 p.getBookmark(beginning);
572 /* In pass 1, analyze which calls are needed. */
574 while ((call = p.parse_call())) {
576 /* There's no use doing any work past the last call requested
578 if (call->no > options->calls.getLast()) {
583 /* If requested, ignore all calls not belonging to the specified thread. */
584 if (options->thread != -1 && call->thread_id != options->thread) {
589 /* Also, prune if uninteresting (unless the user asked for no pruning. */
590 if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {
595 /* If this call is included in the user-specified call set,
596 * then require it (and all dependencies) in the trimmed
598 if (options->calls.contains(*call)) {
599 analyzer.require(call);
602 /* Regardless of whether we include this call or not, we do
603 * some dependency tracking (unless disabled by the user). We
604 * do this even for calls we have included in the output so
605 * that any state updates get performed. */
606 if (options->dependency_analysis) {
607 analyzer.analyze(call);
613 /* Prepare output file and writer for output. */
614 if (options->output.empty()) {
615 os::String base(filename);
616 base.trimExtension();
618 options->output = std::string(base.str()) + std::string("-trim.trace");
621 trace::Writer writer;
622 if (!writer.open(options->output.c_str())) {
623 std::cerr << "error: failed to create " << filename << "\n";
627 /* Reset bookmark for pass 2. */
628 p.setBookmark(beginning);
630 /* In pass 2, emit the calls that are required. */
631 required = analyzer.get_required();
633 while ((call = p.parse_call())) {
635 /* There's no use doing any work past the last call requested
637 if (call->no > options->calls.getLast())
640 if (required->find(call->no) != required->end()) {
641 writer.writeCall(call);
646 std::cout << "Trimmed trace is available as " << options->output << "\n";
652 command(int argc, char *argv[])
654 struct trim_options options;
656 options.calls = trace::CallSet(trace::FREQUENCY_ALL);
657 options.dependency_analysis = true;
658 options.prune_uninteresting = true;
663 while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
669 options.calls = trace::CallSet(optarg);
672 options.dependency_analysis = true;
675 options.dependency_analysis = false;
678 options.prune_uninteresting = true;
681 options.prune_uninteresting = false;
684 options.dependency_analysis = false;
685 options.prune_uninteresting = false;
688 options.thread = atoi(optarg);
691 options.output = optarg;
694 std::cerr << "error: unexpected option `" << opt << "`\n";
700 if (optind >= argc) {
701 std::cerr << "error: apitrace trim requires a trace file as an argument.\n";
706 if (argc > optind + 1) {
707 std::cerr << "error: extraneous arguments:";
708 for (int i = optind + 1; i < argc; i++) {
709 std::cerr << " " << argv[i];
716 return trim_trace(argv[optind], &options);
719 const Command trim_command = {