1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
|
/**************************************************************************
*
* Copyright 2007-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "os.hpp"
#include "os_thread.hpp"
#include "os_string.hpp"
#include "os_version.hpp"
#include "trace_option.hpp"
#include "trace_ostream.hpp"
#include "trace_writer_local.hpp"
#include "trace_format.hpp"
#include "os_backtrace.hpp"
#ifdef _WIN32
#include <shlobj.h>
#endif
namespace trace {
static const char *memcpy_args[3] = {"dest", "src", "n"};
const FunctionSig memcpy_sig = {0, "memcpy", 3, memcpy_args};
static const char *malloc_args[1] = {"size"};
const FunctionSig malloc_sig = {1, "malloc", 1, malloc_args};
static const char *free_args[1] = {"ptr"};
const FunctionSig free_sig = {2, "free", 1, free_args};
static const char *realloc_args[2] = {"ptr", "size"};
const FunctionSig realloc_sig = {3, "realloc", 2, realloc_args};
static void exceptionCallback(void)
{
localWriter.flush();
}
LocalWriter::LocalWriter() :
acquired(0),
sharedPtrThis(std::make_shared<LocalWriter*>(this))
{
os::String process = os::getProcessName();
os::log("apitrace: loaded into %s\n", process.str());
// Install the signal handlers as early as possible, to prevent
// interfering with the application's signal handling.
os::setExceptionCallback(exceptionCallback);
}
static void FlushLocalWriterThread(const std::weak_ptr<LocalWriter*> writerWeakPtr,
const uint32_t intervalMs)
{
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(intervalMs));
const auto locked = writerWeakPtr.lock();
if (!locked)
break;
const auto writer = *locked;
writer->flush();
}
}
LocalWriter::~LocalWriter()
{
os::resetExceptionCallback();
checkProcessId();
os::String process = os::getProcessName();
os::log("apitrace: unloaded from %s\n", process.str());
}
void
LocalWriter::open(void) {
os::String szFileName;
const char *lpFileName;
char suffix[17] = "";
bool hasTimestamp;
hasTimestamp = boolOption(getenv("TRACE_TIMESTAMP"), false);
if (hasTimestamp) {
std::time_t time = std::time({});
strftime(suffix, sizeof(suffix), ".%Y%m%dT%H%M%S", std::localtime(&time));
}
lpFileName = getenv("TRACE_FILE");
if (!lpFileName) {
static unsigned dwCounter = 0;
os::String process = os::getProcessName();
#ifdef _WIN32
process.trimExtension();
#endif
process.trimDirectory();
os::String prefix = os::getCurrentDir();
#ifdef _WIN32
// Default to user's desktop, as current directory often points to
// system directory or program files, which are not generally writable.
char szDesktopPath[MAX_PATH];
HRESULT hr = SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, szDesktopPath);
if (SUCCEEDED(hr)) {
prefix = szDesktopPath;
}
#endif
prefix.join(process);
for (;;) {
FILE *file;
if (dwCounter)
szFileName = os::String::format("%s.%s%u.trace", prefix.str(), suffix, dwCounter);
else
szFileName = os::String::format("%s%s.trace", prefix.str(), suffix);
lpFileName = szFileName;
file = fopen(lpFileName, "rb");
if (file == NULL)
break;
fclose(file);
++dwCounter;
}
} else if (hasTimestamp) {
const char *ext = strrchr(lpFileName, '.');
int length = ext ? ext - lpFileName : strlen(lpFileName);
szFileName = os::String::format("%.*s%s%s", length, lpFileName, suffix, ext ? ext : "");
lpFileName = szFileName;
}
os::log("apitrace: tracing to %s\n", lpFileName);
Properties properties;
os::String processName = os::getProcessName();
properties["process.name"] = processName;
os::String processCommandLine = os::getProcessCommandLine();
properties["process.commandLine"] = processCommandLine;
if (!Writer::open(lpFileName, TRACE_VERSION, properties)) {
os::log("apitrace: error: failed to open %s\n", lpFileName);
os::abort();
}
pid = os::getCurrentProcessId();
const auto flushIntervalStr = getenv("FLUSH_EVERY_MS");
if (flushIntervalStr) {
const auto intervalMs = atoi(flushIntervalStr);
if (intervalMs < 0) {
os::log("apitrace: error: invalid FLUSH_EVERY_MS: %s\n", flushIntervalStr);
os::abort();
}
std::thread(FlushLocalWriterThread, this->sharedPtrThis, uint32_t(intervalMs)).detach();
}
#if 0
// For debugging the exception handler
*((int *)0) = 0;
#endif
}
static uintptr_t next_thread_num = 1;
static OS_THREAD_LOCAL uintptr_t thread_num;
void LocalWriter::checkProcessId(void) {
if (m_file &&
os::getCurrentProcessId() != pid) {
// We are a forked child process that inherited the trace file, so
// create a new file. We can't call any method of the current
// file, as it may cause it to flush and corrupt the parent's
// trace, so we effectively leak the old file object.
close();
// Don't want to open the same file again
os::unsetEnvironment("TRACE_FILE");
open();
}
}
unsigned LocalWriter::beginEnter(const FunctionSig *sig, bool fake) {
mutex.lock();
++acquired;
checkProcessId();
if (!m_file) {
open();
}
uintptr_t this_thread_num = thread_num;
if (!this_thread_num) {
this_thread_num = next_thread_num++;
thread_num = this_thread_num;
}
assert(this_thread_num);
unsigned thread_id = this_thread_num - 1;
unsigned call_no = Writer::beginEnter(sig, thread_id);
if (fake) {
writeFlags(FLAG_FAKE);
} else if (os::backtrace_is_needed(sig->name)) {
std::vector<RawStackFrame> backtrace = os::get_backtrace();
beginBacktrace(backtrace.size());
for (auto & frame : backtrace) {
writeStackFrame(&frame);
}
endBacktrace();
}
return call_no;
}
void LocalWriter::endEnter(void) {
Writer::endEnter();
--acquired;
mutex.unlock();
}
void LocalWriter::beginLeave(unsigned call) {
mutex.lock();
++acquired;
Writer::beginLeave(call);
}
void LocalWriter::endLeave(void) {
Writer::endLeave();
--acquired;
mutex.unlock();
}
void LocalWriter::flush(void) {
/*
* Do nothing if the mutex is already acquired (e.g., if a segfault happen
* while writing the file) as state could be inconsistent, therefore yield
* inconsistent trace files and/or repeated segfaults till infinity.
*/
mutex.lock();
if (acquired) {
os::log("apitrace: ignoring recurrent flush\n");
} else {
++acquired;
if (m_file) {
if (os::getCurrentProcessId() != pid) {
os::log("apitrace: ignoring flush in child process\n");
} else {
os::log("apitrace: flushing trace\n");
m_file->flush();
}
}
--acquired;
}
mutex.unlock();
}
LocalWriter localWriter;
void fakeMemcpy(const void *ptr, size_t size) {
assert(ptr);
if (!size) {
return;
}
unsigned _call = localWriter.beginEnter(&memcpy_sig, true);
#if defined(_WIN32) && !defined(NDEBUG)
size_t maxSize = 0;
MEMORY_BASIC_INFORMATION mi;
while (VirtualQuery((const uint8_t *)ptr + maxSize, &mi, sizeof mi) == sizeof mi &&
mi.Protect & (PAGE_READONLY|PAGE_READWRITE)) {
maxSize = (const uint8_t *)mi.BaseAddress + mi.RegionSize - (const uint8_t *)ptr;
}
if (maxSize < size) {
os::log("apitrace: warning: %u: clamping size from %zu to %zu\n", _call, size, maxSize);
size = maxSize;
}
#endif
localWriter.beginArg(0);
localWriter.writePointer((uintptr_t)ptr);
localWriter.endArg();
localWriter.beginArg(1);
localWriter.writeBlob(ptr, size);
localWriter.endArg();
localWriter.beginArg(2);
localWriter.writeUInt(size);
localWriter.endArg();
localWriter.endEnter();
localWriter.beginLeave(_call);
localWriter.endLeave();
}
} /* namespace trace */
|