Skip to content

fix: memory width issue in macOS keyCodeForChar#1

Open
PekingSpades wants to merge 1 commit intoTelosnex:mainfrom
PekingSpades:main
Open

fix: memory width issue in macOS keyCodeForChar#1
PekingSpades wants to merge 1 commit intoTelosnex:mainfrom
PekingSpades:main

Conversation

@PekingSpades
Copy link
Copy Markdown

Summary

  • Fix 64-bit memory corruption bug in keyCodeForChar function on macOS
  • Use pointer-sized intermediate variable for CFDictionaryGetValueIfPresent output
  • Add explicit uintptr_t cast for integer-to-pointer conversion

Problem

The keyCodeForChar function in src/macos/keycode.c had a critical 64-bit memory corruption bug:

CGKeyCode code;  // uint16_t - only 2 bytes
CFDictionaryGetValueIfPresent(charToCodeDict, charStr, (const void **)&code);

According to Apple's CFDictionary documentation, the value parameter of CFDictionaryGetValueIfPresent is:

"A pointer to memory which should be filled with the pointer-sized value if a matching key is found."

On 64-bit systems, this function writes 8 bytes, but CGKeyCode (uint16_t) is only 2 bytes. This causes stack memory corruption by overwriting 6 adjacent bytes.

Solution

Use a pointer-sized intermediate variable:

void *value = NULL;
CGKeyCode code;
if (!CFDictionaryGetValueIfPresent(charToCodeDict, charStr, (const void **)&value))
{
    code = UINT16_MAX;
}
else
{
    code = (CGKeyCode)(uintptr_t)value;
}

Also added explicit uintptr_t cast when storing values:

CFDictionaryAddValue(charToCodeDict, string, (const void *)(uintptr_t)i);

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant