Debian Codegraph @

js/public/Printer.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 js_Printer_h
8 #define js_Printer_h
9
10 #include "mozilla/Attributes.h"
11 #include "mozilla/glue/Debug.h"
12 #include "mozilla/Range.h"
13 #include "mozilla/Vector.h"
14
15 #include <stdarg.h>
16 #include <stddef.h>
17 #include <stdio.h>
18 #include <string.h>
19
20 #include "js/TypeDecls.h"
21 #include "js/Utility.h"
22
23 // [SMDOC] *Printer, Sprinter, Fprinter, ...
24 //
25 // # Motivation
26 //
27 // In many places, we want to have functions which are capable of logging
28 // various data structures. Previously, we had logging functions for each
29 // storage, such as using `fwrite`, `printf` or `snprintf`. In additional cases,
30 // many of these logging options were using a string serializing logging
31 // function, only to discard the allocated string after it had been copied to a
32 // file.
33 //
34 // GenericPrinter is an answer to avoid excessive amount of temporary
35 // allocations which are used once, and a way to make logging functions work
36 // independently of the backend they are used with.
37 //
38 // # Design
39 //
40 // The GenericPrinter implements most of `put`, `printf`, `vprintf` and
41 // `putChar` functions, which are implemented using `put` and `putChar`
42 // functions in the derivative classes. Thus, one does not have to reimplement
43 // `putString` nor `printf` for each printer.
44 //
45 // // Logging the value N to whatever printer is provided such as
46 // // a file or a string.
47 // void logN(GenericPrinter& out) {
48 // out.printf("[Logging] %d\n", this->n);
49 // }
50 //
51 // The printing functions are infallible, from the logging functions
52 // perspective. If an issue happens while printing, this would be recorded by
53 // the Printer, and this can be tested using `hadOutOfMemory` function by the
54 // owner of the Printer instance.
55 //
56 // Even in case of failure, printing functions should remain safe to use. Thus
57 // calling `put` twice in a row is safe even if no check for `hadOutOfMemory` is
58 // performed. This is necessary to simplify the control flow and avoid bubble up
59 // failures out of logging functions.
60 //
61 // Note, being safe to use does not imply correctness. In case of failure the
62 // correctness of the printed characters is no longer guarantee. One should use
63 // `hadOutOfMemory` function to know if any failure happened which might have
64 // caused incorrect content to be saved. In some cases, such as `Sprinter`,
65 // where the string buffer can be extracted, the returned value would account
66 // for checking `hadOutOfMemory`.
67 //
68 // # Implementations
69 //
70 // The GenericPrinter is a base class where the derivative classes are providing
71 // different implementations which have their own advantages and disadvantages:
72 //
73 // - Fprinter: FILE* printer. Write the content directly to a file.
74 //
75 // - Sprinter: System allocator C-string buffer. Write the content to a buffer
76 // which is reallocated as more content is added. The buffer can then be
77 // extracted into a C-string or a JSString, respectively using `release` and
78 // `releaseJS`.
79 //
80 // - LSprinter: LifoAlloc C-string rope. Write the content to a list of chunks
81 // in a LifoAlloc buffer, no-reallocation occur but one should use
82 // `exportInto` to serialize its content to a Sprinter or a Fprinter. This is
83 // useful to avoid reallocation copies, while using an existing LifoAlloc.
84 //
85 // - SEPrinter: Roughly the same as Fprinter for stderr, except it goes through
86 // printf_stderr, which makes sure the output goes to a useful place: the
87 // Android log or the Windows debug output.
88 //
89 // - EscapePrinter: Wrapper around other printers, to escape characters when
90 // necessary.
91 //
92 // # Print UTF-16
93 //
94 // The GenericPrinter only handle `char` inputs, which is good enough for ASCII
95 // and Latin1 character sets. However, to handle UTF-16, one should use an
96 // EscapePrinter as well as a policy for escaping characters.
97 //
98 // One might require different escaping policies based on the escape sequences
99 // and based on the set of accepted character for the content generated. For
100 // example, JSON does not specify \x<XX> escape sequences.
101 //
102 // Today the following escape policies exists:
103 //
104 // - StringEscape: Produce C-like escape sequences: \<c>, \x<XX> and \u<XXXX>.
105 // - JSONEscape: Produce JSON escape sequences: \<c> and \u<XXXX>.
106 //
107 // An escape policy is defined by 2 functions:
108 //
109 // bool isSafeChar(char16_t c):
110 // Returns whether a character can be printed without being escaped.
111 //
112 // void convertInto(GenericPrinter& out, char16_t c):
113 // Calls the printer with the escape sequence for the character given as
114 // argument.
115 //
116 // To use an escape policy, the printer should be wrapped using an EscapePrinter
117 // as follows:
118 //
119 // {
120 // // The escaped string is surrounded by double-quotes, escape the double
121 // // quotes as well.
122 // StringEscape esc('"');
123 //
124 // // Wrap our existing `GenericPrinter& out` using the `EscapePrinter`.
125 // EscapePrinter ep(out, esc);
126 //
127 // // Append a sequence of characters which might contain UTF-16 characters.
128 // ep.put(chars);
129 // }
130 //
131
132 namespace js {
133
134 class LifoAlloc;
135
136 // Generic printf interface, similar to an ostream in the standard library.
137 //
138 // This class is useful to make generic printers which can work either with a
139 // file backend, with a buffer allocated with an JSContext or a link-list
140 // of chunks allocated with a LifoAlloc.
141 class JS_PUBLIC_API GenericPrinter {
142 protected:
143 bool hadOOM_; // whether setPendingOutOfMemory() has been called.
144
145 constexpr GenericPrinter() : hadOOM_(false) {}
146
147 public:
148 // Puts |len| characters from |s| at the current position. This function might
149 // silently fail and the error can be tested using `hadOutOfMemory()`. Calling
150 // this function or any other printing functions after a failures is accepted,
151 // but the outcome would still remain incorrect and `hadOutOfMemory()` would
152 // still report any of the previous errors.
153 virtual void put(const char* s, size_t len) = 0;
154 inline void put(const char* s) { put(s, strlen(s)); }
155 inline void put(mozilla::Span<const char> s) { put(s.data(), s.size()); };
156
157 // Put a mozilla::Span / mozilla::Range of Latin1Char or char16_t characters
158 // in the output.
159 //
160 // Note that the char16_t variant is expected to crash unless putChar is
161 // overriden to handle properly the full set of WTF-16 character set.
162 virtual void put(mozilla::Span<const JS::Latin1Char> str);
163 virtual void put(mozilla::Span<const char16_t> str);
164
165 // Same as the various put function but only appending a single character.
166 //
167 // Note that the char16_t variant is expected to crash unless putChar is
168 // overriden to handle properly the full set of WTF-16 character set.
169 virtual inline void putChar(const char c) { put(&c, 1); }
170 virtual inline void putChar(const JS::Latin1Char c) { putChar(char(c)); }
171 virtual inline void putChar(const char16_t c) {
172 MOZ_CRASH("Use an EscapePrinter to handle all characters");
173 }
174
175 virtual void putString(JSContext* cx, JSString* str);
176
177 // Prints a formatted string into the buffer.
178 void printf(const char* fmt, ...) MOZ_FORMAT_PRINTF(2, 3);
179 void vprintf(const char* fmt, va_list ap) MOZ_FORMAT_PRINTF(2, 0);
180
181 // In some cases, such as handling JSRopes in a less-quadratic worse-case,
182 // it might be useful to copy content which has already been generated.
183 //
184 // If the buffer is back-readable, then this function should return `true`
185 // and `putFromIndex` should be implemented to delegate to a `put` call at
186 // the matching index and the corresponding length. To provide the index
187 // argument of `putFromIndex`, the `index` method should also be implemented
188 // to return the index within the inner buffer used by the printer.
189 virtual bool canPutFromIndex() const { return false; }
190
191 // Append to the current buffer, bytes which have previously been appended
192 // before.
193 virtual void putFromIndex(size_t index, size_t length) {
194 MOZ_CRASH("Calls to putFromIndex should be guarded by canPutFromIndex.");
195 }
196
197 // When the printer has a seekable buffer and `canPutFromIndex` returns
198 // `true`, this function can return the `index` of the next character to be
199 // added to the buffer.
200 //
201 // This function is monotonic. Thus, if the printer encounter an
202 // Out-Of-Memory issue, then the returned index should be the maximal value
203 // ever returned.
204 virtual size_t index() const { return 0; }
205
206 // In some printers, this ensure that the content is fully written.
207 virtual void flush() { /* Do nothing */ }
208
209 // Set a flag that a string operation failed to get the memory it requested.
210 // The pending out of memory error should be handled by the consumer.
211 virtual void setPendingOutOfMemory();
212
213 // Return true if this Sprinter ran out of memory.
214 virtual bool hadOutOfMemory() const { return hadOOM_; }
215 };
216
217 // Sprintf / JSSprintf, but with unlimited and automatically allocated
218 // buffering.
219 class JS_PUBLIC_API StringPrinter : public GenericPrinter {
220 public:
221 // Check that the invariant holds at the entry and exit of a scope.
222 struct InvariantChecker {
223 const StringPrinter* parent;
224
225 explicit InvariantChecker(const StringPrinter* p) : parent(p) {
226 parent->checkInvariants();
227 }
228
229 ~InvariantChecker() { parent->checkInvariants(); }
230 };
231
232 JSContext* maybeCx;
233
234 private:
235 static const size_t DefaultSize;
236 #ifdef DEBUG
237 bool initialized; // true if this is initialized, use for debug builds
238 #endif
239 bool shouldReportOOM; // whether to report OOM to the maybeCx
240 char* base; // malloc'd buffer address
241 size_t size; // size of buffer allocated at base
242 ptrdiff_t offset; // offset of next free char in buffer
243
244 // The arena to be used by jemalloc to allocate the string into. This is
245 // selected by the child classes when calling the constructor. JSStrings have
246 // a different arena than strings which do not belong to the JS engine, and as
247 // such when building a JSString with the intent of avoiding reallocation, the
248 // destination arena has to be selected upfront.
249 arena_id_t arena;
250
251 private:
252 [[nodiscard]] bool realloc_(size_t newSize);
253
254 protected:
255 // JSContext* parameter is optional and can be omitted if the following
256 // are not used.
257 // * putString method with JSString
258 // * QuoteString function with JSString
259 // * JSONQuoteString function with JSString
260 //
261 // If JSContext* parameter is not provided, or shouldReportOOM is false,
262 // the consumer should manually report OOM on any failure.
263 explicit StringPrinter(arena_id_t arena, JSContext* maybeCx = nullptr,
264 bool shouldReportOOM = true);
265 ~StringPrinter();
266
267 JS::UniqueChars releaseChars();
268 JSString* releaseJS(JSContext* cx);
269
270 public:
271 // Initialize this sprinter, returns false on error.
272 [[nodiscard]] bool init();
273
274 void checkInvariants() const;
275
276 // Attempt to reserve len + 1 space (for a trailing nullptr byte). If the
277 // attempt succeeds, return a pointer to the start of that space and adjust
278 // the internal content. The caller *must* completely fill this space on
279 // success.
280 char* reserve(size_t len);
281
282 // Puts |len| characters from |s| at the current position. May OOM, which must
283 // be checked by testing the return value of releaseJS() at the end of
284 // printing.
285 virtual void put(const char* s, size_t len) final;
286 using GenericPrinter::put; // pick up |put(const char* s);|
287
288 virtual bool canPutFromIndex() const final { return true; }
289 virtual void putFromIndex(size_t index, size_t length) final {
290 MOZ_ASSERT(index <= this->index());
291 MOZ_ASSERT(index + length <= this->index());
292 put(base + index, length);
293 }
294 virtual size_t index() const final { return length(); }
295
296 virtual void putString(JSContext* cx, JSString* str) final;
297
298 size_t length() const;
299
300 // When an OOM has already been reported on the Sprinter, this function will
301 // forward this error to the JSContext given in the Sprinter initialization.
302 //
303 // If no JSContext had been provided or the Sprinter is configured to not
304 // report OOM, then nothing happens.
305 void forwardOutOfMemory();
306 };
307
308 class JS_PUBLIC_API Sprinter : public StringPrinter {
309 public:
310 explicit Sprinter(JSContext* maybeCx = nullptr, bool shouldReportOOM = true)
311 : StringPrinter(js::MallocArena, maybeCx, shouldReportOOM) {}
312 ~Sprinter() {}
313
314 JS::UniqueChars release() { return releaseChars(); }
315 };
316
317 class JS_PUBLIC_API JSSprinter : public StringPrinter {
318 public:
319 explicit JSSprinter(JSContext* cx)
320 : StringPrinter(js::StringBufferArena, cx, true) {}
321 ~JSSprinter() {}
322
323 JSString* release(JSContext* cx) { return releaseJS(cx); }
324 };
325
326 // Fprinter, print a string directly into a file.
327 class JS_PUBLIC_API Fprinter final : public GenericPrinter {
328 private:
329 FILE* file_;
330 bool init_;
331
332 public:
333 explicit Fprinter(FILE* fp);
334
335 constexpr Fprinter() : file_(nullptr), init_(false) {}
336
337 #ifdef DEBUG
338 ~Fprinter();
339 #endif
340
341 // Initialize this printer, returns false on error.
342 [[nodiscard]] bool init(const char* path);
343 void init(FILE* fp);
344 bool isInitialized() const { return file_ != nullptr; }
345 void flush() override;
346 void finish();
347
348 // Puts |len| characters from |s| at the current position. Errors may be
349 // detected with hadOutOfMemory() (which will be set for any fwrite() error,
350 // not just OOM.)
351 void put(const char* s, size_t len) override;
352 using GenericPrinter::put; // pick up |put(const char* s);|
353 };
354
355 // SEprinter, print using printf_stderr (goes to Android log, Windows debug,
356 // else just stderr).
357 class SEprinter final : public GenericPrinter {
358 public:
359 constexpr SEprinter() {}
360
361 // Puts |len| characters from |s| at the current position. Ignores errors.
362 virtual void put(const char* s, size_t len) override {
363 printf_stderr("%.*s", int(len), s);
364 }
365 using GenericPrinter::put; // pick up |put(const char* s);|
366 };
367
368 // LSprinter, is similar to Sprinter except that instead of using an
369 // JSContext to allocate strings, it use a LifoAlloc as a backend for the
370 // allocation of the chunk of the string.
371 class JS_PUBLIC_API LSprinter final : public GenericPrinter {
372 private:
373 struct Chunk {
374 Chunk* next;
375 size_t length;
376
377 char* chars() { return reinterpret_cast<char*>(this + 1); }
378 char* end() { return chars() + length; }
379 };
380
381 private:
382 LifoAlloc* alloc_; // LifoAlloc used as a backend of chunk allocations.
383 Chunk* head_;
384 Chunk* tail_;
385 size_t unused_;
386
387 public:
388 explicit LSprinter(LifoAlloc* lifoAlloc);
389 ~LSprinter();
390
391 // Copy the content of the chunks into another printer, such that we can
392 // flush the content of this printer to a file.
393 void exportInto(GenericPrinter& out) const;
394
395 // Drop the current string, and let them be free with the LifoAlloc.
396 void clear();
397
398 // Puts |len| characters from |s| at the current position.
399 virtual void put(const char* s, size_t len) override;
400 using GenericPrinter::put; // pick up |put(const char* s);|
401 };
402
403 // Escaping printers work like any other printer except that any added character
404 // are checked for escaping sequences. This one would escape a string such that
405 // it can safely be embedded in a JS string.
406 template <typename Delegate, typename Escape>
407 class JS_PUBLIC_API EscapePrinter final : public GenericPrinter {
408 size_t lengthOfSafeChars(const char* s, size_t len) {
409 for (size_t i = 0; i < len; i++) {
410 if (!esc.isSafeChar(uint8_t(s[i]))) {
411 return i;
412 }
413 }
414 return len;
415 }
416
417 private:
418 Delegate& out;
419 Escape& esc;
420
421 public:
422 EscapePrinter(Delegate& out, Escape& esc) : out(out), esc(esc) {}
423 ~EscapePrinter() {}
424
425 using GenericPrinter::put;
426 void put(const char* s, size_t len) override {
427 const char* b = s;
428 while (len) {
429 size_t index = lengthOfSafeChars(b, len);
430 if (index) {
431 out.put(b, index);
432 len -= index;
433 b += index;
434 }
435 if (len) {
436 esc.convertInto(out, char16_t(uint8_t(*b)));
437 len -= 1;
438 b += 1;
439 }
440 }
441 }
442
443 inline void putChar(const char c) override {
444 if (esc.isSafeChar(char16_t(uint8_t(c)))) {
445 out.putChar(char(c));
446 return;
447 }
448 esc.convertInto(out, char16_t(uint8_t(c)));
449 }
450
451 inline void putChar(const JS::Latin1Char c) override {
452 if (esc.isSafeChar(char16_t(c))) {
453 out.putChar(char(c));
454 return;
455 }
456 esc.convertInto(out, char16_t(c));
457 }
458
459 inline void putChar(const char16_t c) override {
460 if (esc.isSafeChar(c)) {
461 out.putChar(char(c));
462 return;
463 }
464 esc.convertInto(out, c);
465 }
466
467 // Forward calls to delegated printer.
468 bool canPutFromIndex() const override { return out.canPutFromIndex(); }
469 void putFromIndex(size_t index, size_t length) final {
470 out.putFromIndex(index, length);
471 }
472 size_t index() const final { return out.index(); }
473 void flush() final { out.flush(); }
474 void setPendingOutOfMemory() final { out.setPendingOutOfMemory(); }
475 bool hadOutOfMemory() const final { return out.hadOutOfMemory(); }
476 };
477
478 class JS_PUBLIC_API JSONEscape {
479 public:
480 bool isSafeChar(char16_t c);
481 void convertInto(GenericPrinter& out, char16_t c);
482 };
483
484 class JS_PUBLIC_API StringEscape {
485 private:
486 const char quote = '\0';
487
488 public:
489 explicit StringEscape(const char quote = '\0') : quote(quote) {}
490
491 bool isSafeChar(char16_t c);
492 void convertInto(GenericPrinter& out, char16_t c);
493 };
494
495 class JS_PUBLIC_API WATStringEscape {
496 public:
497 bool isSafeChar(char16_t c);
498 void convertInto(GenericPrinter& out, char16_t c);
499 };
500
501 // A GenericPrinter that can format its output in a structured way, with nice
502 // formatting.
503 //
504 // Suppose you want to print wasm structs, and you want to change the
505 // presentation depending on the number of fields:
506 //
507 // (struct)
508 // (struct (field i32))
509 // (struct
510 // (field i32)
511 // (field i64)
512 // )
513 //
514 // All three of these can be handled identically with quite straightforward
515 // code:
516 //
517 // out.printf("(struct");
518 // {
519 // StructuredPrinter::Scope _(out);
520 //
521 // for (auto field : fields) {
522 // out.brk(" ", "\n");
523 // out.printf("(field ");
524 // DumpFieldType(field.type, out);
525 // out.printf(")");
526 // }
527 // out.brk("", "\n");
528 //
529 // if (fields.length() > 1) {
530 // out.expand();
531 // }
532 // }
533 // out.printf(")");
534 //
535 // The `brk` method can be used to emit one of two "break" characters depending
536 // on whether the output is "expanded" or "collapsed". The decision about which
537 // style to emit is made later, by conditionally calling `out.expand()`.
538 // Additionally, the use of `StructuredPrinter::Scope` ensures that the struct
539 // fields are indented *if* the output is expanded.
540 //
541 // Newlines may still be printed at any time. Newlines will force the current
542 // scope to be expanded, along with any parent scopes.
543 class JS_PUBLIC_API StructuredPrinter final : public GenericPrinter {
544 GenericPrinter& out_;
545
546 // The number of spaces to insert for each indent.
547 int indentAmount_;
548 bool pendingIndent_;
549
550 // The index of the last expanded scope (or -1 if all scopes are collapsed).
551 int expandedDepth_ = -1;
552
553 struct Break {
554 uint32_t bufferPos;
555 bool isCollapsed;
556 const char* collapsed;
557 const char* expanded;
558 };
559
560 struct ScopeInfo {
561 uint32_t startPos;
562 int indent;
563 };
564
565 // Content is buffered while in collapsed mode in case it gets expanded later.
566 mozilla::Vector<char, 80> buffer_;
567 // Info about break characters in the buffer.
568 // Cleared when the buffer is cleared.
569 mozilla::Vector<Break, 8> breaks_;
570 // The stack of scopes maintained by the printer.
571 mozilla::Vector<ScopeInfo, 16> scopes_;
572
573 int scopeDepth() { return int(scopes_.length()) - 1; }
574
575 void putIndent(int level = -1);
576 void putBreak(const Break& brk);
577 void putWithMaybeIndent(const char* s, size_t len, int level = -1);
578
579 public:
580 explicit StructuredPrinter(GenericPrinter& out, int indentAmount = 2)
581 : out_(out), indentAmount_(indentAmount) {
582 pushScope();
583 }
584 ~StructuredPrinter() {
585 popScope();
586 flush();
587 }
588
589 void pushScope();
590 void popScope();
591
592 void brk(const char* collapsed, const char* expanded);
593 void expand();
594 bool isExpanded();
595
596 void flush() override;
597
598 class Scope {
599 StructuredPrinter& printer_;
600
601 public:
602 explicit Scope(StructuredPrinter& printer) : printer_(printer) {
603 printer_.pushScope();
604 }
605 ~Scope() { printer_.popScope(); }
606 };
607
608 virtual void put(const char* s, size_t len) override;
609 using GenericPrinter::put; // pick up |inline void put(const char* s);|
610 };
611
612 // Map escaped code to the letter/symbol escaped with a backslash.
613 extern const char js_EscapeMap[];
614
615 // Return a C-string containing the chars in str, with any non-printing chars
616 // escaped. If the optional quote parameter is present and is not '\0', quotes
617 // (as specified by the quote argument) are also escaped, and the quote
618 // character is appended at the beginning and end of the result string.
619 // The returned string is guaranteed to contain only ASCII characters.
620 extern JS_PUBLIC_API JS::UniqueChars QuoteString(JSContext* cx, JSString* str,
621 char quote = '\0');
622
623 // Appends the quoted string to the given Sprinter. Follows the same semantics
624 // as QuoteString from above.
625 extern JS_PUBLIC_API void QuoteString(Sprinter* sp, JSString* str,
626 char quote = '\0');
627
628 // Appends the quoted string to the given Sprinter. Follows the same
629 // Appends the JSON quoted string to the given Sprinter.
630 extern JS_PUBLIC_API void JSONQuoteString(StringPrinter* sp, JSString* str);
631
632 // Internal implementation code for QuoteString methods above.
633 enum class QuoteTarget { String, JSON };
634
635 template <QuoteTarget target, typename CharT>
636 void JS_PUBLIC_API QuoteString(Sprinter* sp,
637 const mozilla::Range<const CharT>& chars,
638 char quote = '\0');
639
640 } // namespace js
641
642 #endif // js_Printer_h