From 0075a9074cc88a724da80b9bc2621674ac79b006 Mon Sep 17 00:00:00 2001 From: rowanbeentje Date: Wed, 8 May 2013 08:28:02 +0000 Subject: - Fix bit data conversion to strings to avoid memory trampling, addressing Issue #1708 --- Frameworks/SPMySQLFramework/Source/SPMySQLResult.m | 28 +++++++++++++++------- 1 file changed, 19 insertions(+), 9 deletions(-) (limited to 'Frameworks/SPMySQLFramework/Source') diff --git a/Frameworks/SPMySQLFramework/Source/SPMySQLResult.m b/Frameworks/SPMySQLFramework/Source/SPMySQLResult.m index ee758bad..fdc83332 100644 --- a/Frameworks/SPMySQLFramework/Source/SPMySQLResult.m +++ b/Frameworks/SPMySQLFramework/Source/SPMySQLResult.m @@ -346,21 +346,31 @@ static id NSNullPointer; * Provides a binary representation of the supplied bytes as a returned NSString. * The resulting binary representation will be zero-padded according to the supplied * field length. + * MySQL stores bit data as string data stored in an 8-bit wide character set. */ + (NSString *)bitStringWithBytes:(const char *)bytes length:(NSUInteger)length padToLength:(NSUInteger)padLength { - if (bytes == NULL) return nil; - NSUInteger i = 0; - length--; - padLength--; + NSUInteger bitLength = length << 3; + + if (bytes == NULL) { + return nil; + } - // Generate a C string representation of the binary data - char *cStringBuffer = malloc(length + 1); - while (i <= padLength) { - cStringBuffer[padLength - i++] = ( (bytes[length - (i >> 3)] >> (i & 0x7)) & 1 ) ? '1' : '0'; + // Ensure padLength is never lower than the length + if (padLength < bitLength) { + padLength = bitLength; + } + + // Generate a nul-terminated C string representation of the binary data + char *cStringBuffer = malloc(padLength + 1); + cStringBuffer[padLength] = '\0'; + while (i < bitLength) { + cStringBuffer[padLength - ++i] = ( (bytes[length - 1 - (i >> 3)] >> (i & 0x7)) & 1 ) ? '1' : '0'; + } + while (i++ < padLength) { + cStringBuffer[padLength - i] = '0'; } - cStringBuffer[padLength+1] = '\0'; // Convert to a string NSString *returnString = [NSString stringWithUTF8String:cStringBuffer]; -- cgit v1.2.3