Back to index

glibc  2.9
strcpy_chk.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991, 1997, 2000, 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 <stddef.h>
00020 #include <string.h>
00021 #include <memcopy.h>
00022 
00023 #undef strcpy
00024 
00025 /* Copy SRC to DEST with checking of destination buffer overflow.  */
00026 char *
00027 __strcpy_chk (dest, src, destlen)
00028      char *dest;
00029      const char *src;
00030      size_t destlen;
00031 {
00032   reg_char c;
00033   char *s = (char *) src;
00034   const ptrdiff_t off = dest - s;
00035 
00036   while (__builtin_expect (destlen >= 4, 0))
00037     {
00038       c = s[0];
00039       s[off] = c;
00040       if (c == '\0')
00041         return dest;
00042       c = s[1];
00043       s[off + 1] = c;
00044       if (c == '\0')
00045         return dest;
00046       c = s[2];
00047       s[off + 2] = c;
00048       if (c == '\0')
00049         return dest;
00050       c = s[3];
00051       s[off + 3] = c;
00052       if (c == '\0')
00053         return dest;
00054       destlen -= 4;
00055       s += 4;
00056     }
00057 
00058   do
00059     {
00060       if (__builtin_expect (destlen-- == 0, 0))
00061         __chk_fail ();
00062       c = *s;
00063       *(s++ + off) = c;
00064     }
00065   while (c != '\0');
00066 
00067   return dest;
00068 }