From eb793dede7d7eae27d9c1e8e245b263b52c333e6 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Wed, 15 Jan 2025 17:06:09 -0500
Subject: [PATCH] filesystem: SDL_GetCurrentDirectory() should add a path
separator at the end.
---
include/SDL3/SDL_filesystem.h | 3 +++
src/filesystem/posix/SDL_sysfsops.c | 10 +++++++++-
src/filesystem/windows/SDL_sysfilesystem.c | 12 +++++++++---
3 files changed, 21 insertions(+), 4 deletions(-)
diff --git a/include/SDL3/SDL_filesystem.h b/include/SDL3/SDL_filesystem.h
index 8baa254441952..245fe1fe38a19 100644
--- a/include/SDL3/SDL_filesystem.h
+++ b/include/SDL3/SDL_filesystem.h
@@ -483,6 +483,9 @@ extern SDL_DECLSPEC char ** SDLCALL SDL_GlobDirectory(const char *path, const ch
* platforms without this concept, this would cause surprises with file access
* outside of SDL.
*
+ * The returned path is guaranteed to end with a path separator ('\\' on
+ * Windows, '/' on most other platforms).
+ *
* \returns a UTF-8 string of the current working directory in
* platform-dependent notation. NULL if there's a problem. This
* should be freed with SDL_free() when it is no longer needed.
diff --git a/src/filesystem/posix/SDL_sysfsops.c b/src/filesystem/posix/SDL_sysfsops.c
index c562c2aed2461..015b8d4b5a9f6 100644
--- a/src/filesystem/posix/SDL_sysfsops.c
+++ b/src/filesystem/posix/SDL_sysfsops.c
@@ -217,7 +217,7 @@ char *SDL_SYS_GetCurrentDirectory(void)
}
buf = (char *) ptr;
- if (getcwd(buf, buflen) != NULL) {
+ if (getcwd(buf, buflen-1) != NULL) {
break; // we got it!
}
@@ -231,6 +231,14 @@ char *SDL_SYS_GetCurrentDirectory(void)
return NULL;
}
+ // make sure there's a path separator at the end.
+ SDL_assert(SDL_strlen(buf) < (buflen + 2));
+ buflen = SDL_strlen(buf);
+ if ((buflen == 0) || (buf[buflen-1] != '/')) {
+ buf[buflen] = '/';
+ buf[buflen + 1] = '\0';
+ }
+
return buf;
}
diff --git a/src/filesystem/windows/SDL_sysfilesystem.c b/src/filesystem/windows/SDL_sysfilesystem.c
index df9c9322d8c51..39ba414895177 100644
--- a/src/filesystem/windows/SDL_sysfilesystem.c
+++ b/src/filesystem/windows/SDL_sysfilesystem.c
@@ -355,11 +355,17 @@ char *SDL_SYS_GetCurrentDirectory(void)
if (bw == 0) {
WIN_SetError("GetCurrentDirectoryW failed");
return NULL;
- } else if (bw < buflen) {
- break; // we got it!
+ } else if (bw < buflen) { // we got it!
+ // make sure there's a path separator at the end.
+ SDL_assert(bw < (buflen + 2));
+ if ((bw == 0) || (wstr[bw-1] != '\\')) {
+ wstr[bw] = '\\';
+ wstr[bw + 1] = '\0';
+ }
+ break;
}
- void *ptr = SDL_realloc(wstr, bw * sizeof (WCHAR));
+ void *ptr = SDL_realloc(wstr, (bw + 1) * sizeof (WCHAR));
if (!ptr) {
SDL_free(wstr);
return NULL;