{"record":{"id":"ff95de45f8059d65","repo":"java-native-access/jna","slug":"cfstring-maximum-number-of-bytes-exceeds-long-max","errorCode":null,"errorMessage":"CFString maximum number of bytes exceeds LONG_MAX.","messagePattern":"CFString maximum number of bytes exceeds LONG_MAX\\.","errorType":"exception","errorClass":"StringIndexOutOfBoundsException","httpStatus":null,"severity":"error","filePath":"contrib/platform/src/com/sun/jna/platform/mac/CoreFoundation.java","lineNumber":580,"sourceCode":"        /**\n         * Convert a reference to a Core Foundations String into its\n         * {@link java.lang.String}\n         *\n         * @return The corresponding {@link java.lang.String}, or null if the conversion\n         *         failed.\n         */\n        public String stringValue() {\n            // Get number of characters (UTF-16 code pairs)\n            // Code points > 0xffff will have 2 characters per Unicode character\n            CFIndex length = INSTANCE.CFStringGetLength(this);\n            if (length.longValue() == 0) {\n                return \"\";\n            }\n            // Calculate maximum possible size in UTF8 bytes\n            // This will be 3 x length\n            CFIndex maxSize = INSTANCE.CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);\n            if (maxSize.intValue() == kCFNotFound) {\n                throw new StringIndexOutOfBoundsException(\"CFString maximum number of bytes exceeds LONG_MAX.\");\n            }\n            // Increment size by 1 for a null byte\n            maxSize.setValue(maxSize.longValue() + 1);\n            Memory buf = new Memory(maxSize.longValue());\n            if (0 != INSTANCE.CFStringGetCString(this, buf, maxSize, kCFStringEncodingUTF8)) {\n                return buf.getString(0, \"UTF8\");\n            }\n            throw new IllegalArgumentException(\"CFString conversion fails or the provided buffer is too small.\");\n        }\n    }\n\n    /**\n     * A wrapper for the {@link NativeLong} type, used for {@link CFNumberRef}\n     * types, {@link CFStringRef} lengths, and {@link CFArrayRef} sizes and indices.\n     */\n    class CFIndex extends NativeLong {\n        private static final long serialVersionUID = 1L;\n","sourceCodeStart":562,"sourceCodeEnd":598,"githubUrl":"https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/contrib/platform/src/com/sun/jna/platform/mac/CoreFoundation.java#L562-L598","documentation":"stringValue() computes the UTF-8 buffer size via CFStringGetMaximumSizeForEncoding; if the native function reports kCFNotFound (-1), the required size exceeds LONG_MAX and the method throws StringIndexOutOfBoundsException. This effectively only occurs with absurdly large or corrupted CFString lengths.","triggerScenarios":"Calling CFStringRef.stringValue() (directly or via getStringProperty/getLocaleDateTimeFormat etc.) on a CFString whose reported length, multiplied for UTF-8 encoding, overflows CFIndex, or on a corrupt/forged CFString pointer.","commonSituations":"Wrapping garbage pointers as CFStringRef so CFStringGetLength returns nonsense; OS API changes returning malformed strings; strings longer than CFIndex can represent (practically never for legitimate data).","solutions":["Verify the pointer is a valid CFString (isTypeID(STRING_TYPE_ID)) before calling stringValue(); corrupt pointers are the usual cause.","Wrap stringValue() in try-catch for StringIndexOutOfBoundsException and fall back to an alternate conversion or empty string.","Re-acquire the string from the source API instead of reusing a possibly-released CFString reference.","If legitimate huge strings are expected, chunk them at the source rather than converting in one call."],"exampleFix":"// before\nString s = cfStringRef.stringValue(); // may throw StringIndexOutOfBoundsException\n// after\nString s;\ntry {\n    s = cfStringRef.stringValue();\n} catch (StringIndexOutOfBoundsException e) {\n    s = \"\"; // invalid/oversized CFString, fall back\n}","handlingStrategy":"try-catch","validationCode":"CFTypeRef ref = new CFTypeRef(ptr);\nif (!ref.isTypeID(CoreFoundation.STRING_TYPE_ID)) return null; // not a valid CFString\nif (ptr == null) return null;","typeGuard":"boolean isUsableCFString(Pointer p) {\n    return p != null && new CFTypeRef(p).isTypeID(CoreFoundation.STRING_TYPE_ID);\n}","tryCatchPattern":"try {\n    String s = cfStringRef.stringValue();\n} catch (StringIndexOutOfBoundsException e) {\n    String s = \"\"; // corrupted or oversized CFString\n}","preventionTips":["Validate the pointer is a genuine CFString before calling stringValue()","Do not reuse CFString references after CFRelease — released memory can report corrupt lengths","Treat StringIndexOutOfBoundsException here as a corruption signal, not a size problem","Keep references alive (retain) while converting strings from Get-function results"],"tags":["macos","corefoundation","string","overflow"],"backgroundTag":"value-out-of-range","analyzedSha":"d036ad9781adad4b66693e8fa7098e4ac665e0a3","analyzedAt":"2026-09-12T06:50:59.239Z","contentChangedAt":"2026-09-12T06:50:59.239Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}