[gjs: 2/3] jsapi-util-string: Check for overflow when copying string chars




commit 407ca913b38dab95c5f0aaee4ff738c9ae8bd96a
Author: Philip Chimento <philip chimento gmail com>
Date:   Thu Mar 11 19:31:35 2021 -0800

    jsapi-util-string: Check for overflow when copying string chars
    
    A previously existing bug was that calculating the number of bytes to copy
    might overflow if the number of JS characters was not over the max of
    size_t but the number of bytes was. Check for this unlikely case (a string
    of 2.1 billion characters on 32-bit, and an astronomical number on 64-bit)
    and bail.
    
    Thanks to Bastien Nocera for the suggestion.

 gjs/jsapi-util-string.cpp | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
---
diff --git a/gjs/jsapi-util-string.cpp b/gjs/jsapi-util-string.cpp
index 9d7d0a61..e318b514 100644
--- a/gjs/jsapi-util-string.cpp
+++ b/gjs/jsapi-util-string.cpp
@@ -29,6 +29,7 @@
 #include <js/Value.h>
 #include <jsapi.h>        // for JSID_TO_FLAT_STRING, JS_GetTwoByte...
 #include <jsfriendapi.h>  // for FlatStringToLinearString, GetLatin...
+#include <mozilla/CheckedInt.h>
 
 #include "gjs/jsapi-util.h"
 #include "gjs/macros.h"
@@ -205,8 +206,14 @@ gjs_string_get_char16_data(JSContext       *context,
     if (js_data == NULL)
         return false;
 
-    *data_p = static_cast<char16_t*>(
-        _gjs_memdup2(js_data, sizeof(*js_data) * (*len_p)));
+    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;
 }


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