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