From fa5469b287895128b0415577c81b7ef39176f7d8 Mon Sep 17 00:00:00 2001 From: doublelucky Date: Wed, 8 Jul 2026 11:55:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0statBuf.st=5Fsize=E8=8C=83?= =?UTF-8?q?=E5=9B=B4=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: doublelucky --- src/context_tool.c | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/context_tool.c b/src/context_tool.c index bb243ef..db38ad5 100644 --- a/src/context_tool.c +++ b/src/context_tool.c @@ -37,14 +37,35 @@ void FreeContextBuffer(char *contextBuffer) } } +static int32_t ReadFileContent(FILE *fp, char *contextBuffer, long long fileSize, const char *path) +{ + size_t retFread = fread(contextBuffer, (size_t)fileSize, 1, fp); + if (retFread != 1) { + PRINT_ERR("read file(%s) failed, errno = %d\n", path, errno); + return -1; + } + return 0; +} + +static int32_t CheckFileSize(const struct stat *statBuf) +{ + if (statBuf->st_size <= 0) { + PRINT_ERR("file size (%lld) out of range\n", (long long)statBuf->st_size); + return -1; + } + if ((uint64_t)statBuf->st_size >= (uint64_t)(UINT32_MAX - 1)) { + PRINT_ERR("file size (%lld) exceeds 32-bit limit\n", (long long)statBuf->st_size); + return -1; + } + return 0; +} + int32_t GetFileContext(const char *inputFile, char **contextBufPtr, uint32_t *bufferLen) { - int32_t ret; FILE *fp = NULL; struct stat statBuf; char *contextBuffer = NULL; char path[PATH_MAX + 1] = {0x00}; - #ifdef _POSIX_ if (strlen(inputFile) > PATH_MAX || strncpy_s(path, PATH_MAX, inputFile, strlen(inputFile)) != EOK) { PRINT_ERR("get path(%s) failed\n", inputFile); @@ -56,9 +77,7 @@ int32_t GetFileContext(const char *inputFile, char **contextBufPtr, uint32_t *bu return -1; } #endif - - ret = stat(path, &statBuf); - if (ret != 0) { + if (stat(path, &statBuf) != 0) { PRINT_ERR("get file(%s) st_mode failed, errno = %d\n", path, errno); return -1; } @@ -66,6 +85,9 @@ int32_t GetFileContext(const char *inputFile, char **contextBufPtr, uint32_t *bu PRINT_ERR("don't have permission to read the file(%s)\n", path); return -1; } + if (CheckFileSize(&statBuf) != 0) { + return -1; + } contextBuffer = (char *)malloc(statBuf.st_size + 1); if (contextBuffer == NULL) { PRINT_ERR("malloc buffer failed, size = %d, errno = %d\n", (int32_t)statBuf.st_size + 1, errno); @@ -77,16 +99,13 @@ int32_t GetFileContext(const char *inputFile, char **contextBufPtr, uint32_t *bu FreeContextBuffer(contextBuffer); return -1; } - size_t retFread = fread(contextBuffer, statBuf.st_size, 1, fp); - if (retFread != 1) { - PRINT_ERR("read file(%s) failed, errno = %d\n", path, errno); + if (ReadFileContent(fp, contextBuffer, statBuf.st_size, path) != 0) { FreeContextBuffer(contextBuffer); (void)fclose(fp); return -1; } contextBuffer[statBuf.st_size] = '\0'; (void)fclose(fp); - *contextBufPtr = contextBuffer; *bufferLen = statBuf.st_size + 1; return 0;