summaryrefslogtreecommitdiff
path: root/gjs/jsapi-util-string.cpp
blob: fcef285f7875d29adab1bae574b35d18c1bea70e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2008 litl, LLC

#include <config.h>

#include <stdint.h>
#include <string.h>     // for size_t, strlen
#include <sys/types.h>  // for ssize_t

#include <algorithm>  // for copy
#include <iomanip>    // for operator<<, setfill, setw
#include <sstream>    // for operator<<, basic_ostream, ostring...
#include <string>     // for allocator, char_traits

#include <glib.h>

#include <js/BigInt.h>
#include <js/CharacterEncoding.h>
#include <js/Class.h>
#include <js/ErrorReport.h>
#include <js/GCAPI.h>  // for AutoCheckCannotGC
#include <js/Id.h>
#include <js/Object.h>  // for GetClass
#include <js/Promise.h>
#include <js/RootingAPI.h>
#include <js/String.h>
#include <js/Symbol.h>
#include <js/TypeDecls.h>
#include <js/Utility.h>  // for UniqueChars
#include <js/Value.h>
#include <jsapi.h>        // for JS_GetFunctionDisplayId
#include <jsfriendapi.h>  // for IdToValue, IsFunctionObject, ...
#include <mozilla/CheckedInt.h>
#include <mozilla/Span.h>

#include "gjs/jsapi-util.h"
#include "gjs/macros.h"
#include "util/misc.h"  // for _gjs_memdup2

class JSLinearString;

GjsAutoChar gjs_hyphen_to_underscore(const char* str) {
    char *s = g_strdup(str);
    char *retval = s;
    while (*(s++) != '\0') {
        if (*s == '-')
            *s = '_';
    }
    return retval;
}

GjsAutoChar gjs_hyphen_to_camel(const char* str) {
    GjsAutoChar retval = static_cast<char*>(g_malloc(strlen(str) + 1));
    const char* input_iter = str;
    char* output_iter = retval.get();
    bool uppercase_next = false;
    while (*input_iter != '\0') {
        if (*input_iter == '-') {
            uppercase_next = true;
        } else if (uppercase_next) {
            *output_iter++ = g_ascii_toupper(*input_iter);
            uppercase_next = false;
        } else {
            *output_iter++ = *input_iter;
        }
        input_iter++;
    }
    *output_iter = '\0';
    return retval;
}

/**
 * gjs_string_to_utf8:
 * @cx: JSContext
 * @value: a JS::Value containing a string
 *
 * Converts the JSString in @value to UTF-8 and puts it in @utf8_string_p.
 *
 * This function is a convenience wrapper around JS_EncodeStringToUTF8() that
 * typechecks the JS::Value and throws an exception if it's the wrong type.
 * Don't use this function if you already have a JS::RootedString, or if you
 * know the value already holds a string; use JS_EncodeStringToUTF8() instead.
 *
 * Returns: Unique UTF8 chars, empty on exception throw.
 */
JS::UniqueChars gjs_string_to_utf8(JSContext* cx, const JS::Value value) {
    if (!value.isString()) {
        gjs_throw(cx, "Value is not a string, cannot convert to UTF-8");
        return nullptr;
    }

    JS::RootedString str(cx, value.toString());
    return JS_EncodeStringToUTF8(cx, str);
}

/**
 * gjs_string_to_utf8_n:
 * @param cx: the current #JSContext
 * @param str: a handle to a JSString
 * @param output a pointer to a JS::UniqueChars
 * @param output_len a pointer for the length of output
 *
 * @brief Converts a JSString to UTF-8 and puts the char array in #output and
 * its length in #output_len.
 *
 * This function handles the boilerblate for unpacking a JSString, determining its
 * length, and returning the appropriate JS::UniqueChars. This function should generally
 * be preferred over using JS::DeflateStringToUTF8Buffer directly as it correctly
 * handles allocation in a JS_Free compatible manner.
 */
bool gjs_string_to_utf8_n(JSContext* cx, JS::HandleString str, JS::UniqueChars* output,
                          size_t* output_len) {
    JSLinearString* linear = JS_EnsureLinearString(cx, str);
    if (!linear)
        return false;

    size_t length = JS::GetDeflatedUTF8StringLength(linear);
    char* bytes = js_pod_arena_malloc<char>(js::StringBufferArena, length + 1);
    if (!bytes)
        return false;

    // Append a zero-terminator to the string.
    bytes[length] = '\0';

    size_t deflated_length [[maybe_unused]] =
        JS::DeflateStringToUTF8Buffer(linear, mozilla::Span(bytes, length));
    g_assert(deflated_length == length);

    *output_len = length;
    *output = JS::UniqueChars(bytes);
    return true;
}

/**
 * gjs_lossy_string_from_utf8:
 *
 * @brief Converts an array of UTF-8 characters to a JS string.
 * Instead of throwing, any invalid characters will be converted
 * to the UTF-8 invalid character fallback.
 *
 * @param cx the current #JSContext
 * @param utf8_string an array of UTF-8 characters
 * @param value_p a value to store the resulting string in
 */
JSString* gjs_lossy_string_from_utf8(JSContext* cx, const char* utf8_string) {
    JS::ConstUTF8CharsZ chars(utf8_string, strlen(utf8_string));
    size_t outlen;
    JS::UniqueTwoByteChars twobyte_chars(
        JS::LossyUTF8CharsToNewTwoByteCharsZ(cx, chars, &outlen,
                                             js::MallocArena)
            .get());
    if (!twobyte_chars)
        return nullptr;

    return JS_NewUCStringCopyN(cx, twobyte_chars.get(), outlen);
}

/**
 * gjs_lossy_string_from_utf8_n:
 *
 * @brief Provides the same conversion behavior as gjs_lossy_string_from_utf8
 * with a fixed length. See gjs_lossy_string_from_utf8()
 */
JSString* gjs_lossy_string_from_utf8_n(JSContext* cx, const char* utf8_string,
                                       size_t len) {
    JS::UTF8Chars chars(utf8_string, len);
    size_t outlen;
    JS::UniqueTwoByteChars twobyte_chars(
        JS::LossyUTF8CharsToNewTwoByteCharsZ(cx, chars, &outlen,
                                             js::MallocArena)
            .get());
    if (!twobyte_chars)
        return nullptr;

    return JS_NewUCStringCopyN(cx, twobyte_chars.get(), outlen);
}

bool
gjs_string_from_utf8(JSContext             *context,
                     const char            *utf8_string,
                     JS::MutableHandleValue value_p)
{
    JS::ConstUTF8CharsZ chars(utf8_string, strlen(utf8_string));
    JS::RootedString str(context, JS_NewStringCopyUTF8Z(context, chars));
    if (!str)
        return false;

    value_p.setString(str);
    return true;
}

bool
gjs_string_from_utf8_n(JSContext             *cx,
                       const char            *utf8_chars,
                       size_t                 len,
                       JS::MutableHandleValue out)
{
    JS::UTF8Chars chars(utf8_chars, len);
    JS::RootedString str(cx, JS_NewStringCopyUTF8N(cx, chars));
    if (str)
        out.setString(str);

    return !!str;
}

bool
gjs_string_to_filename(JSContext      *context,
                       const JS::Value filename_val,
                       GjsAutoChar    *filename_string)
{
    GError *error;

    /* gjs_string_to_filename verifies that filename_val is a string */

    JS::UniqueChars tmp = gjs_string_to_utf8(context, filename_val);
    if (!tmp)
        return false;

    error = NULL;
    *filename_string =
        g_filename_from_utf8(tmp.get(), -1, nullptr, nullptr, &error);
    if (!*filename_string)
        return gjs_throw_gerror_message(context, error);

    return true;
}

bool
gjs_string_from_filename(JSContext             *context,
                         const char            *filename_string,
                         ssize_t                n_bytes,
                         JS::MutableHandleValue value_p)
{
    gsize written;
    GError *error;

    error = NULL;
    GjsAutoChar utf8_string = g_filename_to_utf8(filename_string, n_bytes,
                                                 nullptr, &written, &error);
    if (error) {
        gjs_throw(context,
                  "Could not convert UTF-8 string '%s' to a filename: '%s'",
                  filename_string,
                  error->message);
        g_error_free(error);
        return false;
    }

    return gjs_string_from_utf8_n(context, utf8_string, written, value_p);
}

/* Converts a JSString's array of Latin-1 chars to an array of a wider integer
 * type, by what the compiler believes is the most efficient method possible */
template <typename T>
GJS_JSAPI_RETURN_CONVENTION static bool from_latin1(JSContext* cx,
                                                    JSString* str, T** data_p,
                                                    size_t* len_p) {
    /* No garbage collection should be triggered while we are using the string's
     * chars. Crash if that happens. */
    JS::AutoCheckCannotGC nogc;

    const JS::Latin1Char *js_data =
        JS_GetLatin1StringCharsAndLength(cx, nogc, str, len_p);
    if (js_data == NULL)
        return false;

    /* Unicode codepoints 0x00-0xFF are the same as Latin-1
     * codepoints, so we can preserve the string length and simply
     * copy the codepoints to an array of different-sized ints */

    *data_p = g_new(T, *len_p);

    /* This will probably use a loop, unfortunately */
    std::copy(js_data, js_data + *len_p, *data_p);
    return true;
}

/**
 * gjs_string_get_char16_data:
 * @context: js context
 * @str: a rooted JSString
 * @data_p: address to return allocated data buffer
 * @len_p: address to return length of data (number of 16-bit characters)
 *
 * Get the binary data (as a sequence of 16-bit characters) in @str.
 *
 * Returns: false if exception thrown
 **/
bool
gjs_string_get_char16_data(JSContext       *context,
                           JS::HandleString str,
                           char16_t       **data_p,
                           size_t          *len_p)
{
    if (JS::StringHasLatin1Chars(str))
        return from_latin1(context, str, data_p, len_p);

    /* From this point on, crash if a GC is triggered while we are using
     * the string's chars */
    JS::AutoCheckCannotGC nogc;

    const char16_t *js_data =
        JS_GetTwoByteStringCharsAndLength(context, nogc, str, len_p);

    if (js_data == NULL)
        return false;

    mozilla::CheckedInt<size_t> len_bytes =
        mozilla::CheckedInt<size_t>(*len_p) * sizeof(*js_data);
    if (!len_bytes.isValid()) {
        JS_ReportOutOfMemory(context);  // cannot call gjs_throw, it may GC
        return false;
    }

    *data_p = static_cast<char16_t*>(_gjs_memdup2(js_data, len_bytes.value()));

    return true;
}

/**
 * gjs_string_to_ucs4:
 * @cx: a #JSContext
 * @str: rooted JSString
 * @ucs4_string_p: return location for a #gunichar array
 * @len_p: return location for @ucs4_string_p length
 *
 * Returns: true on success, false otherwise in which case a JS error is thrown
 */
bool
gjs_string_to_ucs4(JSContext       *cx,
                   JS::HandleString str,
                   gunichar       **ucs4_string_p,
                   size_t          *len_p)
{
    if (ucs4_string_p == NULL)
        return true;

    size_t len;
    GError *error = NULL;

    if (JS::StringHasLatin1Chars(str))
        return from_latin1(cx, str, ucs4_string_p, len_p);

    /* From this point on, crash if a GC is triggered while we are using
     * the string's chars */
    JS::AutoCheckCannotGC nogc;

    const char16_t *utf16 =
        JS_GetTwoByteStringCharsAndLength(cx, nogc, str, &len);

    if (utf16 == NULL) {
        gjs_throw(cx, "Failed to get UTF-16 string data");
        return false;
    }

    if (ucs4_string_p != NULL) {
        long length;
        *ucs4_string_p = g_utf16_to_ucs4(reinterpret_cast<const gunichar2 *>(utf16),
                                         len, NULL, &length, &error);
        if (*ucs4_string_p == NULL) {
            gjs_throw(cx, "Failed to convert UTF-16 string to UCS-4: %s",
                      error->message);
            g_clear_error(&error);
            return false;
        }
        if (len_p != NULL)
            *len_p = (size_t) length;
    }

    return true;
}

/**
 * gjs_string_from_ucs4:
 * @cx: a #JSContext
 * @ucs4_string: string of #gunichar
 * @n_chars: number of characters in @ucs4_string or -1 for zero-terminated
 * @value_p: JS::Value that will be filled with a string
 *
 * Returns: true on success, false otherwise in which case a JS error is thrown
 */
bool
gjs_string_from_ucs4(JSContext             *cx,
                     const gunichar        *ucs4_string,
                     ssize_t                n_chars,
                     JS::MutableHandleValue value_p)
{
    // a null array pointer takes precedence over whatever `n_chars` says
    if (!ucs4_string) {
        value_p.setString(JS_GetEmptyString(cx));
        return true;
    }

    long u16_string_length;
    GError *error = NULL;

    gunichar2* u16_string = g_ucs4_to_utf16(ucs4_string, n_chars, nullptr,
                                            &u16_string_length, &error);
    if (!u16_string) {
        gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16: %s",
                  error->message);
        g_error_free(error);
        return false;
    }

    // Sadly, must copy, because js::UniquePtr forces that chars passed to
    // JS_NewUCString() must have been allocated by the JS engine.
    JS::RootedString str(
        cx, JS_NewUCStringCopyN(cx, reinterpret_cast<char16_t*>(u16_string),
                                u16_string_length));

    g_free(u16_string);

    if (!str) {
        gjs_throw(cx, "Failed to convert UCS-4 string to UTF-16");
        return false;
    }

    value_p.setString(str);
    return true;
}

/**
 * gjs_get_string_id:
 * @cx: a #JSContext
 * @id: a jsid that is an object hash key (could be an int or string)
 * @name_p place to store ASCII string version of key
 *
 * If the id is not a string ID, return true and set *name_p to nullptr.
 * Otherwise, return true and fill in *name_p with ASCII name of id.
 *
 * Returns: false on error, otherwise true
 **/
bool gjs_get_string_id(JSContext* cx, jsid id, JS::UniqueChars* name_p) {
    if (!id.isString()) {
        name_p->reset();
        return true;
    }

    JSLinearString* lstr = id.toLinearString();
    JS::RootedString s(cx, JS_FORGET_STRING_LINEARNESS(lstr));
    *name_p = JS_EncodeStringToUTF8(cx, s);
    return !!*name_p;
}

/**
 * gjs_unichar_from_string:
 * @string: A string
 * @result: (out): A unicode character
 *
 * If successful, @result is assigned the Unicode codepoint
 * corresponding to the first full character in @string.  This
 * function handles characters outside the BMP.
 *
 * If @string is empty, @result will be 0.  An exception will
 * be thrown if @string can not be represented as UTF-8.
 */
bool
gjs_unichar_from_string (JSContext *context,
                         JS::Value  value,
                         gunichar  *result)
{
    JS::UniqueChars utf8_str = gjs_string_to_utf8(context, value);
    if (utf8_str) {
        *result = g_utf8_get_char(utf8_str.get());
        return true;
    }
    return false;
}

jsid
gjs_intern_string_to_id(JSContext  *cx,
                        const char *string)
{
    JS::RootedString str(cx, JS_AtomizeAndPinString(cx, string));
    if (!str)
        return JS::PropertyKey::Void();
    return JS::PropertyKey::fromPinnedString(str);
}

std::string gjs_debug_bigint(JS::BigInt* bi) {
    // technically this prints the value % INT64_MAX, cast into an int64_t if
    // the value is negative, otherwise cast into uint64_t
    std::ostringstream out;
    if (JS::BigIntIsNegative(bi))
        out << JS::ToBigInt64(bi);
    else
        out << JS::ToBigUint64(bi);
    out << "n (modulo 2^64)";
    return out.str();
}

enum Quotes {
    DoubleQuotes,
    NoQuotes,
};

[[nodiscard]] static std::string gjs_debug_linear_string(JSLinearString* str,
                                                         Quotes quotes) {
    size_t len = JS::GetLinearStringLength(str);

    std::ostringstream out;
    if (quotes == DoubleQuotes)
        out << '"';

    JS::AutoCheckCannotGC nogc;
    if (JS::LinearStringHasLatin1Chars(str)) {
        const JS::Latin1Char* chars = JS::GetLatin1LinearStringChars(nogc, str);
        out << std::string(reinterpret_cast<const char*>(chars), len);
        if (quotes == DoubleQuotes)
            out << '"';
        return out.str();
    }

    const char16_t* chars = JS::GetTwoByteLinearStringChars(nogc, str);
    for (size_t ix = 0; ix < len; ix++) {
        char16_t c = chars[ix];
        if (c == '\n')
            out << "\\n";
        else if (c == '\t')
            out << "\\t";
        else if (c >= 32 && c < 127)
            out << c;
        else if (c <= 255)
            out << "\\x" << std::setfill('0') << std::setw(2) << unsigned(c);
        else
            out << "\\x" << std::setfill('0') << std::setw(4) << unsigned(c);
    }
    if (quotes == DoubleQuotes)
        out << '"';
    return out.str();
}

std::string
gjs_debug_string(JSString *str)
{
    if (!str)
        return "<null string>";
    if (!JS_StringIsLinear(str)) {
        std::ostringstream out("<non-flat string of length ",
                               std::ios_base::ate);
        out << JS_GetStringLength(str) << '>';
        return out.str();
    }
    return gjs_debug_linear_string(JS_ASSERT_STRING_IS_LINEAR(str),
                                   DoubleQuotes);
}

std::string
gjs_debug_symbol(JS::Symbol * const sym)
{
    if (!sym)
        return "<null symbol>";

    /* This is OK because JS::GetSymbolCode() and JS::GetSymbolDescription()
     * can't cause a garbage collection */
    JS::HandleSymbol handle = JS::HandleSymbol::fromMarkedLocation(&sym);
    JS::SymbolCode code = JS::GetSymbolCode(handle);
    JSString *descr = JS::GetSymbolDescription(handle);

    if (size_t(code) < JS::WellKnownSymbolLimit)
        return gjs_debug_string(descr);

    std::ostringstream out;
    if (code == JS::SymbolCode::InSymbolRegistry) {
        out << "Symbol.for(";
        if (descr)
            out << gjs_debug_string(descr);
        else
            out << "undefined";
        out << ")";
        return out.str();
    }
    if (code == JS::SymbolCode::UniqueSymbol) {
        if (descr)
            out << "Symbol(" << gjs_debug_string(descr) << ")";
        else
            out << "<Symbol at " << sym << ">";
        return out.str();
    }

    out << "<unexpected symbol code " << uint32_t(code) << ">";
    return out.str();
}

std::string
gjs_debug_object(JSObject * const obj)
{
    if (!obj)
        return "<null object>";

    std::ostringstream out;

    if (js::IsFunctionObject(obj)) {
        JSFunction* fun = JS_GetObjectFunction(obj);
        JSString* display_name = JS_GetFunctionDisplayId(fun);
        if (display_name && JS_GetStringLength(display_name))
            out << "<function " << gjs_debug_string(display_name);
        else
            out << "<anonymous function";
        out << " at " << fun << '>';
        return out.str();
    }

    // This is OK because the promise methods can't cause a garbage collection
    JS::HandleObject handle = JS::HandleObject::fromMarkedLocation(&obj);
    if (JS::IsPromiseObject(handle)) {
        out << '<';
        JS::PromiseState state = JS::GetPromiseState(handle);
        if (state == JS::PromiseState::Pending)
            out << "pending ";
        out << "promise " << JS::GetPromiseID(handle) << " at " << obj;
        if (state != JS::PromiseState::Pending) {
            out << ' ';
            out << (state == JS::PromiseState::Rejected ? "rejected"
                                                        : "resolved");
            out << " with " << gjs_debug_value(JS::GetPromiseResult(handle));
        }
        out << '>';
        return out.str();
    }

    const JSClass* clasp = JS::GetClass(obj);
    out << "<object " << clasp->name << " at " << obj <<  '>';
    return out.str();
}

std::string
gjs_debug_value(JS::Value v)
{
    if (v.isNull())
        return "null";
    if (v.isUndefined())
        return "undefined";
    if (v.isInt32()) {
        std::ostringstream out;
        out << v.toInt32();
        return out.str();
    }
    if (v.isDouble()) {
        std::ostringstream out;
        out << v.toDouble();
        return out.str();
    }
    if (v.isBigInt())
        return gjs_debug_bigint(v.toBigInt());
    if (v.isString())
        return gjs_debug_string(v.toString());
    if (v.isSymbol())
        return gjs_debug_symbol(v.toSymbol());
    if (v.isObject())
        return gjs_debug_object(&v.toObject());
    if (v.isBoolean())
        return (v.toBoolean() ? "true" : "false");
    if (v.isMagic())
        return "<magic>";
    return "unexpected value";
}

std::string
gjs_debug_id(jsid id)
{
    if (id.isString())
        return gjs_debug_linear_string(id.toLinearString(), NoQuotes);
    return gjs_debug_value(js::IdToValue(id));
}