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