Ensure strncpy'ed strings are all null terminated

If there is no null byte among the first n bytes of the source the
resulting string will not be properly null terminated.
Ensure that all strings that are copied via strncpy are properly
terminated copy "sizeof (dest) - 1" bytes and manually terminate
the string in the cases the array was not initialized.

Example compiler warning:
  ../daemon/gamemode-tests.c: In function ‘run_cpu_governor_tests’:
  ../daemon/gamemode-tests.c:326:4: warning: ‘strncpy’ specified bound
      256 equals destination size [-Wstringop-truncation]
    strncpy(defaultgov, currentgov, CONFIG_VALUE_MAX);
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This commit is contained in:
Christian Kellner
2019-03-21 09:55:51 +01:00
committed by Alex Smith
parent db4dd87e22
commit bbde1d0357
4 changed files with 12 additions and 11 deletions

View File

@@ -289,7 +289,7 @@ static int get_gpu_state_amd(struct GameModeGPUInfo *info)
return -1;
}
char buff[CONFIG_VALUE_MAX];
char buff[CONFIG_VALUE_MAX] = { 0 };
if (!fgets(buff, CONFIG_VALUE_MAX, file)) {
LOG_ERROR("Could not read file %s (%s)!\n", path, strerror(errno));
return -1;
@@ -301,8 +301,8 @@ static int get_gpu_state_amd(struct GameModeGPUInfo *info)
}
/* Copy in the value from the file */
strncpy(info->amd_performance_level, buff, CONFIG_VALUE_MAX);
strncpy(info->amd_performance_level, buff, CONFIG_VALUE_MAX - 1);
info->amd_performance_level[CONFIG_VALUE_MAX - 1] = '\0';
return info == NULL;
}
@@ -449,7 +449,7 @@ int main(int argc, char *argv[])
LOG_ERROR("Must pass performance level for AMD gpu!\n");
print_usage_and_exit();
}
strncpy(info.amd_performance_level, argv[3], CONFIG_VALUE_MAX);
strncpy(info.amd_performance_level, argv[3], CONFIG_VALUE_MAX - 1);
return set_gpu_state_amd(&info);
break;
default: