1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "crazy_linker_debug.h"
6
7#include <errno.h>
8#include <string.h>
9
10#ifdef __ANDROID__
11#include <android/log.h>
12#endif
13#include <stdarg.h>
14#include <stdio.h>
15
16namespace crazy {
17
18#if CRAZY_DEBUG
19
20namespace {
21
22void LogArgs(const char* fmt, va_list args, bool print_error, int error) {
23  const size_t buffer_size = 4096;
24  char* buffer = reinterpret_cast<char*>(::malloc(buffer_size));
25  int ret;
26
27  ret = vsnprintf(buffer, buffer_size, fmt, args);
28  if (ret >= static_cast<int>(buffer_size))
29    ret = static_cast<int>(buffer_size) - 1;
30
31  if (print_error) {
32    strlcat(buffer, ": ", buffer_size);
33    strlcat(buffer, strerror(error), buffer_size);
34  }
35
36  // First, send to stderr.
37  fprintf(stderr, "%.*s", ret, buffer);
38
39#ifdef __ANDROID__
40  // Then to the Android log.
41  __android_log_write(ANDROID_LOG_INFO, "crazy_linker", buffer);
42#endif
43
44  ::free(buffer);
45}
46
47}  // namespace
48
49void Log(const char* fmt, ...) {
50  int old_errno = errno;
51  va_list args;
52  va_start(args, fmt);
53  LogArgs(fmt, args, false, -1);
54  va_end(args);
55  errno = old_errno;
56}
57
58void LogErrno(const char* fmt, ...) {
59  int old_errno = errno;
60  va_list args;
61  va_start(args, fmt);
62  LogArgs(fmt, args, true, old_errno);
63  va_end(args);
64  errno = old_errno;
65}
66
67#endif  // CRAZY_DEBUG
68
69}  // namespace crazy
70