| 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 |
#include "js/Printer.h" |
| 8 |
|
| 9 |
#include "mozilla/PodOperations.h" |
| 10 |
#include "mozilla/Printf.h" |
| 11 |
#include "mozilla/RangedPtr.h" |
| 12 |
|
| 13 |
#include <stdarg.h> |
| 14 |
#include <stdio.h> |
| 15 |
|
| 16 |
#include "ds/LifoAlloc.h" |
| 17 |
#include "js/CharacterEncoding.h" |
| 18 |
#include "util/Memory.h" |
| 19 |
#include "util/Text.h" |
| 20 |
#include "util/WindowsWrapper.h" |
| 21 |
#include "vm/StringType.h" |
| 22 |
|
| 23 |
using mozilla::PodCopy; |
| 24 |
|
| 25 |
namespace { |
| 26 |
|
| 27 |
class GenericPrinterPrintfTarget : public mozilla::PrintfTarget { |
| 28 |
public: |
| 29 |
explicit GenericPrinterPrintfTarget(js::GenericPrinter& p) : printer(p) {} |
| 30 |
|
| 31 |
bool append(const char* sp, size_t len) override { |
| 32 |
printer.put(sp, len); |
| 33 |
return true; |
| 34 |
} |
| 35 |
|
| 36 |
private: |
| 37 |
js::GenericPrinter& printer; |
| 38 |
}; |
| 39 |
|
| 40 |
} // namespace |
| 41 |
|
| 42 |
namespace js { |
| 43 |
|
| 44 |
void GenericPrinter::setPendingOutOfMemory() { |
| 45 |
if (hadOOM_) { |
| 46 |
return; |
| 47 |
} |
| 48 |
hadOOM_ = true; |
| 49 |
} |
| 50 |
|
| 51 |
void GenericPrinter::put(mozilla::Span<const JS::Latin1Char> str) { |
| 52 |
if (!str.Length()) { |
| 53 |
return; |
| 54 |
} |
| 55 |
put(reinterpret_cast<const char*>(&str[0]), str.Length()); |
| 56 |
} |
| 57 |
|
| 58 |
void GenericPrinter::put(mozilla::Span<const char16_t> str) { |
| 59 |
for (char16_t c : str) { |
| 60 |
putChar(c); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
void GenericPrinter::putString(JSContext* cx, JSString* str) { |
| 65 |
StringSegmentRange iter(cx); |
| 66 |
if (!iter.init(str)) { |
| 67 |
setPendingOutOfMemory(); |
| 68 |
return; |
| 69 |
} |
| 70 |
JS::AutoCheckCannotGC nogc; |
| 71 |
while (!iter.empty()) { |
| 72 |
JSLinearString* linear = iter.front(); |
| 73 |
if (linear->hasLatin1Chars()) { |
| 74 |
put(linear->latin1Range(nogc)); |
| 75 |
} else { |
| 76 |
put(linear->twoByteRange(nogc)); |
| 77 |
} |
| 78 |
if (!iter.popFront()) { |
| 79 |
setPendingOutOfMemory(); |
| 80 |
return; |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
void GenericPrinter::printf(const char* fmt, ...) { |
| 86 |
va_list va; |
| 87 |
va_start(va, fmt); |
| 88 |
vprintf(fmt, va); |
| 89 |
va_end(va); |
| 90 |
} |
| 91 |
|
| 92 |
void GenericPrinter::vprintf(const char* fmt, va_list ap) { |
| 93 |
// Simple shortcut to avoid allocating strings. |
| 94 |
if (strchr(fmt, '%') == nullptr) { |
| 95 |
put(fmt); |
| 96 |
return; |
| 97 |
} |
| 98 |
|
| 99 |
GenericPrinterPrintfTarget printer(*this); |
| 100 |
(void)printer.vprint(fmt, ap); |
| 101 |
} |
| 102 |
|
| 103 |
const size_t StringPrinter::DefaultSize = 64; |
| 104 |
|
| 105 |
bool StringPrinter::realloc_(size_t newSize) { |
| 106 |
MOZ_ASSERT(newSize > (size_t)offset); |
| 107 |
if (hadOOM_) { |
| 108 |
return false; |
| 109 |
} |
| 110 |
char* newBuf = (char*)js_arena_realloc(arena, base, newSize); |
| 111 |
if (!newBuf) { |
| 112 |
// NOTE: The consumer of this method shouldn't directly propagate the error |
| 113 |
// mode to the outside of this class. |
| 114 |
// The OOM flag set here should be forwarded to the JSContext with |
| 115 |
// the releaseChars etc. |
| 116 |
setPendingOutOfMemory(); |
| 117 |
return false; |
| 118 |
} |
| 119 |
base = newBuf; |
| 120 |
size = newSize; |
| 121 |
base[size - 1] = '\0'; |
| 122 |
return true; |
| 123 |
} |
| 124 |
|
| 125 |
StringPrinter::StringPrinter(arena_id_t arena, JSContext* maybeCx, |
| 126 |
bool shouldReportOOM) |
| 127 |
: maybeCx(maybeCx), |
| 128 |
#ifdef DEBUG |
| 129 |
initialized(false), |
| 130 |
#endif |
| 131 |
shouldReportOOM(maybeCx && shouldReportOOM), |
| 132 |
base(nullptr), |
| 133 |
size(0), |
| 134 |
offset(0), |
| 135 |
arena(arena) { |
| 136 |
} |
| 137 |
|
| 138 |
StringPrinter::~StringPrinter() { |
| 139 |
#ifdef DEBUG |
| 140 |
if (initialized) { |
| 141 |
checkInvariants(); |
| 142 |
} |
| 143 |
#endif |
| 144 |
js_free(base); |
| 145 |
} |
| 146 |
|
| 147 |
bool StringPrinter::init() { |
| 148 |
MOZ_ASSERT(!initialized); |
| 149 |
base = js_pod_arena_malloc<char>(arena, DefaultSize); |
| 150 |
if (!base) { |
| 151 |
setPendingOutOfMemory(); |
| 152 |
forwardOutOfMemory(); |
| 153 |
return false; |
| 154 |
} |
| 155 |
#ifdef DEBUG |
| 156 |
initialized = true; |
| 157 |
#endif |
| 158 |
*base = '\0'; |
| 159 |
size = DefaultSize; |
| 160 |
base[size - 1] = '\0'; |
| 161 |
return true; |
| 162 |
} |
| 163 |
|
| 164 |
void StringPrinter::checkInvariants() const { |
| 165 |
MOZ_ASSERT(initialized); |
| 166 |
MOZ_ASSERT((size_t)offset < size); |
| 167 |
MOZ_ASSERT(base[size - 1] == '\0'); |
| 168 |
} |
| 169 |
|
| 170 |
UniqueChars StringPrinter::releaseChars() { |
| 171 |
if (hadOOM_) { |
| 172 |
forwardOutOfMemory(); |
| 173 |
return nullptr; |
| 174 |
} |
| 175 |
|
| 176 |
checkInvariants(); |
| 177 |
char* str = base; |
| 178 |
base = nullptr; |
| 179 |
offset = size = 0; |
| 180 |
#ifdef DEBUG |
| 181 |
initialized = false; |
| 182 |
#endif |
| 183 |
return UniqueChars(str); |
| 184 |
} |
| 185 |
|
| 186 |
JSString* StringPrinter::releaseJS(JSContext* cx) { |
| 187 |
if (hadOOM_) { |
| 188 |
MOZ_ASSERT_IF(maybeCx, maybeCx == cx); |
| 189 |
forwardOutOfMemory(); |
| 190 |
return nullptr; |
| 191 |
} |
| 192 |
|
| 193 |
checkInvariants(); |
| 194 |
|
| 195 |
// Extract StringPrinter data. |
| 196 |
size_t len = length(); |
| 197 |
UniqueChars str(base); |
| 198 |
|
| 199 |
// Reset StringPrinter. |
| 200 |
base = nullptr; |
| 201 |
offset = 0; |
| 202 |
size = 0; |
| 203 |
#ifdef DEBUG |
| 204 |
initialized = false; |
| 205 |
#endif |
| 206 |
|
| 207 |
// Convert extracted data to a JSString, reusing the current buffer whenever |
| 208 |
// possible. |
| 209 |
JS::UTF8Chars utf8(str.get(), len); |
| 210 |
JS::SmallestEncoding encoding = JS::FindSmallestEncoding(utf8); |
| 211 |
if (encoding == JS::SmallestEncoding::ASCII) { |
| 212 |
UniqueLatin1Chars latin1(reinterpret_cast<JS::Latin1Char*>(str.release())); |
| 213 |
return js::NewString<js::CanGC>(cx, std::move(latin1), len); |
| 214 |
} |
| 215 |
|
| 216 |
size_t length; |
| 217 |
if (encoding == JS::SmallestEncoding::Latin1) { |
| 218 |
UniqueLatin1Chars latin1( |
| 219 |
UTF8CharsToNewLatin1CharsZ(cx, utf8, &length, js::StringBufferArena) |
| 220 |
.get()); |
| 221 |
if (!latin1) { |
| 222 |
return nullptr; |
| 223 |
} |
| 224 |
|
| 225 |
return js::NewString<js::CanGC>(cx, std::move(latin1), length); |
| 226 |
} |
| 227 |
|
| 228 |
MOZ_ASSERT(encoding == JS::SmallestEncoding::UTF16); |
| 229 |
|
| 230 |
UniqueTwoByteChars utf16( |
| 231 |
UTF8CharsToNewTwoByteCharsZ(cx, utf8, &length, js::StringBufferArena) |
| 232 |
.get()); |
| 233 |
if (!utf16) { |
| 234 |
return nullptr; |
| 235 |
} |
| 236 |
|
| 237 |
return js::NewString<js::CanGC>(cx, std::move(utf16), length); |
| 238 |
} |
| 239 |
|
| 240 |
char* StringPrinter::reserve(size_t len) { |
| 241 |
InvariantChecker ic(this); |
| 242 |
|
| 243 |
while (len + 1 > size - offset) { /* Include trailing \0 */ |
| 244 |
if (!realloc_(size * 2)) { |
| 245 |
return nullptr; |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
char* sb = base + offset; |
| 250 |
offset += len; |
| 251 |
return sb; |
| 252 |
} |
| 253 |
|
| 254 |
void StringPrinter::put(const char* s, size_t len) { |
| 255 |
InvariantChecker ic(this); |
| 256 |
|
| 257 |
const char* oldBase = base; |
| 258 |
const char* oldEnd = base + size; |
| 259 |
|
| 260 |
char* bp = reserve(len); |
| 261 |
if (!bp) { |
| 262 |
return; |
| 263 |
} |
| 264 |
|
| 265 |
// s is within the buffer already |
| 266 |
if (s >= oldBase && s < oldEnd) { |
| 267 |
// Update the source pointer in case of a realloc-ation. |
| 268 |
size_t index = s - oldBase; |
| 269 |
s = &base[index]; |
| 270 |
memmove(bp, s, len); |
| 271 |
} else { |
| 272 |
js_memcpy(bp, s, len); |
| 273 |
} |
| 274 |
|
| 275 |
bp[len] = '\0'; |
| 276 |
} |
| 277 |
|
| 278 |
void StringPrinter::putString(JSContext* cx, JSString* s) { |
| 279 |
MOZ_ASSERT(cx); |
| 280 |
InvariantChecker ic(this); |
| 281 |
|
| 282 |
JSLinearString* linear = s->ensureLinear(cx); |
| 283 |
if (!linear) { |
| 284 |
return; |
| 285 |
} |
| 286 |
|
| 287 |
size_t length = JS::GetDeflatedUTF8StringLength(linear); |
| 288 |
|
| 289 |
char* buffer = reserve(length); |
| 290 |
if (!buffer) { |
| 291 |
return; |
| 292 |
} |
| 293 |
|
| 294 |
mozilla::DebugOnly<size_t> written = |
| 295 |
JS::DeflateStringToUTF8Buffer(linear, mozilla::Span(buffer, length)); |
| 296 |
MOZ_ASSERT(written == length); |
| 297 |
|
| 298 |
buffer[length] = '\0'; |
| 299 |
} |
| 300 |
|
| 301 |
size_t StringPrinter::length() const { return size_t(offset); } |
| 302 |
|
| 303 |
void StringPrinter::forwardOutOfMemory() { |
| 304 |
MOZ_ASSERT(hadOOM_); |
| 305 |
if (maybeCx && shouldReportOOM) { |
| 306 |
ReportOutOfMemory(maybeCx); |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
const char js_EscapeMap[] = { |
| 311 |
// clang-format off |
| 312 |
'\b', 'b', |
| 313 |
'\f', 'f', |
| 314 |
'\n', 'n', |
| 315 |
'\r', 'r', |
| 316 |
'\t', 't', |
| 317 |
'\v', 'v', |
| 318 |
'"', '"', |
| 319 |
'\'', '\'', |
| 320 |
'\\', '\\', |
| 321 |
'\0' |
| 322 |
// clang-format on |
| 323 |
}; |
| 324 |
|
| 325 |
static const char JSONEscapeMap[] = { |
| 326 |
// clang-format off |
| 327 |
'\b', 'b', |
| 328 |
'\f', 'f', |
| 329 |
'\n', 'n', |
| 330 |
'\r', 'r', |
| 331 |
'\t', 't', |
| 332 |
'"', '"', |
| 333 |
'\\', '\\', |
| 334 |
'\0' |
| 335 |
// clang-format on |
| 336 |
}; |
| 337 |
|
| 338 |
static const char WATEscapeMap[] = { |
| 339 |
// clang-format off |
| 340 |
'\t', 't', |
| 341 |
'\n', 'n', |
| 342 |
'\r', 'r', |
| 343 |
'"', '"', |
| 344 |
'\'', '\'', |
| 345 |
'\\', '\\', |
| 346 |
'\0' |
| 347 |
// clang-format on |
| 348 |
}; |
| 349 |
|
| 350 |
template <QuoteTarget target, typename CharT> |
| 351 |
JS_PUBLIC_API void QuoteString(Sprinter* sp, |
| 352 |
const mozilla::Range<const CharT>& chars, |
| 353 |
char quote) { |
| 354 |
MOZ_ASSERT_IF(target == QuoteTarget::JSON, quote == '\0'); |
| 355 |
|
| 356 |
if (quote) { |
| 357 |
sp->putChar(quote); |
| 358 |
} |
| 359 |
if (target == QuoteTarget::String) { |
| 360 |
StringEscape esc(quote); |
| 361 |
EscapePrinter ep(*sp, esc); |
| 362 |
ep.put(chars); |
| 363 |
} else { |
| 364 |
MOZ_ASSERT(target == QuoteTarget::JSON); |
| 365 |
JSONEscape esc; |
| 366 |
EscapePrinter ep(*sp, esc); |
| 367 |
ep.put(chars); |
| 368 |
} |
| 369 |
if (quote) { |
| 370 |
sp->putChar(quote); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
template JS_PUBLIC_API void QuoteString<QuoteTarget::String, Latin1Char>( |
| 375 |
Sprinter* sp, const mozilla::Range<const Latin1Char>& chars, char quote); |
| 376 |
|
| 377 |
template JS_PUBLIC_API void QuoteString<QuoteTarget::String, char16_t>( |
| 378 |
Sprinter* sp, const mozilla::Range<const char16_t>& chars, char quote); |
| 379 |
|
| 380 |
template JS_PUBLIC_API void QuoteString<QuoteTarget::JSON, Latin1Char>( |
| 381 |
Sprinter* sp, const mozilla::Range<const Latin1Char>& chars, char quote); |
| 382 |
|
| 383 |
template JS_PUBLIC_API void QuoteString<QuoteTarget::JSON, char16_t>( |
| 384 |
Sprinter* sp, const mozilla::Range<const char16_t>& chars, char quote); |
| 385 |
|
| 386 |
JS_PUBLIC_API void QuoteString(Sprinter* sp, JSString* str, |
| 387 |
char quote /*= '\0' */) { |
| 388 |
MOZ_ASSERT(sp->maybeCx); |
| 389 |
if (quote) { |
| 390 |
sp->putChar(quote); |
| 391 |
} |
| 392 |
StringEscape esc(quote); |
| 393 |
EscapePrinter ep(*sp, esc); |
| 394 |
ep.putString(sp->maybeCx, str); |
| 395 |
if (quote) { |
| 396 |
sp->putChar(quote); |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
JS_PUBLIC_API UniqueChars QuoteString(JSContext* cx, JSString* str, |
| 401 |
char quote /* = '\0' */) { |
| 402 |
Sprinter sprinter(cx); |
| 403 |
if (!sprinter.init()) { |
| 404 |
return nullptr; |
| 405 |
} |
| 406 |
QuoteString(&sprinter, str, quote); |
| 407 |
return sprinter.release(); |
| 408 |
} |
| 409 |
|
| 410 |
JS_PUBLIC_API void JSONQuoteString(StringPrinter* sp, JSString* str) { |
| 411 |
MOZ_ASSERT(sp->maybeCx); |
| 412 |
JSONEscape esc; |
| 413 |
EscapePrinter ep(*sp, esc); |
| 414 |
ep.putString(sp->maybeCx, str); |
| 415 |
} |
| 416 |
|
| 417 |
Fprinter::Fprinter(FILE* fp) : file_(nullptr), init_(false) { init(fp); } |
| 418 |
|
| 419 |
#ifdef DEBUG |
| 420 |
Fprinter::~Fprinter() { MOZ_ASSERT_IF(init_, !file_); } |
| 421 |
#endif |
| 422 |
|
| 423 |
bool Fprinter::init(const char* path) { |
| 424 |
MOZ_ASSERT(!file_); |
| 425 |
file_ = fopen(path, "w"); |
| 426 |
if (!file_) { |
| 427 |
return false; |
| 428 |
} |
| 429 |
init_ = true; |
| 430 |
return true; |
| 431 |
} |
| 432 |
|
| 433 |
void Fprinter::init(FILE* fp) { |
| 434 |
MOZ_ASSERT(!file_); |
| 435 |
file_ = fp; |
| 436 |
init_ = false; |
| 437 |
} |
| 438 |
|
| 439 |
void Fprinter::flush() { |
| 440 |
MOZ_ASSERT(file_); |
| 441 |
fflush(file_); |
| 442 |
} |
| 443 |
|
| 444 |
void Fprinter::finish() { |
| 445 |
MOZ_ASSERT(file_); |
| 446 |
if (init_) { |
| 447 |
fclose(file_); |
| 448 |
} |
| 449 |
file_ = nullptr; |
| 450 |
} |
| 451 |
|
| 452 |
void Fprinter::put(const char* s, size_t len) { |
| 453 |
if (hadOutOfMemory()) { |
| 454 |
return; |
| 455 |
} |
| 456 |
|
| 457 |
MOZ_ASSERT(file_); |
| 458 |
int i = fwrite(s, /*size=*/1, /*nitems=*/len, file_); |
| 459 |
if (size_t(i) != len) { |
| 460 |
setPendingOutOfMemory(); |
| 461 |
return; |
| 462 |
} |
| 463 |
#ifdef XP_WIN |
| 464 |
if ((file_ == stderr) && (IsDebuggerPresent())) { |
| 465 |
UniqueChars buf = DuplicateString(s, len); |
| 466 |
if (!buf) { |
| 467 |
setPendingOutOfMemory(); |
| 468 |
return; |
| 469 |
} |
| 470 |
OutputDebugStringA(buf.get()); |
| 471 |
} |
| 472 |
#endif |
| 473 |
} |
| 474 |
|
| 475 |
LSprinter::LSprinter(LifoAlloc* lifoAlloc) |
| 476 |
: alloc_(lifoAlloc), head_(nullptr), tail_(nullptr), unused_(0) {} |
| 477 |
|
| 478 |
LSprinter::~LSprinter() { |
| 479 |
// This LSprinter might be allocated as part of the same LifoAlloc, so we |
| 480 |
// should not expect the destructor to be called. |
| 481 |
} |
| 482 |
|
| 483 |
void LSprinter::exportInto(GenericPrinter& out) const { |
| 484 |
if (!head_) { |
| 485 |
return; |
| 486 |
} |
| 487 |
|
| 488 |
for (Chunk* it = head_; it != tail_; it = it->next) { |
| 489 |
out.put(it->chars(), it->length); |
| 490 |
} |
| 491 |
out.put(tail_->chars(), tail_->length - unused_); |
| 492 |
} |
| 493 |
|
| 494 |
void LSprinter::clear() { |
| 495 |
head_ = nullptr; |
| 496 |
tail_ = nullptr; |
| 497 |
unused_ = 0; |
| 498 |
hadOOM_ = false; |
| 499 |
} |
| 500 |
|
| 501 |
void LSprinter::put(const char* s, size_t len) { |
| 502 |
if (hadOutOfMemory()) { |
| 503 |
return; |
| 504 |
} |
| 505 |
|
| 506 |
// Compute how much data will fit in the current chunk. |
| 507 |
size_t existingSpaceWrite = 0; |
| 508 |
size_t overflow = len; |
| 509 |
if (unused_ > 0 && tail_) { |
| 510 |
existingSpaceWrite = std::min(unused_, len); |
| 511 |
overflow = len - existingSpaceWrite; |
| 512 |
} |
| 513 |
|
| 514 |
// If necessary, allocate a new chunk for overflow data. |
| 515 |
size_t allocLength = 0; |
| 516 |
Chunk* last = nullptr; |
| 517 |
if (overflow > 0) { |
| 518 |
allocLength = |
| 519 |
AlignBytes(sizeof(Chunk) + overflow, js::detail::LIFO_ALLOC_ALIGN); |
| 520 |
|
| 521 |
LifoAlloc::AutoFallibleScope fallibleAllocator(alloc_); |
| 522 |
last = reinterpret_cast<Chunk*>(alloc_->alloc(allocLength)); |
| 523 |
if (!last) { |
| 524 |
setPendingOutOfMemory(); |
| 525 |
return; |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
// All fallible operations complete: now fill up existing space, then |
| 530 |
// overflow space in any new chunk. |
| 531 |
MOZ_ASSERT(existingSpaceWrite + overflow == len); |
| 532 |
|
| 533 |
if (existingSpaceWrite > 0) { |
| 534 |
PodCopy(tail_->end() - unused_, s, existingSpaceWrite); |
| 535 |
unused_ -= existingSpaceWrite; |
| 536 |
s += existingSpaceWrite; |
| 537 |
} |
| 538 |
|
| 539 |
if (overflow > 0) { |
| 540 |
if (tail_ && reinterpret_cast<char*>(last) == tail_->end()) { |
| 541 |
// tail_ and last are consecutive in memory. LifoAlloc has no |
| 542 |
// metadata and is just a bump allocator, so we can cheat by |
| 543 |
// appending the newly-allocated space to tail_. |
| 544 |
unused_ = allocLength; |
| 545 |
tail_->length += allocLength; |
| 546 |
} else { |
| 547 |
// Remove the size of the header from the allocated length. |
| 548 |
size_t availableSpace = allocLength - sizeof(Chunk); |
| 549 |
last->next = nullptr; |
| 550 |
last->length = availableSpace; |
| 551 |
|
| 552 |
unused_ = availableSpace; |
| 553 |
if (!head_) { |
| 554 |
head_ = last; |
| 555 |
} else { |
| 556 |
tail_->next = last; |
| 557 |
} |
| 558 |
|
| 559 |
tail_ = last; |
| 560 |
} |
| 561 |
|
| 562 |
PodCopy(tail_->end() - unused_, s, overflow); |
| 563 |
|
| 564 |
MOZ_ASSERT(unused_ >= overflow); |
| 565 |
unused_ -= overflow; |
| 566 |
} |
| 567 |
|
| 568 |
MOZ_ASSERT(len <= INT_MAX); |
| 569 |
} |
| 570 |
|
| 571 |
bool JSONEscape::isSafeChar(char16_t c) { |
| 572 |
return js::IsAsciiPrintable(c) && c != '"' && c != '\\'; |
| 573 |
} |
| 574 |
|
| 575 |
void JSONEscape::convertInto(GenericPrinter& out, char16_t c) { |
| 576 |
const char* escape = nullptr; |
| 577 |
if (!(c >> 8) && c != 0 && |
| 578 |
(escape = strchr(JSONEscapeMap, int(c))) != nullptr) { |
| 579 |
out.printf("\\%c", escape[1]); |
| 580 |
} else { |
| 581 |
out.printf("\\u%04X", c); |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
bool StringEscape::isSafeChar(char16_t c) { |
| 586 |
return js::IsAsciiPrintable(c) && c != quote && c != '\\'; |
| 587 |
} |
| 588 |
|
| 589 |
void StringEscape::convertInto(GenericPrinter& out, char16_t c) { |
| 590 |
const char* escape = nullptr; |
| 591 |
if (!(c >> 8) && c != 0 && |
| 592 |
(escape = strchr(js_EscapeMap, int(c))) != nullptr) { |
| 593 |
out.printf("\\%c", escape[1]); |
| 594 |
} else { |
| 595 |
// Use \x only if the high byte is 0 and we're in a quoted string, because |
| 596 |
// ECMA-262 allows only \u, not \x, in Unicode identifiers (see bug 621814). |
| 597 |
out.printf(!(c >> 8) ? "\\x%02X" : "\\u%04X", c); |
| 598 |
} |
| 599 |
} |
| 600 |
|
| 601 |
bool WATStringEscape::isSafeChar(char16_t c) { |
| 602 |
return js::IsAsciiPrintable(c) && c != '"' && c != '\\'; |
| 603 |
} |
| 604 |
|
| 605 |
void WATStringEscape::convertInto(GenericPrinter& out, char16_t c) { |
| 606 |
const char* escape = nullptr; |
| 607 |
if (!(c >> 8) && c != 0 && |
| 608 |
(escape = strchr(WATEscapeMap, int(c))) != nullptr) { |
| 609 |
out.printf("\\%c", escape[1]); |
| 610 |
} else { |
| 611 |
out.printf("\\%02X", c); |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
void StructuredPrinter::pushScope() { |
| 616 |
if (hadOutOfMemory()) { |
| 617 |
return; |
| 618 |
} |
| 619 |
|
| 620 |
bool ok = scopes_.append((ScopeInfo){ |
| 621 |
.startPos = uint32_t(buffer_.length()), |
| 622 |
.indent = scopeDepth() + 1, |
| 623 |
}); |
| 624 |
if (!ok) { |
| 625 |
setPendingOutOfMemory(); |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
void StructuredPrinter::popScope() { |
| 630 |
// If we previously ran out of memory, we may have failed to push a scope, and |
| 631 |
// this logic may fail. |
| 632 |
if (hadOutOfMemory()) { |
| 633 |
return; |
| 634 |
} |
| 635 |
|
| 636 |
// If the scope remained collapsed, flag all its breaks as collapsed. |
| 637 |
if (!isExpanded()) { |
| 638 |
const ScopeInfo& scope = scopes_.back(); |
| 639 |
for (Break& brk : breaks_) { |
| 640 |
if (scope.startPos <= brk.bufferPos) { |
| 641 |
brk.isCollapsed = true; |
| 642 |
} |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
scopes_.popBack(); |
| 647 |
if (scopeDepth() < expandedDepth_) { |
| 648 |
expandedDepth_ = scopeDepth(); |
| 649 |
} |
| 650 |
|
| 651 |
// If we are back to a depth where we are printing expanded, flush the buffer |
| 652 |
// to get back into our expected expanded state. |
| 653 |
if (isExpanded()) { |
| 654 |
flush(); |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
void StructuredPrinter::flush() { |
| 659 |
uint32_t cursor = 0; |
| 660 |
|
| 661 |
// Output any initial breaks. |
| 662 |
while (!breaks_.empty() && breaks_[0].bufferPos == 0) { |
| 663 |
putBreak(breaks_[0]); |
| 664 |
breaks_.erase(&breaks_[0]); |
| 665 |
} |
| 666 |
|
| 667 |
// Output all chunks from the buffer, split by scopes and breaks. |
| 668 |
while (cursor < buffer_.length()) { |
| 669 |
int indent = 0; |
| 670 |
mozilla::Maybe<const ScopeInfo&> nextScope; |
| 671 |
for (const ScopeInfo& scope : scopes_) { |
| 672 |
if (cursor < scope.startPos) { |
| 673 |
nextScope.emplace(scope); |
| 674 |
break; |
| 675 |
} |
| 676 |
indent = scope.indent; |
| 677 |
} |
| 678 |
|
| 679 |
// Find the next break(s) or start of the next scope. |
| 680 |
size_t len = buffer_.length() - cursor; |
| 681 |
mozilla::Maybe<size_t> nextBreaksIndex; |
| 682 |
size_t numBreaks = 0; |
| 683 |
for (size_t i = 0; i < breaks_.length(); i++) { |
| 684 |
const Break& brk = breaks_[i]; |
| 685 |
if (nextScope.isSome() && nextScope->startPos < brk.bufferPos) { |
| 686 |
len = nextScope->startPos - cursor; |
| 687 |
break; |
| 688 |
} |
| 689 |
if (cursor < brk.bufferPos) { |
| 690 |
len = brk.bufferPos - cursor; |
| 691 |
nextBreaksIndex.emplace(i); |
| 692 |
// There can be more than one break at the same cursor position; |
| 693 |
// grab them all. |
| 694 |
for (size_t j = i; j < breaks_.length(); j++) { |
| 695 |
if (breaks_[i].bufferPos == breaks_[j].bufferPos) { |
| 696 |
numBreaks += 1; |
| 697 |
} |
| 698 |
} |
| 699 |
break; |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
putWithMaybeIndent(&buffer_[cursor], len, indent); |
| 704 |
cursor += len; |
| 705 |
|
| 706 |
if (nextBreaksIndex.isSome()) { |
| 707 |
for (size_t i = 0; i < numBreaks; i++) { |
| 708 |
putBreak(breaks_[nextBreaksIndex.value() + i]); |
| 709 |
} |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
// Clear the buffer, clear all breaks, and reset scope positions. |
| 714 |
buffer_.clear(); |
| 715 |
breaks_.clear(); |
| 716 |
for (ScopeInfo& scope : scopes_) { |
| 717 |
scope.startPos = 0; |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
void StructuredPrinter::brk(const char* whenCollapsed, |
| 722 |
const char* whenExpanded) { |
| 723 |
Break b = (Break){ |
| 724 |
.bufferPos = uint32_t(buffer_.length()), |
| 725 |
.collapsed = whenCollapsed, |
| 726 |
.expanded = whenExpanded, |
| 727 |
}; |
| 728 |
if (isExpanded()) { |
| 729 |
putBreak(b); |
| 730 |
} else { |
| 731 |
bool ok = breaks_.append(b); |
| 732 |
if (!ok) { |
| 733 |
setPendingOutOfMemory(); |
| 734 |
} |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
void StructuredPrinter::expand() { |
| 739 |
expandedDepth_ = scopeDepth(); |
| 740 |
flush(); |
| 741 |
} |
| 742 |
|
| 743 |
bool StructuredPrinter::isExpanded() { return expandedDepth_ == scopeDepth(); } |
| 744 |
|
| 745 |
void StructuredPrinter::putIndent(int level) { |
| 746 |
// Allocate a static buffer of 16 spaces (plus null terminator) and use that |
| 747 |
// in batches for the total number of spaces we need to put. |
| 748 |
static const char spaceBuffer[17] = " "; |
| 749 |
|
| 750 |
if (level < 0) { |
| 751 |
level = scopeDepth(); |
| 752 |
} |
| 753 |
size_t remainingSpaces = level * indentAmount_; |
| 754 |
while (remainingSpaces > 16) { |
| 755 |
out_.put(spaceBuffer, 16); |
| 756 |
remainingSpaces -= 16; |
| 757 |
} |
| 758 |
if (remainingSpaces) { |
| 759 |
out_.put(spaceBuffer, remainingSpaces); |
| 760 |
} |
| 761 |
} |
| 762 |
|
| 763 |
void StructuredPrinter::putBreak(const Break& brk) { |
| 764 |
const char* s = brk.isCollapsed ? brk.collapsed : brk.expanded; |
| 765 |
size_t len = strlen(s); |
| 766 |
if (len > 0) { |
| 767 |
out_.put(s, len); |
| 768 |
pendingIndent_ = s[len - 1] == '\n'; |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
void StructuredPrinter::putWithMaybeIndent(const char* s, size_t len, |
| 773 |
int level) { |
| 774 |
if (len == 0) { |
| 775 |
return; |
| 776 |
} |
| 777 |
if (pendingIndent_) { |
| 778 |
putIndent(level); |
| 779 |
pendingIndent_ = false; |
| 780 |
} |
| 781 |
out_.put(s, len); |
| 782 |
} |
| 783 |
|
| 784 |
void StructuredPrinter::put(const char* s, size_t len) { |
| 785 |
const char* current = s; |
| 786 |
|
| 787 |
// Split the text into lines and output each with the appropriate indent |
| 788 |
while (const char* nextLineEnd = (const char*)memchr(current, '\n', len)) { |
| 789 |
// Newlines mean we must expand. |
| 790 |
expand(); |
| 791 |
|
| 792 |
// For the rest of this loop we can assume that we are expanded and buffer |
| 793 |
// nothing. |
| 794 |
|
| 795 |
// Put this line (including the newline) |
| 796 |
size_t lineWithNewLineSize = nextLineEnd - current + 1; |
| 797 |
putWithMaybeIndent(current, lineWithNewLineSize); |
| 798 |
|
| 799 |
// The next put should have an indent added |
| 800 |
pendingIndent_ = true; |
| 801 |
|
| 802 |
// Advance the cursor |
| 803 |
current += lineWithNewLineSize; |
| 804 |
len -= lineWithNewLineSize; |
| 805 |
} |
| 806 |
|
| 807 |
// The rest of the text is newline-free. We buffer it if we are collapsed, and |
| 808 |
// output it directly if expanded. |
| 809 |
if (isExpanded()) { |
| 810 |
putWithMaybeIndent(current, len); |
| 811 |
} else { |
| 812 |
if (!buffer_.append(current, len)) { |
| 813 |
setPendingOutOfMemory(); |
| 814 |
} |
| 815 |
} |
| 816 |
} |
| 817 |
|
| 818 |
} // namespace js |