2005-12-13 Ulrich Drepper <drepper@redhat.com>
[platform/upstream/linaro-glibc.git] / debug / strncpy_chk.c
1 /* Copyright (C) 1991, 1997, 2003, 2004 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Lesser General Public
6    License as published by the Free Software Foundation; either
7    version 2.1 of the License, or (at your option) any later version.
8
9    The GNU C Library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Lesser General Public License for more details.
13
14    You should have received a copy of the GNU Lesser General Public
15    License along with the GNU C Library; if not, write to the Free
16    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17    02111-1307 USA.  */
18
19 #include <string.h>
20 #include <memcopy.h>
21
22
23 char *
24 __strncpy_chk (s1, s2, n, s1len)
25      char *s1;
26      const char *s2;
27      size_t n;
28      size_t s1len;
29 {
30   reg_char c;
31   char *s = s1;
32
33   if (__builtin_expect (s1len < n, 0))
34     __chk_fail ();
35
36   --s1;
37
38   if (n >= 4)
39     {
40       size_t n4 = n >> 2;
41
42       for (;;)
43         {
44           c = *s2++;
45           *++s1 = c;
46           if (c == '\0')
47             break;
48           c = *s2++;
49           *++s1 = c;
50           if (c == '\0')
51             break;
52           c = *s2++;
53           *++s1 = c;
54           if (c == '\0')
55             break;
56           c = *s2++;
57           *++s1 = c;
58           if (c == '\0')
59             break;
60           if (--n4 == 0)
61             goto last_chars;
62         }
63       n = n - (s1 - s) - 1;
64       if (n == 0)
65         return s;
66       goto zero_fill;
67     }
68
69  last_chars:
70   n &= 3;
71   if (n == 0)
72     return s;
73
74   do
75     {
76       c = *s2++;
77       *++s1 = c;
78       if (--n == 0)
79         return s;
80     }
81   while (c != '\0');
82
83  zero_fill:
84   do
85     *++s1 = '\0';
86   while (--n > 0);
87
88   return s;
89 }