|
| 1 | +// Copyright 2022 The Bazel Authors. All rights reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include <unistd.h> |
| 16 | +#include <limits.h> |
| 17 | + |
| 18 | +#include "src/main/cpp/blaze_util_platform.h" |
| 19 | +#include "src/main/cpp/util/errors.h" |
| 20 | +#include "src/main/cpp/util/exit_code.h" |
| 21 | +#include "src/main/cpp/util/logging.h" |
| 22 | + |
| 23 | +namespace blaze { |
| 24 | + |
| 25 | +using blaze_util::GetLastErrorString; |
| 26 | +using std::string; |
| 27 | + |
| 28 | +string GetSelfPath(const char* argv0) { |
| 29 | + char buffer[PATH_MAX] = {}; |
| 30 | + ssize_t bytes = readlink("/proc/self/exe", buffer, sizeof(buffer)); |
| 31 | + if (bytes == sizeof(buffer)) { |
| 32 | + // symlink contents truncated |
| 33 | + bytes = -1; |
| 34 | + errno = ENAMETOOLONG; |
| 35 | + } |
| 36 | + if (bytes == -1) { |
| 37 | + BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR) |
| 38 | + << "error reading /proc/self/exe: " << GetLastErrorString(); |
| 39 | + } |
| 40 | + buffer[bytes] = '\0'; // readlink does not NUL-terminate |
| 41 | + return string(buffer); |
| 42 | +} |
| 43 | + |
| 44 | +} // namespace blaze |
0 commit comments