Back to index

glibc  2.9
strncpy_chk.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991, 1997, 2003, 2004 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <string.h>
00020 #include <memcopy.h>
00021 
00022 
00023 char *
00024 __strncpy_chk (s1, s2, n, s1len)
00025      char *s1;
00026      const char *s2;
00027      size_t n;
00028      size_t s1len;
00029 {
00030   reg_char c;
00031   char *s = s1;
00032 
00033   if (__builtin_expect (s1len < n, 0))
00034     __chk_fail ();
00035 
00036   --s1;
00037 
00038   if (n >= 4)
00039     {
00040       size_t n4 = n >> 2;
00041 
00042       for (;;)
00043        {
00044          c = *s2++;
00045          *++s1 = c;
00046          if (c == '\0')
00047            break;
00048          c = *s2++;
00049          *++s1 = c;
00050          if (c == '\0')
00051            break;
00052          c = *s2++;
00053          *++s1 = c;
00054          if (c == '\0')
00055            break;
00056          c = *s2++;
00057          *++s1 = c;
00058          if (c == '\0')
00059            break;
00060          if (--n4 == 0)
00061            goto last_chars;
00062        }
00063       n = n - (s1 - s) - 1;
00064       if (n == 0)
00065        return s;
00066       goto zero_fill;
00067     }
00068 
00069  last_chars:
00070   n &= 3;
00071   if (n == 0)
00072     return s;
00073 
00074   do
00075     {
00076       c = *s2++;
00077       *++s1 = c;
00078       if (--n == 0)
00079        return s;
00080     }
00081   while (c != '\0');
00082 
00083  zero_fill:
00084   do
00085     *++s1 = '\0';
00086   while (--n > 0);
00087 
00088   return s;
00089 }