[PATCH 1/2] powerpc/prom_init: Convert prom_strcpy() into prom_strscpy_pad()

Michael Ellerman mpe at ellerman.id.au
Tue Jun 22 14:11:39 AEST 2021


Daniel Axtens <dja at axtens.net> writes:
> Hi
>
>> -static char __init *prom_strcpy(char *dest, const char *src)
>> +static ssize_t __init prom_strscpy_pad(char *dest, const char *src, size_t n)
>>  {
>> -	char *tmp = dest;
>> +	ssize_t rc;
>> +	size_t i;
>>  
>> -	while ((*dest++ = *src++) != '\0')
>> -		/* nothing */;
>> -	return tmp;
>> +	if (n == 0 || n > INT_MAX)
>> +		return -E2BIG;
>> +
>> +	// Copy up to n bytes
>> +	for (i = 0; i < n && src[i] != '\0'; i++)
>> +		dest[i] = src[i];
>> +
>> +	rc = i;
>> +
>> +	// If we copied all n then we have run out of space for the nul
>> +	if (rc == n) {
>> +		// Rewind by one character to ensure nul termination
>> +		i--;
>> +		rc = -E2BIG;
>> +	}
>> +
>> +	for (; i < n; i++)
>> +		dest[i] = '\0';
>> +
>> +	return rc;
>>  }
>>  
>
> This implementation seems good to me.
>
> I copied it into a new C file and added the following:
>
> int main() {
> 	char longstr[255]="abcdefghijklmnopqrstuvwxyz";
> 	char shortstr[5];
> 	assert(prom_strscpy_pad(longstr, "", 0) == -E2BIG);
> 	assert(prom_strscpy_pad(longstr, "hello", 255) == 5);
> 	assert(prom_strscpy_pad(shortstr, "hello", 5) == -E2BIG);
> 	assert(memcmp(shortstr, "hell", 5) == 0);
> 	assert(memcmp(longstr, "hello\0\0\0\0\0\0\0\0\0", 6) == 0);
> 	return 0;
> }
>
> All the assertions pass. I believe this covers all the conditions from
> the strscpy_pad docstring.
>
> Reviewed-by: Daniel Axtens <dja at axtens.net>

Thanks.

I'll also drop the explicit nul termination in patch 2, which is a
leftover from when I was using strncpy().

cheers


More information about the Linuxppc-dev mailing list