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