{"record":{"id":"deb9120824940c8d","repo":"java-native-access/jna","slug":"cfstring-conversion-fails-or-the-provided-buffer-is-too","errorCode":null,"errorMessage":"CFString conversion fails or the provided buffer is too small.","messagePattern":"CFString conversion fails or the provided buffer is too small\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"contrib/platform/src/com/sun/jna/platform/mac/CoreFoundation.java","lineNumber":588,"sourceCode":"            // 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\n        public CFIndex() {\n            super();\n        }\n\n        public CFIndex(long value) {\n            super(value);\n        }\n    }","sourceCodeStart":570,"sourceCodeEnd":606,"githubUrl":"https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/contrib/platform/src/com/sun/jna/platform/mac/CoreFoundation.java#L570-L606","documentation":"CFStringRef.stringValue() converts a CoreFoundation string to a Java String via CFStringGetCString into a UTF-8 buffer sized from CFStringGetMaximumCStringSize plus 1. If the conversion fails (invalid CFString, embedded nulls, or the buffer was somehow too small), CFStringGetCString returns 0 and this IllegalArgumentException is thrown.","triggerScenarios":"Calling stringValue() on a CFStringRef whose native pointer is invalid or whose content cannot be encoded to UTF-8 as a C string; callers include getStringProperty on CFDictionary values, window list descriptions, and locale date/time formats where a key holds a non-string value.","commonSituations":"Reading a CFDictionary property that does not actually contain a CFString (e.g. a CFNumber or CFBoolean cast as CFStringRef); corrupted or already-released CFString references from CoreGraphics/CoreFoundation APIs; macOS API changes returning unexpected types.","solutions":["Verify the dictionary value is actually a CFString before casting (check CFGetTypeID against CFStringGetTypeID())","Wrap stringValue() in try-catch for IllegalArgumentException and fall back to an empty/default string","Check that the CFStringRef pointer is non-null (ref.equals(Pointer.NULL) is false) before calling stringValue()"],"exampleFix":"// before\nString name = cfDictionaryRef.getStringProperty(key);\n// after\nString name;\ntry {\n    name = cfDictionaryRef.getStringProperty(key);\n} catch (IllegalArgumentException e) {\n    name = \"\"; // value was not a convertible CFString\n}","handlingStrategy":"try-catch","validationCode":"// check pointer validity first\nif (cfStringRef == null || cfStringRef.getPointer() == null || Pointer.NULL.equals(cfStringRef.getPointer())) {\n    throw new IllegalArgumentException(\"CFStringRef has no valid pointer\");\n}","typeGuard":"boolean isConvertible(CFStringRef s) { return s != null && s.getPointer() != null; }","tryCatchPattern":"try { value = cfString.stringValue(); } catch (IllegalArgumentException e) { value = \"\"; }","preventionTips":["Confirm the source API actually returns a CFString before casting to CFStringRef","Never call stringValue() on a default-constructed or released CFStringRef","Wrap stringValue() in a helper that returns Optional<String>"],"tags":["macos","corefoundation","native","string-conversion"],"backgroundTag":"invalid-argument-value","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"}