1 //===---------- Shared implementations for shm_open/shm_unlink ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "src/__support/CPP/array.h" 10 #include "src/__support/CPP/optional.h" 11 #include "src/__support/CPP/string_view.h" 12 #include "src/__support/macros/config.h" 13 #include "src/errno/libc_errno.h" 14 #include "src/string/memory_utils/inline_memcpy.h" 15 16 // TODO: Get PATH_MAX via https://github.com/llvm/llvm-project/issues/85121 17 #include <linux/limits.h> 18 19 namespace LIBC_NAMESPACE_DECL { 20 21 namespace shm_common { 22 23 LIBC_INLINE_VAR constexpr cpp::string_view SHM_PREFIX = "/dev/shm/"; 24 using SHMPath = cpp::array<char, NAME_MAX + SHM_PREFIX.size() + 1>; 25 translate_name(cpp::string_view name)26LIBC_INLINE cpp::optional<SHMPath> translate_name(cpp::string_view name) { 27 // trim leading slashes 28 size_t offset = name.find_first_not_of('/'); 29 if (offset == cpp::string_view::npos) { 30 libc_errno = EINVAL; 31 return cpp::nullopt; 32 } 33 name = name.substr(offset); 34 35 // check the name 36 if (name.size() > NAME_MAX) { 37 libc_errno = ENAMETOOLONG; 38 return cpp::nullopt; 39 } 40 if (name == "." || name == ".." || name.contains('/')) { 41 libc_errno = EINVAL; 42 return cpp::nullopt; 43 } 44 45 // prepend the prefix 46 SHMPath buffer; 47 inline_memcpy(buffer.data(), SHM_PREFIX.data(), SHM_PREFIX.size()); 48 inline_memcpy(buffer.data() + SHM_PREFIX.size(), name.data(), name.size()); 49 buffer[SHM_PREFIX.size() + name.size()] = '\0'; 50 return buffer; 51 } 52 } // namespace shm_common 53 54 } // namespace LIBC_NAMESPACE_DECL 55