[mlir] Update Ch-2.md (#121379)
[llvm-project.git] / libc / src / sys / mman / linux / shm_common.h
blobce75c2b5b6991d8e4bac4fcc554430145401068a
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 //===----------------------------------------------------------------------===//
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"
16 // TODO: Get PATH_MAX via https://github.com/llvm/llvm-project/issues/85121
17 #include <linux/limits.h>
19 namespace LIBC_NAMESPACE_DECL {
21 namespace shm_common {
23 LIBC_INLINE_VAR constexpr cpp::string_view SHM_PREFIX = "/dev/shm/";
24 using SHMPath = cpp::array<char, NAME_MAX + SHM_PREFIX.size() + 1>;
26 LIBC_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;
33 name = name.substr(offset);
35 // check the name
36 if (name.size() > NAME_MAX) {
37 libc_errno = ENAMETOOLONG;
38 return cpp::nullopt;
40 if (name == "." || name == ".." || name.contains('/')) {
41 libc_errno = EINVAL;
42 return cpp::nullopt;
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;
52 } // namespace shm_common
54 } // namespace LIBC_NAMESPACE_DECL