foxygit / doom Log in
commit e63a8d5e3b2ebc848e01c139756cd2096efe7c80
Author:     Simon Howard <fraggle@gmail.com>
AuthorDate: Sat Mar 29 20:37:11 2014 -0400
Commit:     Simon Howard <fraggle@gmail.com>
CommitDate: Sat Mar 29 20:37:11 2014 -0400

    misc: Add M_StringConcat.

    Just as M_StringCopy behaves the same as strlcpy(), M_StringConcat
    behaves the same as strlcat(). Use this in one location.
---
 src/doom/d_main.c |  7 ++++---
 src/m_misc.c      | 21 ++++++++++++++++++++-
 src/m_misc.h      |  1 +
 3 files changed, 25 insertions(+), 4 deletions(-)

diff --git a/src/doom/d_main.c b/src/doom/d_main.c
index fa84bc3b..60d93696 100644
--- a/src/doom/d_main.c
+++ b/src/doom/d_main.c
@@ -1002,10 +1002,11 @@ static void LoadChexDeh(void)

         if (sep != NULL)
         {
-            chex_deh = malloc(strlen(iwadfile) + 9);
-            strcpy(chex_deh, iwadfile);
+            size_t chex_deh_len = strlen(iwadfile) + 9;
+            chex_deh = malloc(chex_deh_len);
+            M_StringCopy(chex_deh, iwadfile, chex_deh_len);
             chex_deh[sep - iwadfile + 1] = '\0';
-            strcat(chex_deh, "chex.deh");
+            M_StringConcat(chex_deh, "chex.deh", chex_deh_len);
         }
         else
         {
diff --git a/src/m_misc.c b/src/m_misc.c
index 7bab3f1b..02031213 100644
--- a/src/m_misc.c
+++ b/src/m_misc.c
@@ -366,6 +366,25 @@ boolean M_StringCopy(char *dest, char *src, size_t dest_size)
     return strlen(dest) == strlen(src);
 }

+// Safe string concat function that works like OpenBSD's strlcat().
+// Returns true if string not truncated.
+
+boolean M_StringConcat(char *dest, char *src, size_t dest_size)
+{
+    size_t offset;
+
+    offset = strlen(dest);
+    if (offset > dest_size)
+    {
+        offset = dest_size;
+    }
+
+    dest += offset;
+    dest_size -= offset;
+
+    return M_StringCopy(dest, src, dest_size);
+}
+
 // Returns true if 's' begins with the specified prefix.

 boolean M_StringStartsWith(char *s, char *prefix)
@@ -425,7 +444,7 @@ char *M_StringJoin(char *s, ...)
             break;
         }

-        strncat(result, v, result_len);
+        M_StringConcat(result, v, result_len);
     }
     va_end(args);

diff --git a/src/m_misc.h b/src/m_misc.h
index f81d6dc8..66035b5b 100644
--- a/src/m_misc.h
+++ b/src/m_misc.h
@@ -44,6 +44,7 @@ void M_ExtractFileBase(char *path, char *dest);
 void M_ForceUppercase(char *text);
 char *M_StrCaseStr(char *haystack, char *needle);
 boolean M_StringCopy(char *dest, char *src, size_t dest_size);
+boolean M_StringConcat(char *dest, char *src, size_t dest_size);
 char *M_StringReplace(char *haystack, char *needle, char *replacement);
 char *M_StringJoin(char *s, ...);
 boolean M_StringStartsWith(char *s, char *prefix);