1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <pthread.h>
32 #include <stdatomic.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/types.h>
37 
38 #include <mutex>
39 
40 #include <android-base/stringprintf.h>
41 
42 #include "Config.h"
43 #include "debug_disable.h"
44 #include "debug_log.h"
45 #include "DebugData.h"
46 #include "RecordData.h"
47 
RecordEntry()48 RecordEntry::RecordEntry() : tid_(gettid()) {
49 }
50 
GetString() const51 std::string ThreadCompleteEntry::GetString() const {
52   return android::base::StringPrintf("%d: thread_done 0x0\n", tid_);
53 }
54 
AllocEntry(void * pointer)55 AllocEntry::AllocEntry(void* pointer) : pointer_(pointer) {
56 }
57 
MallocEntry(void * pointer,size_t size)58 MallocEntry::MallocEntry(void* pointer, size_t size) : AllocEntry(pointer), size_(size) {
59 }
60 
GetString() const61 std::string MallocEntry::GetString() const {
62   return android::base::StringPrintf("%d: malloc %p %zu\n", tid_, pointer_, size_);
63 }
64 
FreeEntry(void * pointer)65 FreeEntry::FreeEntry(void* pointer) : AllocEntry(pointer) {
66 }
67 
GetString() const68 std::string FreeEntry::GetString() const {
69   return android::base::StringPrintf("%d: free %p\n", tid_, pointer_);
70 }
71 
CallocEntry(void * pointer,size_t nmemb,size_t size)72 CallocEntry::CallocEntry(void* pointer, size_t nmemb, size_t size)
73     : MallocEntry(pointer, size), nmemb_(nmemb) {
74 }
75 
GetString() const76 std::string CallocEntry::GetString() const {
77   return android::base::StringPrintf("%d: calloc %p %zu %zu\n", tid_, pointer_, nmemb_, size_);
78 }
79 
ReallocEntry(void * pointer,size_t size,void * old_pointer)80 ReallocEntry::ReallocEntry(void* pointer, size_t size, void* old_pointer)
81     : MallocEntry(pointer, size), old_pointer_(old_pointer) {
82 }
83 
GetString() const84 std::string ReallocEntry::GetString() const {
85   return android::base::StringPrintf("%d: realloc %p %p %zu\n", tid_, pointer_,
86                                      old_pointer_, size_);
87 }
88 
89 // posix_memalign, memalgin, pvalloc, valloc all recorded with this class.
MemalignEntry(void * pointer,size_t size,size_t alignment)90 MemalignEntry::MemalignEntry(void* pointer, size_t size, size_t alignment)
91     : MallocEntry(pointer, size), alignment_(alignment) {
92 }
93 
GetString() const94 std::string MemalignEntry::GetString() const {
95   return android::base::StringPrintf("%d: memalign %p %zu %zu\n", tid_, pointer_,
96                                      alignment_, size_);
97 }
98 
99 struct ThreadData {
ThreadDataThreadData100   ThreadData(RecordData* record_data, ThreadCompleteEntry* entry) : record_data(record_data), entry(entry) {}
101   RecordData* record_data;
102   ThreadCompleteEntry* entry;
103   size_t count = 0;
104 };
105 
ThreadKeyDelete(void * data)106 static void ThreadKeyDelete(void* data) {
107   ThreadData* thread_data = reinterpret_cast<ThreadData*>(data);
108 
109   thread_data->count++;
110 
111   // This should be the last time we are called.
112   if (thread_data->count == 4) {
113     ScopedDisableDebugCalls disable;
114 
115     thread_data->record_data->AddEntryOnly(thread_data->entry);
116     delete thread_data;
117   } else {
118     pthread_setspecific(thread_data->record_data->key(), data);
119   }
120 }
121 
RecordDump(int,siginfo_t *,void *)122 static void RecordDump(int, siginfo_t*, void*) {
123   // It's not necessarily safe to do the dump here, instead wait for the
124   // next allocation call to do the dump.
125   g_debug->record->SetToDump();
126 }
127 
Dump()128 void RecordData::Dump() {
129   std::lock_guard<std::mutex> lock(dump_lock_);
130 
131   // Make it so that no more entries can be added while dumping.
132   unsigned int last_entry_index = cur_index_.exchange(static_cast<unsigned int>(num_entries_));
133   if (dump_ == false) {
134     // Multiple Dump() calls from different threads, and we lost. Do nothing.
135     return;
136   }
137 
138   // cur_index_ keeps getting incremented even if we hit the num_entries_.
139   // If that happens, cap the entries to dump by num_entries_.
140   if (last_entry_index > num_entries_) {
141     last_entry_index = num_entries_;
142   }
143 
144   int dump_fd = open(dump_file_.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
145                      0755);
146   if (dump_fd != -1) {
147     for (size_t i = 0; i < last_entry_index; i++) {
148       std::string line = entries_[i]->GetString();
149       ssize_t bytes = write(dump_fd, line.c_str(), line.length());
150       if (bytes == -1 || static_cast<size_t>(bytes) != line.length()) {
151         error_log("Failed to write record alloc information: %s", strerror(errno));
152         // Free all of the rest of the errors, we don't have any way
153         // to dump a partial list of the entries.
154         for (i++; i < last_entry_index; i++) {
155           delete entries_[i];
156           entries_[i] = nullptr;
157         }
158         break;
159       }
160       delete entries_[i];
161       entries_[i] = nullptr;
162     }
163     close(dump_fd);
164 
165     // Mark the entries dumped.
166     cur_index_ = 0U;
167   } else {
168     error_log("Cannot create record alloc file %s: %s", dump_file_.c_str(), strerror(errno));
169     // Since we couldn't create the file, reset the entries dumped back
170     // to the original value.
171     cur_index_ = last_entry_index;
172   }
173 
174   dump_ = false;
175 }
176 
RecordData()177 RecordData::RecordData() {
178   pthread_key_create(&key_, ThreadKeyDelete);
179 }
180 
Initialize(const Config & config)181 bool RecordData::Initialize(const Config& config) {
182   struct sigaction dump_act;
183   memset(&dump_act, 0, sizeof(dump_act));
184 
185   dump_act.sa_sigaction = RecordDump;
186   dump_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
187   sigemptyset(&dump_act.sa_mask);
188   if (sigaction(config.record_allocs_signal, &dump_act, nullptr) != 0) {
189     error_log("Unable to set up record dump signal function: %s", strerror(errno));
190     return false;
191   }
192   pthread_setspecific(key_, nullptr);
193 
194   info_log("%s: Run: 'kill -%d %d' to dump the allocation records.", getprogname(),
195            config.record_allocs_signal, getpid());
196 
197   num_entries_ = config.record_allocs_num_entries;
198   entries_ = new const RecordEntry*[num_entries_];
199   cur_index_ = 0;
200   dump_ = false;
201   dump_file_ = config.record_allocs_file;
202 
203   return true;
204 }
205 
~RecordData()206 RecordData::~RecordData() {
207   delete [] entries_;
208   pthread_key_delete(key_);
209 }
210 
AddEntryOnly(const RecordEntry * entry)211 void RecordData::AddEntryOnly(const RecordEntry* entry) {
212   unsigned int entry_index = cur_index_.fetch_add(1);
213   if (entry_index < num_entries_) {
214     entries_[entry_index] = entry;
215   }
216 }
217 
AddEntry(const RecordEntry * entry)218 void RecordData::AddEntry(const RecordEntry* entry) {
219   void* data = pthread_getspecific(key_);
220   if (data == nullptr) {
221     ThreadData* thread_data = new ThreadData(this, new ThreadCompleteEntry());
222     pthread_setspecific(key_, thread_data);
223   }
224 
225   AddEntryOnly(entry);
226 
227   // Check to see if it's time to dump the entries.
228   if (dump_) {
229     Dump();
230   }
231 }
232