Fix buffer overflow in BLI_path_append

This commit is contained in:
Campbell Barton
2023-05-17 12:58:01 +10:00
parent 0ae286be03
commit 761eac2f5d
2 changed files with 51 additions and 9 deletions

View File

@@ -1604,18 +1604,19 @@ size_t BLI_path_append(char *__restrict dst, const size_t dst_maxncpy, const cha
{
BLI_string_debug_size_after_nil(dst, dst_maxncpy);
size_t dirlen = BLI_strnlen(dst, dst_maxncpy);
size_t dst_len = BLI_strnlen(dst, dst_maxncpy);
/* Inline #BLI_path_slash_ensure. */
if ((dirlen > 0) && !BLI_path_slash_is_native_compat(dst[dirlen - 1])) {
dst[dirlen++] = SEP;
dst[dirlen] = '\0';
if (dst_len + 1 < dst_maxncpy) {
if ((dst_len > 0) && !BLI_path_slash_is_native_compat(dst[dst_len - 1])) {
dst[dst_len++] = SEP;
dst[dst_len] = '\0';
}
if (dst_len + 1 < dst_maxncpy) {
dst_len += BLI_strncpy_rlen(dst + dst_len, file, dst_maxncpy - dst_len);
}
}
if (dirlen >= dst_maxncpy) {
return dirlen; /* Fills the path. */
}
return dirlen + BLI_strncpy_rlen(dst + dirlen, file, dst_maxncpy - dirlen);
return dst_len;
}
size_t BLI_path_append_dir(char *__restrict dst,

View File

@@ -580,6 +580,47 @@ TEST(path_util, JoinRelativePrefix)
/** \} */
/* -------------------------------------------------------------------- */
/** \name Tests for: #BLI_path_append
* \{ */
/* For systems with `/` path separator (non WIN32). */
#define APPEND(str_expect, size, path, filename) \
{ \
const char *expect = str_expect; \
char result[(size) + 1024] = path; \
char filename_native[] = filename; \
/* Check we don't write past the last byte. */ \
if (SEP == '\\') { \
BLI_str_replace_char(filename_native, '/', '\\'); \
BLI_str_replace_char(result, '/', '\\'); \
} \
BLI_path_append(result, size, filename_native); \
if (SEP == '\\') { \
BLI_str_replace_char(result, '\\', '/'); \
} \
EXPECT_STREQ(result, expect); \
} \
((void)0)
TEST(path_util, AppendFile)
{
APPEND("a/b", 100, "a", "b");
APPEND("a/b", 100, "a/", "b");
}
TEST(path_util, AppendFile_Truncate)
{
APPEND("/A", 3, "/", "ABC");
APPEND("/", 2, "/", "test");
APPEND("X", 2, "X", "ABC");
APPEND("X/", 3, "X/", "ABC");
}
#undef APPEND
/** \} */
/* -------------------------------------------------------------------- */
/** \name Tests for: #BLI_path_frame
* \{ */