{"record":{"id":"9ffd252d85defb76","repo":"karatelabs/karate","slug":"invalid-array-length-jsarrayprototype","errorCode":null,"errorMessage":"Invalid array length","messagePattern":"Invalid array length","errorType":"exception","errorClass":"JsErrorException","httpStatus":null,"severity":"error","filePath":"karate-js/src/main/java/io/karatelabs/js/JsArrayPrototype.java","lineNumber":422,"sourceCode":"        Number n = lenObj instanceof ObjectLike\n                ? Terms.toNumberCoerce(lenObj, ctx)\n                : Terms.objectToNumber(lenObj);\n        if (ctx != null && ctx.isError()) return 0;\n        double d = n == null ? Double.NaN : n.doubleValue();\n        if (Double.isNaN(d) || d <= 0) return 0;\n        if (d >= Integer.MAX_VALUE) return Integer.MAX_VALUE;\n        return (int) d;\n    }\n\n    /** {@link #lengthOf} clamps a huge claimed length to Integer.MAX_VALUE;\n     *  a result of that magnitude cannot be dense-allocated. The spec answer\n     *  is RangeError (ArrayCreate §10.4.2.2 throws above 2^32-1; the store\n     *  bound here is lower and documented in TEST262.md) — throwing it here\n     *  keeps a lying {@code {length: 2**32}} array-like from OOMing the JVM\n     *  through map / splice / toReversed / toSorted / toSpliced. */\n    private static int checkResultLength(int len) {\n        if (len == Integer.MAX_VALUE) {\n            throw JsErrorException.rangeError(\"Invalid array length\");\n        }\n        return len;\n    }\n\n    /** Spec §23.1.3.34 step 4 (unshift) / §23.1.3.31 (splice): a receiver\n     *  whose length plus the inserted count would exceed 2^53-1 throws\n     *  TypeError before any element is moved. Reads the raw double length —\n     *  {@link #lengthOf}'s int clamp cannot see these magnitudes. */\n    private static void checkLengthLimit(ObjectLike target, CoreContext ctx, int addCount) {\n        Object lenObj = target.getMember(\"length\", target, ctx);\n        if (lenObj == null || lenObj == Terms.UNDEFINED) return;\n        Number n = lenObj instanceof ObjectLike\n                ? Terms.toNumberCoerce(lenObj, ctx)\n                : Terms.objectToNumber(lenObj);\n        if (ctx != null && ctx.isError()) return;\n        double d = n == null ? Double.NaN : n.doubleValue();\n        if (d + addCount > 9007199254740991.0) { // 2^53 - 1\n            throw JsErrorException.typeError(\"Invalid array length\");","sourceCodeStart":404,"sourceCodeEnd":440,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-js/src/main/java/io/karatelabs/js/JsArrayPrototype.java#L404-L440","documentation":"This RangeError is thrown by Karate's JS engine when an array-like operation would produce a result length at or above the JVM-safe bound (spec ArrayCreate throws above 2^32-1; this store bound is lower and documented in TEST262.md). It exists so a lying {length: 2**32} array-like cannot OOM the JVM through map / splice / toReversed / toSorted / toSpliced.","triggerScenarios":"Calling len, removed, result, items, or the newLen path of array methods on a receiver whose length coerces to Integer.MAX_VALUE (2147483647), e.g. an object with {length: 4294967295} passed to Array.prototype.map.call, or a huge new length passed to splice/unshift.","commonSituations":"Hand-rolled array-like objects with inflated length fields; JSON payloads with spoofed length; ported JS that relies on V8's larger limits; fuzzing or hostile scripts evaluated in Karate's embedded JS.","solutions":["Fix the receiver's length value to a realistic array size","Ensure inputs to map/splice/toSorted etc. are real arrays, not array-likes with huge lengths","Wrap the call in try/catch and treat RangeError as invalid input","Validate length <= 2^32-2 before invoking array methods on array-likes"],"exampleFix":"// before\nvar fake = { length: 4294967295 };\nArray.prototype.map.call(fake, f);\n// after\nvar fake = { length: 4294967295 };\nif (fake.length > 2147483646) throw new Error('array-like too large');\nArray.prototype.map.call(fake, f);","handlingStrategy":"validation","validationCode":"if (typeof obj.length !== 'number' || obj.length < 0 || obj.length > 2147483646) throw new Error('array-like length out of safe range: ' + obj.length);","typeGuard":"function isSafeArrayLike(o) { return o != null && typeof o.length === 'number' && Number.isInteger(o.length) && o.length >= 0 && o.length <= 2147483646; }","tryCatchPattern":null,"preventionTips":["Never trust a length field from external JSON — clamp it before use","Prefer real arrays over hand-rolled array-likes","Fuzz-test array methods with extreme length values","Keep array-likes below Integer.MAX_VALUE - 1"],"tags":["javascript","array","range-error"],"backgroundTag":"value-out-of-range","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}