Debian Codegraph @

src/bin/dwarfdump/dd_safe_strcpy.c

raw
1 /*
2 Copyright (c) 2021, David Anderson
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with
6 or without modification, are permitted provided that the
7 following conditions are met:
8
9 Redistributions of source code must retain the above
10 copyright notice, this list of conditions and the following
11 disclaimer.
12
13 Redistributions in binary form must reproduce the above
14 copyright notice, this list of conditions and the following
15 disclaimer in the documentation and/or other materials
16 provided with the distribution.
17
18 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
23 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 #include <config.h>
34
35 #include <stddef.h> /* NULL size_t */
36 #include "dd_safe_strcpy.h"
37
38 /* An strcpy/strncpy which ensures NUL terminated string
39 and never overruns the output.
40 inlen is strlen() size of in_s
41 outlen is buffer and has to have space
42 for the NUL in in_s to avoid truncation.
43 So typically outlen == (inlen+1).
44
45 If outlen is 0 it quietly returns.
46 If outlen is 1 it assigns a NUL byte to *out and returns.
47 If outlen > 0 then this function always writes
48 a trailing NUL byte.
49
50 ISO C 9899:1990 specifies that if outlen has extra space
51 that the function zeroes the extra bytes.
52 And if outlen is too small no NUL byte is written
53 to out.
54
55 This function writes only one NUL byte, the rest of
56 the 'out' buffer is untouched. Sometimes our callers
57 do not have a narrow bound to outlen, so zeroing
58 all the unused bytes is wasteful (hence we do not
59 do that here).
60
61 PRECONDITION:
62 The pointer arguments are required to be non-null.
63 */
64 void
65 dd_safe_strcpy(char *out,
66 size_t outlen,
67 const char *in_s,
68 size_t inlen)
69 {
70 size_t full_inlen = inlen+1;
71 char *cpo = 0;
72 const char *cpi= 0;
73 const char *cpiend = 0;
74
75 if (full_inlen >= outlen) {
76 if (!outlen) {
77 return;
78 }
79 cpo = out;
80 cpi= in_s;
81 cpiend = in_s +(outlen-1);
82 } else {
83 /* If outlen is very large
84 strncpy is very wasteful. */
85 cpo = out;
86 cpi= in_s;
87 cpiend = in_s +inlen;
88 }
89 for ( ; *cpi && cpi < cpiend ; ++cpo, ++cpi) {
90 *cpo = *cpi;
91 }
92 *cpo = 0;
93 }