• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 
17 #include <err.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <malloc.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #include "Alloc.h"
31 #include "File.h"
32 #include "NativeInfo.h"
33 #include "Pointers.h"
34 #include "Thread.h"
35 #include "Threads.h"
36 
37 #include <log/log.h>
38 #include <log/log_read.h>
39 
40 constexpr size_t kDefaultMaxThreads = 512;
41 
GetMaxAllocs(const AllocEntry * entries,size_t num_entries)42 static size_t GetMaxAllocs(const AllocEntry* entries, size_t num_entries) {
43   size_t max_allocs = 0;
44   size_t num_allocs = 0;
45   for (size_t i = 0; i < num_entries; i++) {
46     switch (entries[i].type) {
47       case THREAD_DONE:
48         break;
49       case MALLOC:
50       case CALLOC:
51       case MEMALIGN:
52         if (entries[i].ptr != 0) {
53           num_allocs++;
54         }
55         break;
56       case REALLOC:
57         if (entries[i].ptr == 0 && entries[i].u.old_ptr != 0) {
58           num_allocs--;
59         } else if (entries[i].ptr != 0 && entries[i].u.old_ptr == 0) {
60           num_allocs++;
61         }
62         break;
63       case FREE:
64         if (entries[i].ptr != 0) {
65           num_allocs--;
66         }
67         break;
68     }
69     if (num_allocs > max_allocs) {
70       max_allocs = num_allocs;
71     }
72   }
73   return max_allocs;
74 }
75 
PrintLogStats(const char * log_name)76 static void PrintLogStats(const char* log_name) {
77   logger_list* list =
78       android_logger_list_open(android_name_to_log_id(log_name), ANDROID_LOG_NONBLOCK, 0, getpid());
79   if (list == nullptr) {
80     printf("Failed to open log for %s\n", log_name);
81     return;
82   }
83   while (true) {
84     log_msg entry;
85     ssize_t retval = android_logger_list_read(list, &entry);
86     if (retval == 0) {
87       break;
88     }
89     if (retval < 0) {
90       if (retval == -EINTR) {
91         continue;
92       }
93       // EAGAIN means there is nothing left to read when ANDROID_LOG_NONBLOCK is set.
94       if (retval != -EAGAIN) {
95         printf("Failed to read log entry: %s\n", strerrordesc_np(retval));
96       }
97       break;
98     }
99     if (entry.msg() == nullptr) {
100       continue;
101     }
102     // Only print allocator tagged log entries.
103     std::string_view tag(entry.msg() + 1);
104     if (tag != "scudo" && tag != "jemalloc") {
105       continue;
106     }
107     printf("%s\n", &tag.back() + 2);
108   }
109   android_logger_list_close(list);
110 }
111 
ProcessDump(const AllocEntry * entries,size_t num_entries,size_t max_threads)112 static void ProcessDump(const AllocEntry* entries, size_t num_entries, size_t max_threads) {
113   // Do a pass to get the maximum number of allocations used at one
114   // time to allow a single mmap that can hold the maximum number of
115   // pointers needed at once.
116   size_t max_allocs = GetMaxAllocs(entries, num_entries);
117   Pointers pointers(max_allocs);
118   Threads threads(&pointers, max_threads);
119 
120   dprintf(STDOUT_FILENO, "Maximum threads available:   %zu\n", threads.max_threads());
121   dprintf(STDOUT_FILENO, "Maximum allocations in dump: %zu\n", max_allocs);
122   dprintf(STDOUT_FILENO, "Total pointers available:    %zu\n\n", pointers.max_pointers());
123 
124   NativePrintInfo("Initial ");
125 
126   for (size_t i = 0; i < num_entries; i++) {
127     if (((i + 1) % 100000) == 0) {
128       dprintf(STDOUT_FILENO, "  At line %zu:\n", i + 1);
129       NativePrintInfo("    ");
130     }
131     const AllocEntry& entry = entries[i];
132     Thread* thread = threads.FindThread(entry.tid);
133     if (thread == nullptr) {
134       thread = threads.CreateThread(entry.tid);
135     }
136 
137     // Wait for the thread to complete any previous actions before handling
138     // the next action.
139     thread->WaitForReady();
140 
141     thread->SetAllocEntry(&entry);
142 
143     bool does_free = AllocDoesFree(entry);
144     if (does_free) {
145       // Make sure that any other threads doing allocations are complete
146       // before triggering the action. Otherwise, another thread could
147       // be creating the allocation we are going to free.
148       threads.WaitForAllToQuiesce();
149     }
150 
151     // Tell the thread to execute the action.
152     thread->SetPending();
153 
154     if (entries[i].type == THREAD_DONE) {
155       // Wait for the thread to finish and clear the thread entry.
156       threads.Finish(thread);
157     }
158 
159     // Wait for this action to complete. This avoids a race where
160     // another thread could be creating the same allocation where are
161     // trying to free.
162     if (does_free) {
163       thread->WaitForReady();
164     }
165   }
166   // Wait for all threads to stop processing actions.
167   threads.WaitForAllToQuiesce();
168 
169   NativePrintInfo("Final ");
170 
171   // Free any outstanding pointers.
172   // This allows us to run a tool like valgrind to verify that no memory
173   // is leaked and everything is accounted for during a run.
174   threads.FinishAll();
175   pointers.FreeAll();
176 
177   // Print out the total time making all allocation calls.
178   char buffer[256];
179   uint64_t total_nsecs = threads.total_time_nsecs();
180   NativeFormatFloat(buffer, sizeof(buffer), total_nsecs, 1000000000);
181   dprintf(STDOUT_FILENO, "Total Allocation/Free Time: %" PRIu64 "ns %ss\n", total_nsecs, buffer);
182 
183   // Send native allocator stats to the log
184   mallopt(M_LOG_STATS, 0);
185 
186   // No need to avoid allocations at this point since all stats have been sent to the log.
187   printf("Native Allocator Stats:\n");
188   PrintLogStats("system");
189   PrintLogStats("main");
190 }
191 
main(int argc,char ** argv)192 int main(int argc, char** argv) {
193   if (argc != 2 && argc != 3) {
194     if (argc > 3) {
195       fprintf(stderr, "Only two arguments are expected.\n");
196     } else {
197       fprintf(stderr, "Requires at least one argument.\n");
198     }
199     fprintf(stderr, "Usage: %s MEMORY_LOG_FILE [MAX_THREADS]\n", basename(argv[0]));
200     fprintf(stderr, "  MEMORY_LOG_FILE\n");
201     fprintf(stderr, "    This can either be a text file or a zipped text file.\n");
202     fprintf(stderr, "  MAX_THREADs\n");
203     fprintf(stderr, "    The maximum number of threads in the trace. The default is %zu.\n",
204             kDefaultMaxThreads);
205     fprintf(stderr, "    This pre-allocates the memory for thread data to avoid allocating\n");
206     fprintf(stderr, "    while the trace is being replayed.\n");
207     return 1;
208   }
209 
210 #if defined(__LP64__)
211   dprintf(STDOUT_FILENO, "64 bit environment.\n");
212 #else
213   dprintf(STDOUT_FILENO, "32 bit environment.\n");
214 #endif
215 
216 #if defined(__BIONIC__)
217   dprintf(STDOUT_FILENO, "Setting decay time to 1\n");
218   mallopt(M_DECAY_TIME, 1);
219 #endif
220 
221   size_t max_threads = kDefaultMaxThreads;
222   if (argc == 3) {
223     max_threads = atoi(argv[2]);
224   }
225 
226   AllocEntry* entries;
227   size_t num_entries;
228   GetUnwindInfo(argv[1], &entries, &num_entries);
229 
230   dprintf(STDOUT_FILENO, "Processing: %s\n", argv[1]);
231 
232   ProcessDump(entries, num_entries, max_threads);
233 
234   FreeEntries(entries, num_entries);
235 
236   return 0;
237 }
238