Browse Source

filesystem: SDL_GetCurrentDirectory() should add a path separator at the end.

Ryan C. Gordon 3 months ago
parent
commit
eb793dede7

+ 3 - 0
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.

+ 9 - 1
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;
 }
 

+ 9 - 3
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;