]> git.saurik.com Git - apple/xnu.git/blobdiff - libsyscall/mach/mig_strncpy.c
xnu-4903.241.1.tar.gz
[apple/xnu.git] / libsyscall / mach / mig_strncpy.c
index 4366563fa9b545c86fdf92f24dc828ef5f72ee06..3bc188adf9d636591965e18f185782eea4faf346 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
+ * Copyright (c) 1999-2010 Apple Inc. All rights reserved.
  *
  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
  * 
 
 int
 mig_strncpy(
-    register char *dest,
-    register const char *src,
-    register int len)
+    char *dest,
+    const char *src,
+    int len)
 {
-    register int i;
+    int i;
 
-    if (len <= 0)
-       return 0;
+    if (len <= 0) {
+               return 0;
+       }
 
-    for (i=1; i<len; i++)
-       if (! (*dest++ = *src++))
-           return i;
+    for (i = 1; i < len; i++) {
+               if (!(*dest++ = *src++)) {
+                       return i;
+               }
+       }
 
     *dest = '\0';
     return i;
 }
+
+/*
+ * mig_strncpy_zerofill -- Bounded string copy.  Does what the
+ * library routine strncpy OUGHT to do:  Copies the (null terminated)
+ * string in src into dest, a buffer of length len.  Assures that
+ * the copy is still null terminated and doesn't overflow the buffer,
+ * truncating the copy if necessary. If the string in src is smaller
+ * than given length len, it will zero fill the remaining bytes in dest.
+ *
+ * Parameters:
+ *
+ *     dest - Pointer to destination buffer.
+ *
+ *     src - Pointer to source string.
+ *
+ *     len - Length of destination buffer.
+ *
+ * Result:
+ *     length of string copied, INCLUDING the trailing 0.
+ */
+int
+mig_strncpy_zerofill(
+    char *dest,
+    const char *src,
+    int len)
+{
+       int i;
+       boolean_t terminated = FALSE;
+       int retval = 0;
+
+       if (len <= 0 || dest == 0) {
+               return 0;
+       }
+
+       if (src == 0) {
+               terminated = TRUE;
+       }
+
+       for (i = 1; i < len; i++) {
+               if (!terminated) {
+                       if (!(*dest++ = *src++)) {
+                               retval = i;
+                               terminated = TRUE;
+                       }
+               } else {
+                       *dest++ = '\0';
+               }
+       }
+
+       *dest = '\0';
+       if (!terminated) {
+               retval = i;
+       }
+
+       return retval;
+}