NativeInfo.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (C) 2014 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <err.h>
  17. #include <errno.h>
  18. #include <fcntl.h>
  19. #include <inttypes.h>
  20. #include <stdint.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #include <android-base/unique_fd.h>
  27. #include "LineBuffer.h"
  28. #include "NativeInfo.h"
  29. // This function is not re-entrant since it uses a static buffer for
  30. // the line data.
  31. void GetNativeInfo(int smaps_fd, size_t* pss_bytes, size_t* va_bytes) {
  32. static char map_buffer[65535];
  33. LineBuffer line_buf(smaps_fd, map_buffer, sizeof(map_buffer));
  34. char* line;
  35. size_t total_pss_bytes = 0;
  36. size_t total_va_bytes = 0;
  37. size_t line_len;
  38. bool native_map = false;
  39. while (line_buf.GetLine(&line, &line_len)) {
  40. uintptr_t start, end;
  41. int name_pos;
  42. size_t native_pss_kB;
  43. if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %*4s %*x %*x:%*x %*d %n",
  44. &start, &end, &name_pos) == 2) {
  45. if (strcmp(line + name_pos, "[anon:libc_malloc]") == 0 ||
  46. strcmp(line + name_pos, "[heap]") == 0) {
  47. total_va_bytes += end - start;
  48. native_map = true;
  49. } else {
  50. native_map = false;
  51. }
  52. } else if (native_map && sscanf(line, "Pss: %zu", &native_pss_kB) == 1) {
  53. total_pss_bytes += native_pss_kB * 1024;
  54. }
  55. }
  56. *pss_bytes = total_pss_bytes;
  57. *va_bytes = total_va_bytes;
  58. }
  59. void PrintNativeInfo(const char* preamble) {
  60. size_t pss_bytes;
  61. size_t va_bytes;
  62. android::base::unique_fd smaps_fd(open("/proc/self/smaps", O_RDONLY));
  63. if (smaps_fd == -1) {
  64. err(1, "Cannot open /proc/self/smaps: %s\n", strerror(errno));
  65. }
  66. GetNativeInfo(smaps_fd, &pss_bytes, &va_bytes);
  67. printf("%sNative PSS: %zu bytes %0.2fMB\n", preamble, pss_bytes, pss_bytes/(1024*1024.0));
  68. printf("%sNative VA Space: %zu bytes %0.2fMB\n", preamble, va_bytes, va_bytes/(1024*1024.0));
  69. fflush(stdout);
  70. }