paths_linux.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2016 The Crashpad 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. #include "util/misc/paths.h"
  15. #include <limits.h>
  16. #include <unistd.h>
  17. #include <algorithm>
  18. #include <string>
  19. #include "base/logging.h"
  20. namespace crashpad {
  21. // static
  22. bool Paths::Executable(base::FilePath* path) {
  23. // Linux does not provide a straightforward way to size the buffer before
  24. // calling readlink(). Normally, the st_size field returned by lstat() could
  25. // be used, but this is usually zero for things in /proc.
  26. //
  27. // The /proc filesystem does not provide any way to read “exe” links for
  28. // pathnames longer than a page. See linux-4.9.20/fs/proc/base.c
  29. // do_proc_readlink(), which allocates a single page to receive the path
  30. // string. Coincidentally, the page size and PATH_MAX are normally the same
  31. // value, although neither is strictly a limit on the length of a pathname.
  32. //
  33. // On Android, the smaller of the page size and PATH_MAX actually does serve
  34. // as an effective limit on the length of an executable’s pathname. See
  35. // Android 7.1.1 bionic/linker/linker.cpp get_executable_path(), which aborts
  36. // via __libc_fatal() if the “exe” link can’t be read into a PATH_MAX-sized
  37. // buffer.
  38. std::string exe_path(std::max(getpagesize(), PATH_MAX),
  39. std::string::value_type());
  40. ssize_t exe_path_len =
  41. readlink("/proc/self/exe", &exe_path[0], exe_path.size());
  42. if (exe_path_len < 0) {
  43. PLOG(ERROR) << "readlink";
  44. return false;
  45. } else if (static_cast<size_t>(exe_path_len) >= exe_path.size()) {
  46. LOG(ERROR) << "readlink";
  47. return false;
  48. }
  49. exe_path.resize(exe_path_len);
  50. *path = base::FilePath(exe_path);
  51. return true;
  52. }
  53. } // namespace crashpad