1 /*
2 * Copyright 2022 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 #pragma once
18
19 #include <log/log.h>
20 #include <sys/syscall.h> /* Definition of SYS_* constants */
21 #include <unistd.h>
22
23 #include <chrono>
24 #include <string>
25
26 #include "build_timestamp.h" // generated
27
28 long long GetTimestampMs();
29
30 // Internal to headless below
31
32 extern int console_fd;
33 extern std::chrono::system_clock::time_point _prev;
34
35 // Highlight the MAIN thread with text replacement
36 constexpr char _main[7 + 1] = " MAIN ";
37
38 #define STR(obj) (obj).ToString().c_str()
39
40 #define ASSERT_LOG(condition, fmt, args...) \
41 do { \
42 if (!(condition)) { \
43 LOG_ALWAYS_FATAL("assertion '" #condition "' failed - " fmt, ##args); \
44 } \
45 } while (false)
46
47 #define LOG_CONSOLE(fmt, args...) \
48 do { \
49 ASSERT_LOG(console_fd != -1, "Console output fd has not been set"); \
50 /* Also log to Android logging via INFO level */ \
51 ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args); \
52 auto _now = std::chrono::system_clock::now(); \
53 auto _delta = \
54 std::chrono::duration_cast<std::chrono::microseconds>(_now - _prev); \
55 _prev = _now; \
56 auto _now_us = \
57 std::chrono::time_point_cast<std::chrono::microseconds>(_now); \
58 auto _now_t = std::chrono::system_clock::to_time_t(_now); \
59 /* YYYY-MM-DD_HH:MM:SS.ssssss is 26 byte long, plus 1 for null terminator \
60 */ \
61 char _buf[26 + 1]; \
62 auto l = std::strftime(_buf, sizeof(_buf), "%Y-%m-%d %H:%M:%S", \
63 std::localtime(&_now_t)); \
64 snprintf(_buf + l, sizeof(_buf) - l, ".%06u", \
65 static_cast<unsigned int>(_now_us.time_since_epoch().count() % \
66 1000000)); \
67 /* pid max is 2^22 = 4194304 in 64-bit system, and 32768 by default, hence \
68 * 7 digits are needed most */ \
69 char _buf_thread[7 + 1]; \
70 snprintf(_buf_thread, sizeof(_buf_thread), "%7ld", syscall(SYS_gettid)); \
71 dprintf(console_fd, "%s - [ %9.06f ] %7d %s %s : " fmt "\n", _buf, \
72 _delta.count() / 1000000.0, static_cast<int>(getpid()), \
73 (syscall(SYS_gettid) == static_cast<int>(getpid())) ? _main \
74 : _buf_thread, \
75 LOG_TAG, ##args); \
76 } while (false)
77
78 constexpr char kCompiledDateFormat[] = "%b %d %Y";
79 constexpr char kBuildDateFormat[] = "%Y-%m-%d";
80
build_id()81 inline std::string build_id() {
82 return std::string(bluetooth::test::headless::kBuildTime);
83 }
84