]> git.cworth.org Git - apitrace/blob - cli/cli_trim.cpp
trim: Abstract common stringstream idioms into shared functions.
[apitrace] / cli / cli_trim.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010 VMware, Inc.
4  * Copyright 2011 Intel corporation
5  * All Rights Reserved.
6  *
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:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
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
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27 #include <sstream>
28 #include <string.h>
29 #include <limits.h> // for CHAR_MAX
30 #include <getopt.h>
31
32 #include <GL/gl.h>
33 #include <GL/glext.h>
34
35 #include <set>
36
37 #include "cli.hpp"
38
39 #include "os_string.hpp"
40
41 #include "trace_callset.hpp"
42 #include "trace_parser.hpp"
43 #include "trace_writer.hpp"
44
45 #define STRNCMP_LITERAL(var, literal) strncmp((var), (literal), sizeof (literal) -1)
46
47 static const char *synopsis = "Create a new trace by trimming an existing trace.";
48
49 static void
50 usage(void)
51 {
52     std::cout
53         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
54         << synopsis << "\n"
55         "\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"
66     ;
67 }
68
69 static void
70 help()
71 {
72     std::cout
73         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
74         << synopsis << "\n"
75         "\n"
76         "    -h, --help               Show this help message and exit\n"
77         "\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"
83         "                             this behavior.\n"
84         "\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"
89         "\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"
93         "\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"
97         "\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"
101         "\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"
105         "\n"
106         "        --thread=THREAD_ID   Only retain calls from specified thread\n"
107         "\n"
108         "    -o, --output=TRACE_FILE  Output trace file\n"
109         "\n"
110     ;
111 }
112
113 enum {
114     CALLS_OPT = CHAR_MAX + 1,
115     DEPS_OPT,
116     NO_DEPS_OPT,
117     PRUNE_OPT,
118     NO_PRUNE_OPT,
119     THREAD_OPT,
120 };
121
122 const static char *
123 shortOptions = "ho:x";
124
125 const static struct option
126 longOptions[] = {
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'},
136     {0, 0, 0, 0}
137 };
138
139 struct stringCompare {
140     bool operator() (const char *a, const char *b) const {
141         return strcmp(a, b) < 0;
142     }
143 };
144
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;
149
150     /* Maps for tracking OpenGL state. */
151     std::map<GLenum, unsigned> texture_map;
152
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;
157
158     bool transformFeedbackActive;
159     bool framebufferObjectActive;
160     bool insideBeginEnd;
161     GLuint activeProgram;
162
163     /* Rendering often has no side effects, but it can in some cases,
164      * (such as when transform feedback is active, or when rendering
165      * targets a framebuffer object). */
166     bool renderingHasSideEffect() {
167         return transformFeedbackActive || framebufferObjectActive;
168     }
169
170     /* Provide: Record that the given call affects the given resource
171      * as a side effect. */
172     void provide(std::string resource, trace::CallNo call_no) {
173         resources[resource].insert(call_no);
174     }
175
176     /* Like provide, but with a simply-formatted string, (appending an
177      * integer to the given string). */
178     void providef(std::string resource, int resource_no, trace::CallNo call_no) {
179         std::stringstream ss;
180         ss << resource << resource_no;
181         provide(ss.str(), call_no);
182     }
183
184     /* Link: Establish a dependency between resource 'resource' and
185      * resource 'dependency'. This dependency is captured by name so
186      * that if the list of calls that provide 'dependency' grows
187      * before 'resource' is consumed, those calls will still be
188      * captured. */
189     void link(std::string resource, std::string dependency) {
190         dependencies[resource].insert(dependency);
191     }
192
193     /* Like link, but with a simply-formatted string, (appending an
194      * integer to the given string). */
195     void linkf(std::string resource, std::string dependency, int dep_no) {
196
197         std::stringstream ss;
198         ss << dependency << dep_no;
199         link(resource, ss.str());
200     }
201
202     /* Unlink: Remove dependency from 'resource' on 'dependency'. */
203     void unlink(std::string resource, std::string dependency) {
204         dependencies[resource].erase(dependency);
205         if (dependencies[resource].size() == 0) {
206             dependencies.erase(resource);
207         }
208     }
209
210     /* Like unlink, but with a simply-formated string, (appending an
211      * integer to the given string). */
212     void unlinkf(std::string resource, std::string dependency, int dep_no) {
213
214         std::stringstream ss;
215         ss << dependency << dep_no;
216         unlink(resource, ss.str());
217     }
218
219     /* Unlink all: Remove dependencies from 'resource' to all other
220      * resources. */
221     void unlinkAll(std::string resource) {
222         dependencies.erase(resource);
223     }
224
225     /* Resolve: Recursively compute all calls providing 'resource',
226      * (including linked dependencies of 'resource' on other
227      * resources). */
228     std::set<unsigned> resolve(std::string resource) {
229         std::set<std::string> *deps;
230         std::set<std::string>::iterator dep;
231
232         std::set<unsigned> *calls;
233         std::set<unsigned>::iterator call;
234
235         std::set<unsigned> result, deps_set;
236
237         /* Recursively chase dependencies. */
238         if (dependencies.count(resource)) {
239             deps = &dependencies[resource];
240             for (dep = deps->begin(); dep != deps->end(); dep++) {
241                 deps_set = resolve(*dep);
242                 for (call = deps_set.begin(); call != deps_set.end(); call++) {
243                     result.insert(*call);
244                 }
245             }
246         }
247
248         /* Also look for calls that directly provide 'resource' */
249         if (resources.count(resource)) {
250             calls = &resources[resource];
251             for (call = calls->begin(); call != calls->end(); call++) {
252                 result.insert(*call);
253             }
254         }
255
256         return result;
257     }
258
259     /* Consume: Resolve all calls that provide the given resource, and
260      * add them to the required list. Then clear the call list for
261      * 'resource' along with any dependencies. */
262     void consume(std::string resource) {
263
264         std::set<unsigned> calls;
265         std::set<unsigned>::iterator call;
266
267         calls = resolve(resource);
268
269         dependencies.erase(resource);
270         resources.erase(resource);
271
272         for (call = calls.begin(); call != calls.end(); call++) {
273             required.insert(*call);
274         }
275     }
276
277     void stateTrackPreCall(trace::Call *call) {
278
279         const char *name = call->name();
280
281         if (strcmp(name, "glBegin") == 0) {
282             insideBeginEnd = true;
283             return;
284         }
285
286         if (strcmp(name, "glBeginTransformFeedback") == 0) {
287             transformFeedbackActive = true;
288             return;
289         }
290
291         if (strcmp(name, "glBindTexture") == 0) {
292             GLenum target;
293             GLuint texture;
294
295             target = static_cast<GLenum>(call->arg(0).toSInt());
296             texture = call->arg(1).toUInt();
297
298             if (texture == 0) {
299                 texture_map.erase(target);
300             } else {
301                 texture_map[target] = texture;
302             }
303
304             return;
305         }
306
307         if (strcmp(name, "glUseProgram") == 0) {
308             activeProgram = call->arg(0).toUInt();
309         }
310
311         if (strcmp(name, "glBindFramebuffer") == 0) {
312             GLenum target;
313             GLuint framebuffer;
314
315             target = static_cast<GLenum>(call->arg(0).toSInt());
316             framebuffer = call->arg(1).toUInt();
317
318             if (target == GL_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER) {
319                 if (framebuffer == 0) {
320                     framebufferObjectActive = false;
321                 } else {
322                     framebufferObjectActive = true;
323                 }
324             }
325             return;
326         }
327     }
328
329     void stateTrackPostCall(trace::Call *call) {
330
331         const char *name = call->name();
332
333         if (strcmp(name, "glEnd") == 0) {
334             insideBeginEnd = false;
335             return;
336         }
337
338         if (strcmp(name, "glEndTransformFeedback") == 0) {
339             transformFeedbackActive = false;
340             return;
341         }
342
343         /* If this swapbuffers was included in the trace then it will
344          * have already consumed all framebuffer dependencies. If not,
345          * then clear them now so that they don't carry over into the
346          * next frame. */
347         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
348             call->flags & trace::CALL_FLAG_END_FRAME) {
349             dependencies.erase("framebuffer");
350             resources.erase("framebuffer");
351             return;
352         }
353     }
354
355     void recordSideEffects(trace::Call *call) {
356
357         const char *name = call->name();
358
359         /* If call is flagged as no side effects, then we are done here. */
360         if (call->flags & trace::CALL_FLAG_NO_SIDE_EFFECTS) {
361             return;
362         }
363
364         /* Similarly, swap-buffers calls don't have interesting side effects. */
365         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
366             call->flags & trace::CALL_FLAG_END_FRAME) {
367             return;
368         }
369
370         if (strcmp(name, "glGenTextures") == 0) {
371             const trace::Array *textures = dynamic_cast<const trace::Array *>(&call->arg(1));
372             size_t i;
373             GLuint texture;
374
375             if (textures) {
376                 for (i = 0; i < textures->size(); i++) {
377                     texture = textures->values[i]->toUInt();
378                     providef("texture-", texture, call->no);
379                 }
380             }
381             return;
382         }
383
384         if (strcmp(name, "glBindTexture") == 0) {
385             GLenum target;
386             GLuint texture;
387
388             std::stringstream ss_target, ss_texture;
389
390             target = static_cast<GLenum>(call->arg(0).toSInt());
391             texture = call->arg(1).toUInt();
392
393             ss_target << "texture-target-" << target;
394             ss_texture << "texture-" << texture;
395
396             resources.erase(ss_target.str());
397             provide(ss_target.str(), call->no);
398
399             unlinkAll(ss_target.str());
400             link(ss_target.str(), ss_texture.str());
401
402             return;
403         }
404
405         /* FIXME: Need to handle glMultTexImage and friends. */
406         if (STRNCMP_LITERAL(name, "glTexImage") == 0 ||
407             STRNCMP_LITERAL(name, "glTexSubImage") == 0 ||
408             STRNCMP_LITERAL(name, "glCopyTexImage") == 0 ||
409             STRNCMP_LITERAL(name, "glCopyTexSubImage") == 0 ||
410             STRNCMP_LITERAL(name, "glCompressedTexImage") == 0 ||
411             STRNCMP_LITERAL(name, "glCompressedTexSubImage") == 0 ||
412             strcmp(name, "glInvalidateTexImage") == 0 ||
413             strcmp(name, "glInvalidateTexSubImage") == 0) {
414
415             std::set<unsigned> *calls;
416             std::set<unsigned>::iterator c;
417             std::stringstream ss_target, ss_texture;
418
419             GLenum target = static_cast<GLenum>(call->arg(0).toSInt());
420
421             ss_target << "texture-target-" << target;
422             ss_texture << "texture-" << texture_map[target];
423
424             /* The texture resource depends on this call and any calls
425              * providing the given texture target. */
426             provide(ss_texture.str(), call->no);
427
428             if (resources.count(ss_target.str())) {
429                 calls = &resources[ss_target.str()];
430                 for (c = calls->begin(); c != calls->end(); c++) {
431                     provide(ss_texture.str(), *c);
432                 }
433             }
434
435             return;
436         }
437
438         if (strcmp(name, "glEnable") == 0) {
439             GLenum cap;
440
441             cap = static_cast<GLenum>(call->arg(0).toSInt());
442
443             if (cap == GL_TEXTURE_1D ||
444                 cap == GL_TEXTURE_2D ||
445                 cap == GL_TEXTURE_3D ||
446                 cap == GL_TEXTURE_CUBE_MAP)
447             {
448                 linkf("render-state", "texture-target-", cap);
449             }
450
451             provide("state", call->no);
452             return;
453         }
454
455         if (strcmp(name, "glDisable") == 0) {
456             GLenum cap;
457
458             cap = static_cast<GLenum>(call->arg(0).toSInt());
459
460             if (cap == GL_TEXTURE_1D ||
461                 cap == GL_TEXTURE_2D ||
462                 cap == GL_TEXTURE_3D ||
463                 cap == GL_TEXTURE_CUBE_MAP)
464             {
465                 unlinkf("render-state", "texture-target-", cap);
466             }
467
468             provide("state", call->no);
469             return;
470         }
471
472         if (strcmp(name, "glCreateShader") == 0 ||
473             strcmp(name, "glCreateShaderObjectARB") == 0) {
474
475             GLuint shader = call->ret->toUInt();
476             providef("shader-", shader, call->no);
477             return;
478         }
479
480         if (strcmp(name, "glShaderSource") == 0 ||
481             strcmp(name, "glShaderSourceARB") == 0 ||
482             strcmp(name, "glCompileShader") == 0 ||
483             strcmp(name, "glCompileShaderARB") == 0 ||
484             strcmp(name, "glGetShaderiv") == 0 ||
485             strcmp(name, "glGetShaderInfoLog") == 0) {
486
487             GLuint shader = call->arg(0).toUInt();
488             providef("shader-", shader, call->no);
489             return;
490         }
491
492         if (strcmp(name, "glCreateProgram") == 0 ||
493             strcmp(name, "glCreateProgramObjectARB") == 0) {
494
495             GLuint program = call->ret->toUInt();
496             providef("program-", program, call->no);
497             return;
498         }
499
500         if (strcmp(name, "glAttachShader") == 0 ||
501             strcmp(name, "glAttachObjectARB") == 0) {
502
503             GLuint program, shader;
504             std::stringstream ss_program, ss_shader;
505
506             program = call->arg(0).toUInt();
507             shader = call->arg(1).toUInt();
508
509             ss_program << "program-" << program;
510             ss_shader << "shader-" << shader;
511
512             link(ss_program.str(), ss_shader.str());
513             provide(ss_program.str(), call->no);
514
515             return;
516         }
517
518         if (strcmp(name, "glDetachShader") == 0 ||
519             strcmp(name, "glDetachObjectARB") == 0) {
520
521             GLuint program, shader;
522             std::stringstream ss_program, ss_shader;
523
524             program = call->arg(0).toUInt();
525             shader = call->arg(1).toUInt();
526
527             ss_program << "program-" << program;
528             ss_shader << "shader-" << shader;
529
530             unlink(ss_program.str(), ss_shader.str());
531
532             return;
533         }
534
535         if (strcmp(name, "glUseProgram") == 0 ||
536             strcmp(name, "glUseProgramObjectARB") == 0) {
537
538             GLuint program;
539
540             program = call->arg(0).toUInt();
541
542             unlinkAll("render-program-state");
543
544             if (program == 0) {
545                 unlink("render-state", "render-program-state");
546                 provide("state", call->no);
547             } else {
548                 std::stringstream ss;
549
550                 ss << "program-" << program;
551
552                 link("render-state", "render-program-state");
553                 link("render-program-state", ss.str());
554
555                 provide(ss.str(), call->no);
556             }
557
558             return;
559         }
560
561         if (strcmp(name, "glGetUniformLocation") == 0 ||
562             strcmp(name, "glGetUniformLocationARB") == 0 ||
563             strcmp(name, "glGetFragDataLocation") == 0 ||
564             strcmp(name, "glGetFragDataLocationEXT") == 0 ||
565             strcmp(name, "glGetSubroutineUniformLocation") == 0 ||
566             strcmp(name, "glGetProgramResourceLocation") == 0 ||
567             strcmp(name, "glGetProgramResourceLocationIndex") == 0 ||
568             strcmp(name, "glGetVaryingLocationNV") == 0) {
569
570             GLuint program = call->arg(0).toUInt();
571
572             providef("program-", program, call->no);
573
574             return;
575         }
576
577         /* For any call that accepts 'location' as its first argument,
578          * perform a lookup in our location->program map and add a
579          * dependence on the program we find there. */
580         if (call->sig->num_args > 0 &&
581             strcmp(call->sig->arg_names[0], "location") == 0) {
582
583             providef("program-", activeProgram, call->no);
584             return;
585         }
586
587         /* FIXME: We cut a huge swath by assuming that any unhandled
588          * call that has a first argument named "program" should not
589          * be included in the trimmed output unless the program of
590          * that number is also included.
591          *
592          * This heuristic is correct for many cases, but we should
593          * actually carefully verify if this includes some calls
594          * inappropriately, or if it misses some.
595          */
596         if (strcmp(name, "glLinkProgram") == 0 ||
597             strcmp(name, "glLinkProgramARB") == 0 ||
598             (call->sig->num_args > 0 &&
599              (strcmp(call->sig->arg_names[0], "program") == 0 ||
600               strcmp(call->sig->arg_names[0], "programObj") == 0))) {
601
602             GLuint program = call->arg(0).toUInt();
603             providef("program-", program, call->no);
604             return;
605         }
606
607         /* Handle all rendering operations, (even though only glEnd is
608          * flagged as a rendering operation we treat everything from
609          * glBegin through glEnd as a rendering operation). */
610         if (call->flags & trace::CALL_FLAG_RENDER ||
611             insideBeginEnd) {
612
613             std::set<unsigned> calls;
614             std::set<unsigned>::iterator c;
615
616             provide("framebuffer", call->no);
617
618             calls = resolve("render-state");
619
620             for (c = calls.begin(); c != calls.end(); c++) {
621                 provide("framebuffer", *c);
622             }
623
624             /* In some cases, rendering has side effects beyond the
625              * framebuffer update. */
626             if (renderingHasSideEffect()) {
627                 provide("state", call->no);
628                 for (c = calls.begin(); c != calls.end(); c++) {
629                     provide("state", *c);
630                 }
631             }
632
633             return;
634         }
635
636         /* By default, assume this call affects the state somehow. */
637         resources["state"].insert(call->no);
638     }
639
640     void requireDependencies(trace::Call *call) {
641
642         /* Swap-buffers calls depend on framebuffer state. */
643         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
644             call->flags & trace::CALL_FLAG_END_FRAME) {
645             consume("framebuffer");
646         }
647
648         /* By default, just assume this call depends on generic state. */
649         consume("state");
650     }
651
652
653 public:
654     TraceAnalyzer(): transformFeedbackActive(false),
655                      framebufferObjectActive(false),
656                      insideBeginEnd(false)
657     {}
658
659     ~TraceAnalyzer() {}
660
661     /* Analyze this call by tracking state and recording all the
662      * resources provided by this call as side effects.. */
663     void analyze(trace::Call *call) {
664
665         stateTrackPreCall(call);
666
667         recordSideEffects(call);
668
669         stateTrackPostCall(call);
670     }
671
672     /* Require this call and all of its dependencies to be included in
673      * the final trace. */
674     void require(trace::Call *call) {
675
676         /* First, find and insert all calls that this call depends on. */
677         requireDependencies(call);
678
679         /* Then insert this call itself. */
680         required.insert(call->no);
681     }
682
683     /* Return a set of all the required calls, (both those calls added
684      * explicitly with require() and those implicitly depended
685      * upon. */
686     std::set<unsigned> *get_required(void) {
687         return &required;
688     }
689 };
690
691 struct trim_options {
692     /* Calls to be included in trace. */
693     trace::CallSet calls;
694
695     /* Whether dependency analysis should be performed. */
696     bool dependency_analysis;
697
698     /* Whether uninteresting calls should be pruned.. */
699     bool prune_uninteresting;
700
701     /* Output filename */
702     std::string output;
703
704     /* Emit only calls from this thread (-1 == all threads) */
705     int thread;
706 };
707
708 static int
709 trim_trace(const char *filename, struct trim_options *options)
710 {
711     trace::ParseBookmark beginning;
712     trace::Parser p;
713     TraceAnalyzer analyzer;
714     std::set<unsigned> *required;
715
716     if (!p.open(filename)) {
717         std::cerr << "error: failed to open " << filename << "\n";
718         return 1;
719     }
720
721     /* Mark the beginning so we can return here for pass 2. */
722     p.getBookmark(beginning);
723
724     /* In pass 1, analyze which calls are needed. */
725     trace::Call *call;
726     while ((call = p.parse_call())) {
727
728         /* There's no use doing any work past the last call requested
729          * by the user. */
730         if (call->no > options->calls.getLast()) {
731             delete call;
732             break;
733         }
734
735         /* If requested, ignore all calls not belonging to the specified thread. */
736         if (options->thread != -1 && call->thread_id != options->thread) {
737             delete call;
738             continue;
739         }
740
741         /* Also, prune if uninteresting (unless the user asked for no pruning. */
742         if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {
743             delete call;
744             continue;
745         }
746
747         /* If this call is included in the user-specified call set,
748          * then require it (and all dependencies) in the trimmed
749          * output. */
750         if (options->calls.contains(*call)) {
751             analyzer.require(call);
752         }
753
754         /* Regardless of whether we include this call or not, we do
755          * some dependency tracking (unless disabled by the user). We
756          * do this even for calls we have included in the output so
757          * that any state updates get performed. */
758         if (options->dependency_analysis) {
759             analyzer.analyze(call);
760         }
761
762         delete call;
763     }
764
765     /* Prepare output file and writer for output. */
766     if (options->output.empty()) {
767         os::String base(filename);
768         base.trimExtension();
769
770         options->output = std::string(base.str()) + std::string("-trim.trace");
771     }
772
773     trace::Writer writer;
774     if (!writer.open(options->output.c_str())) {
775         std::cerr << "error: failed to create " << filename << "\n";
776         return 1;
777     }
778
779     /* Reset bookmark for pass 2. */
780     p.setBookmark(beginning);
781
782     /* In pass 2, emit the calls that are required. */
783     required = analyzer.get_required();
784
785     while ((call = p.parse_call())) {
786
787         /* There's no use doing any work past the last call requested
788          * by the user. */
789         if (call->no > options->calls.getLast())
790             break;
791
792         if (required->find(call->no) != required->end()) {
793             writer.writeCall(call);
794         }
795         delete call;
796     }
797
798     std::cout << "Trimmed trace is available as " << options->output << "\n";
799
800     return 0;
801 }
802
803 static int
804 command(int argc, char *argv[])
805 {
806     struct trim_options options;
807
808     options.calls = trace::CallSet(trace::FREQUENCY_ALL);
809     options.dependency_analysis = true;
810     options.prune_uninteresting = true;
811     options.output = "";
812     options.thread = -1;
813
814     int opt;
815     while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
816         switch (opt) {
817         case 'h':
818             help();
819             return 0;
820         case CALLS_OPT:
821             options.calls = trace::CallSet(optarg);
822             break;
823         case DEPS_OPT:
824             options.dependency_analysis = true;
825             break;
826         case NO_DEPS_OPT:
827             options.dependency_analysis = false;
828             break;
829         case PRUNE_OPT:
830             options.prune_uninteresting = true;
831             break;
832         case NO_PRUNE_OPT:
833             options.prune_uninteresting = false;
834             break;
835         case 'x':
836             options.dependency_analysis = false;
837             options.prune_uninteresting = false;
838             break;
839         case THREAD_OPT:
840             options.thread = atoi(optarg);
841             break;
842         case 'o':
843             options.output = optarg;
844             break;
845         default:
846             std::cerr << "error: unexpected option `" << opt << "`\n";
847             usage();
848             return 1;
849         }
850     }
851
852     if (optind >= argc) {
853         std::cerr << "error: apitrace trim requires a trace file as an argument.\n";
854         usage();
855         return 1;
856     }
857
858     if (argc > optind + 1) {
859         std::cerr << "error: extraneous arguments:";
860         for (int i = optind + 1; i < argc; i++) {
861             std::cerr << " " << argv[i];
862         }
863         std::cerr << "\n";
864         usage();
865         return 1;
866     }
867
868     return trim_trace(argv[optind], &options);
869 }
870
871 const Command trim_command = {
872     "trim",
873     synopsis,
874     help,
875     command
876 };