xref: /aosp_15_r20/external/google-breakpad/src/common/linux/safe_readlink.cc (revision 9712c20fc9bbfbac4935993a2ca0b3958c5adad2)
1 // Copyright 2011 Google LLC
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 //     * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 //     * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 //     * Neither the name of Google LLC nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 // safe_readlink.cc: Implement google_breakpad::SafeReadLink.
30 // See safe_readlink.h for details.
31 
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>  // Must come first
34 #endif
35 
36 #include <stddef.h>
37 
38 #include "third_party/lss/linux_syscall_support.h"
39 
40 namespace google_breakpad {
41 
SafeReadLink(const char * path,char * buffer,size_t buffer_size)42 bool SafeReadLink(const char* path, char* buffer, size_t buffer_size) {
43   // sys_readlink() does not add a NULL byte to |buffer|. In order to return
44   // a NULL-terminated string in |buffer|, |buffer_size| should be at least
45   // one byte longer than the expected path length. Also, sys_readlink()
46   // returns the actual path length on success, which does not count the
47   // NULL byte, so |result_size| should be less than |buffer_size|.
48   ssize_t result_size = sys_readlink(path, buffer, buffer_size);
49   if (result_size >= 0 && static_cast<size_t>(result_size) < buffer_size) {
50     buffer[result_size] = '\0';
51     return true;
52   }
53   return false;
54 }
55 
56 }  // namespace google_breakpad
57