[gjs/gnome-40] byteArray: Fix crash with 0-length string



commit e2872de066638cb232c1084962eaab8daf744546
Author: Philip Chimento <philip chimento gmail com>
Date:   Sun May 23 15:37:35 2021 -0700

    byteArray: Fix crash with 0-length string
    
    Similar to the bug fixed in the previous commit, going through the
    non-UTF-8 path of ByteArray.fromString() with a zero-length string would
    crash. Create an empty Uint8Array here as well.

 gjs/byteArray.cpp                   | 10 ++++++++++
 installed-tests/js/testByteArray.js |  5 +++++
 2 files changed, 15 insertions(+)
---
diff --git a/gjs/byteArray.cpp b/gjs/byteArray.cpp
index e8e294ff..1635e902 100644
--- a/gjs/byteArray.cpp
+++ b/gjs/byteArray.cpp
@@ -296,6 +296,16 @@ from_string_func(JSContext *context,
         if (!encoded)
             return gjs_throw_gerror_message(context, error);  // frees GError
 
+        if (bytes_written == 0) {
+            g_free(encoded);
+            JS::RootedObject empty_array(context, JS_NewUint8Array(context, 0));
+            if (!empty_array || !define_legacy_tostring(context, empty_array))
+                return false;
+
+            argv.rval().setObject(*empty_array);
+            return true;
+        }
+
         array_buffer =
             JS::NewExternalArrayBuffer(context, bytes_written, encoded,
                                        gfree_arraybuffer_contents, nullptr);
diff --git a/installed-tests/js/testByteArray.js b/installed-tests/js/testByteArray.js
index bcae4183..4dd1ec91 100644
--- a/installed-tests/js/testByteArray.js
+++ b/installed-tests/js/testByteArray.js
@@ -73,6 +73,11 @@ describe('Byte array', function () {
         expect(ByteArray.fromGBytes(noBytes).length).toEqual(0);
     });
 
+    it('deals gracefully with a 0-length string', function () {
+        expect(ByteArray.fromString('').length).toEqual(0);
+        expect(ByteArray.fromString('', 'LATIN1').length).toEqual(0);
+    });
+
     it('deals gracefully with a non Uint8Array', function () {
         const a = [97, 98, 99, 100, 0];
         expect(() => ByteArray.toString(a)).toThrow();


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]