Debian Codegraph @

js/src/util/StructuredSpewer.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef jit_StructuredSpewer_h
8 #define jit_StructuredSpewer_h
9
10 #ifdef JS_STRUCTURED_SPEW
11
12 # include "mozilla/Atomics.h"
13 # include "mozilla/Attributes.h"
14 # include "mozilla/EnumeratedArray.h"
15 # include "mozilla/EnumSet.h"
16 # include "mozilla/Maybe.h"
17 # include "mozilla/Sprintf.h"
18
19 # include "jstypes.h"
20 # include "js/Printer.h"
21 # include "vm/JSONPrinter.h"
22
23 # ifdef XP_WIN
24 # include <process.h>
25 # define getpid _getpid
26 # else
27 # include <unistd.h>
28 # endif
29
30 // [SMDOC] JSON Structured Spewer
31 //
32 // This spewer design has two goals:
33 //
34 // 1. Provide a spew mechanism that has first-class support for slicing and
35 // dicing output. This means that filtering by script and channel should be
36 // the dominant output mechanism.
37 // 2. Provide a simple powerful mechanism for getting information out of the
38 // compiler and into tools. I'm inspired by tools like CacheIR analyzer,
39 // IR Hydra, and the upcoming tracelogger integration into
40 // profiler.firefox.com.
41 //
42 // The spewer has four main control knobs, all currently set as
43 // environment variables. All but the first are optional. When the spewer is
44 // activated through the browser, it is synchronized with the gecko profiler
45 // start and stop routines. Setting SPEW=AtStartup activates the spewer at
46 // startup instead of profiler start, but profiler stop will still deactivate
47 // the spewer.
48 //
49 // SPEW: Activates the spewer. The value provided is interpreted as a comma
50 // separated list that selects channels by name. Currently there's no
51 // mapping between internal and external names, so the channel names
52 // are exactly those described in STRUCTURED_CHANNEL_LIST below.
53 //
54 // SPEW_FILE: Selects the file to write to. An absolute path.
55 //
56 // SPEW_FILTER: A string which is matched against 'signature' constructed or a
57 // JSScript, currently connsisting of filename:line:col.
58 //
59 // Matching in this version is merely finding the string in
60 // in question in the 'signature'
61 //
62 // SPEW_UPLOAD: If this variable is set as well as MOZ_UPLOAD_DIR, output goes
63 // to $MOZ_UPLOAD_DIR/spew_output* to ease usage with Treeherder.
64 //
65 // Other notes:
66 // - Thread safety is provided by opening a new spewer file for every thread.
67 // - Each file is prefixed with the PID to handle multiple processes.
68 // - Files are opened lazily, just before the first write to them.
69
70 class JS_PUBLIC_API JSScript;
71
72 namespace js {
73
74 # define STRUCTURED_CHANNEL_LIST(_) \
75 _(BaselineICStats) \
76 _(CacheIRHealthReport)
77
78 // Structured spew channels
79 enum class SpewChannel {
80 # define STRUCTURED_CHANNEL(name) name,
81 STRUCTURED_CHANNEL_LIST(STRUCTURED_CHANNEL)
82 # undef STRUCTURED_CHANNEL
83 Count,
84 Disabled
85 };
86
87 // A filter is used to select what channel is enabled
88 //
89 // To save memory, JSScripts do not have their own filters, but instead have
90 // a single bit which tracks if that script has opted into spewing.
91 class StructuredSpewFilter {
92 // Indicates what spew channel is enabled.
93 SpewChannel channel_ = SpewChannel::Disabled;
94
95 public:
96 // Return true iff any channel is enabled.
97 bool isChannelSelected() const {
98 return !(channel_ == SpewChannel::Disabled);
99 }
100
101 // Return true iff spew is enabled for this channel for
102 // the script this was created for.
103 bool enabled(SpewChannel x) const { return channel_ == x; }
104
105 // Returns true if we have enabled a new channel, false otherwise.
106 bool enableChannel(SpewChannel x) {
107 // Assert that we are not going to set the channel to
108 // SpewChannel::Disabled.
109 MOZ_ASSERT(x != SpewChannel::Disabled);
110 if (!isChannelSelected()) {
111 channel_ = x;
112 return true;
113 }
114
115 return false;
116 }
117
118 void disableAllChannels() { channel_ = SpewChannel::Disabled; }
119 };
120
121 class StructuredSpewer {
122 public:
123 StructuredSpewer()
124 : outputInitializationAttempted_(false),
125 spewingEnabled_(0),
126 json_(mozilla::Nothing()),
127 selectedChannel_() {
128 if (getenv("SPEW")) {
129 parseSpewFlags(getenv("SPEW"));
130 }
131 }
132
133 ~StructuredSpewer() {
134 if (json_.isSome()) {
135 json_->endList();
136 output_.flush();
137 output_.finish();
138 json_.reset();
139 }
140 }
141
142 void enableSpewing() { spewingEnabled_++; }
143
144 void disableSpewing() {
145 MOZ_ASSERT(spewingEnabled_ > 0);
146 spewingEnabled_--;
147 }
148
149 // Check if the spewer is enabled for a particular script, used to power
150 // script level filtering.
151 bool enabled(JSScript* script);
152
153 // A generic printf like spewer that logs the formatted string.
154 static void spew(JSContext* cx, SpewChannel channel, const char* fmt, ...)
155 MOZ_FORMAT_PRINTF(3, 4);
156
157 // Returns true iff the channel is enabled for the given script.
158 bool enabled(JSContext* cx, const JSScript* script,
159 SpewChannel channel) const;
160
161 private:
162 // In order to support lazy initialization, and simultaneously support a
163 // failure to open a log file being non-fatal (as lazily reporting failure
164 // would be hard, we have an akward set of states to represent.
165 //
166 // We need to handle:
167 // - Output file not initialized, and not yet attempted
168 // - Output file not intialized, attempted, and failed.
169 // - Output file initialized, JSON writer ready for input.
170 //
171 // Because Fprinter doesn't record whether or not its initialization was
172 // attempted, we keep track of that here.
173 //
174 // The contract we require is that ensureInitializationAttempted() be called
175 // just before any attempte to write. This will ensure the file open is
176 // attemped in the right place.
177 bool outputInitializationAttempted_;
178
179 // Indicates the number of times spewing has been enabled. If
180 // spewingEnabled_ is greater than zero, then spewing is enabled.
181 size_t spewingEnabled_;
182
183 Fprinter output_;
184 mozilla::Maybe<JSONPrinter> json_;
185
186 // Globally selected channel.
187 StructuredSpewFilter selectedChannel_;
188
189 using NameArray = mozilla::EnumeratedArray<SpewChannel, const char*,
190 size_t(SpewChannel::Count)>;
191 // Channel Names
192 static NameArray const names_;
193
194 // Get channel name
195 static const char* getName(SpewChannel channel) { return names_[channel]; }
196
197 // Call just before writes to the output are expected.
198 //
199 // Avoids opening files that will remain empty
200 //
201 // Returns true iff we are able to write now.
202 bool ensureInitializationAttempted();
203
204 void tryToInitializeOutput(const char* path);
205
206 // Using flags, choose the enabled channels for this spewer.
207 void parseSpewFlags(const char* flags);
208
209 // Returns true iff the channels is enabled
210 bool enabled(SpewChannel channel) {
211 return (spewingEnabled_ > 0 && selectedChannel_.enabled(channel));
212 }
213
214 // Start a record
215 void startObject(JSContext* cx, const JSScript* script, SpewChannel channel);
216
217 friend class AutoSpewChannel;
218 friend class AutoStructuredSpewer;
219 };
220
221 // An RAII class for accessing the structured spewer.
222 //
223 // This class prefixes the spew with channel and location information.
224 //
225 // Before writing with this Spewer, it must be checked: ie.
226 //
227 // {
228 // AutoSpew x(...);
229 // if (x) {
230 // x->property("lalala", y);
231 // }
232 // }
233 //
234 // As the selected channel may not be enabled.
235 //
236 // Note: If the lifespan of two AutoSpewers overlap, then the output
237 // may not be well defined JSON. These spewers should be given as
238 // short a lifespan as possible.
239 //
240 // As well, this class cannot be copied or assigned to ensure the
241 // correct number of destructors fire.
242 class MOZ_RAII AutoStructuredSpewer {
243 mozilla::Maybe<JSONPrinter*> printer_;
244 AutoStructuredSpewer(const AutoStructuredSpewer&) = delete;
245 void operator=(AutoStructuredSpewer&) = delete;
246
247 public:
248 explicit AutoStructuredSpewer(JSContext* cx, SpewChannel channel,
249 JSScript* script);
250
251 ~AutoStructuredSpewer() {
252 if (printer_.isSome()) {
253 printer_.ref()->endObject();
254 }
255 }
256
257 explicit operator bool() const { return printer_.isSome(); }
258
259 JSONPrinter* operator->() {
260 MOZ_ASSERT(printer_.isSome());
261 return printer_.ref();
262 }
263
264 JSONPrinter& operator*() {
265 MOZ_ASSERT(printer_.isSome());
266 return *printer_.ref();
267 }
268 };
269
270 // An RAII class for setting a structured spewer's channel.
271 //
272 // This class is used to set a spewer's channel and then automatically
273 // unset the channel when AutoSpewChannel goes out of scope.
274 class MOZ_RAII AutoSpewChannel {
275 JSContext* cx_;
276 bool wasChannelAutoSet = false;
277
278 AutoSpewChannel(const AutoSpewChannel&) = delete;
279 void operator=(AutoSpewChannel&) = delete;
280
281 public:
282 explicit AutoSpewChannel(JSContext* cx, SpewChannel channel,
283 JSScript* script);
284
285 ~AutoSpewChannel();
286 };
287
288 } // namespace js
289
290 #endif
291 #endif /* jit_StructuredSpewer_h */