logcat.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. /*
  2. * Copyright (C) 2006-2017 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. #include "logcat.h"
  17. #include <android-base/macros.h>
  18. #include <arpa/inet.h>
  19. #include <assert.h>
  20. #include <ctype.h>
  21. #include <dirent.h>
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <getopt.h>
  25. #include <math.h>
  26. #include <pthread.h>
  27. #include <sched.h>
  28. #include <stdarg.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <sys/cdefs.h>
  33. #include <sys/resource.h>
  34. #include <sys/socket.h>
  35. #include <sys/stat.h>
  36. #include <sys/types.h>
  37. #include <time.h>
  38. #include <unistd.h>
  39. #include <atomic>
  40. #include <memory>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. #include <android-base/file.h>
  45. #include <android-base/properties.h>
  46. #include <android-base/stringprintf.h>
  47. #include <android-base/strings.h>
  48. #include <cutils/sockets.h>
  49. #include <log/event_tag_map.h>
  50. #include <log/logprint.h>
  51. #include <private/android_logger.h>
  52. #include <processgroup/sched_policy.h>
  53. #include <system/thread_defs.h>
  54. #include <pcrecpp.h>
  55. #define DEFAULT_MAX_ROTATED_LOGS 4
  56. struct log_device_t {
  57. const char* device;
  58. bool binary;
  59. struct logger* logger;
  60. struct logger_list* logger_list;
  61. bool printed;
  62. log_device_t* next;
  63. log_device_t(const char* d, bool b) {
  64. device = d;
  65. binary = b;
  66. next = nullptr;
  67. printed = false;
  68. logger = nullptr;
  69. logger_list = nullptr;
  70. }
  71. };
  72. struct android_logcat_context_internal {
  73. // status
  74. volatile std::atomic_int retval; // valid if thread_stopped set
  75. // Arguments passed in, or copies and storage thereof if a thread.
  76. int argc;
  77. char* const* argv;
  78. char* const* envp;
  79. std::vector<std::string> args;
  80. std::vector<const char*> argv_hold;
  81. std::vector<std::string> envs;
  82. std::vector<const char*> envp_hold;
  83. int output_fd; // duplication of fileno(output) (below)
  84. int error_fd; // duplication of fileno(error) (below)
  85. // library
  86. int fds[2]; // From popen call
  87. FILE* output; // everything writes to fileno(output), buffer unused
  88. FILE* error; // unless error == output.
  89. pthread_t thr;
  90. volatile std::atomic_bool stop; // quick exit flag
  91. volatile std::atomic_bool thread_stopped;
  92. bool stderr_null; // shell "2>/dev/null"
  93. bool stderr_stdout; // shell "2>&1"
  94. // global variables
  95. AndroidLogFormat* logformat;
  96. const char* outputFileName;
  97. // 0 means "no log rotation"
  98. size_t logRotateSizeKBytes;
  99. // 0 means "unbounded"
  100. size_t maxRotatedLogs;
  101. size_t outByteCount;
  102. int printBinary;
  103. int devCount; // >1 means multiple
  104. pcrecpp::RE* regex;
  105. log_device_t* devices;
  106. EventTagMap* eventTagMap;
  107. // 0 means "infinite"
  108. size_t maxCount;
  109. size_t printCount;
  110. bool printItAnyways;
  111. bool debug;
  112. bool hasOpenedEventTagMap;
  113. };
  114. // Creates a context associated with this logcat instance
  115. android_logcat_context create_android_logcat() {
  116. android_logcat_context_internal* context;
  117. context = (android_logcat_context_internal*)calloc(
  118. 1, sizeof(android_logcat_context_internal));
  119. if (!context) return nullptr;
  120. context->fds[0] = -1;
  121. context->fds[1] = -1;
  122. context->output_fd = -1;
  123. context->error_fd = -1;
  124. context->maxRotatedLogs = DEFAULT_MAX_ROTATED_LOGS;
  125. context->argv_hold.clear();
  126. context->args.clear();
  127. context->envp_hold.clear();
  128. context->envs.clear();
  129. return (android_logcat_context)context;
  130. }
  131. // logd prefixes records with a length field
  132. #define RECORD_LENGTH_FIELD_SIZE_BYTES sizeof(uint32_t)
  133. namespace android {
  134. enum helpType { HELP_FALSE, HELP_TRUE, HELP_FORMAT };
  135. // if showHelp is set, newline required in fmt statement to transition to usage
  136. static void logcat_panic(android_logcat_context_internal* context,
  137. enum helpType showHelp, const char* fmt, ...)
  138. __printflike(3, 4);
  139. static int openLogFile(const char* pathname) {
  140. return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  141. }
  142. static void close_output(android_logcat_context_internal* context) {
  143. // split output_from_error
  144. if (context->error == context->output) {
  145. context->output = nullptr;
  146. context->output_fd = -1;
  147. }
  148. if (context->error && (context->output_fd == fileno(context->error))) {
  149. context->output_fd = -1;
  150. }
  151. if (context->output_fd == context->error_fd) {
  152. context->output_fd = -1;
  153. }
  154. // close output channel
  155. if (context->output) {
  156. if (context->output != stdout) {
  157. if (context->output_fd == fileno(context->output)) {
  158. context->output_fd = -1;
  159. }
  160. if (context->fds[1] == fileno(context->output)) {
  161. context->fds[1] = -1;
  162. }
  163. fclose(context->output);
  164. }
  165. context->output = nullptr;
  166. }
  167. if (context->output_fd >= 0) {
  168. if (context->output_fd != fileno(stdout)) {
  169. if (context->fds[1] == context->output_fd) {
  170. context->fds[1] = -1;
  171. }
  172. close(context->output_fd);
  173. }
  174. context->output_fd = -1;
  175. }
  176. }
  177. static void close_error(android_logcat_context_internal* context) {
  178. // split error_from_output
  179. if (context->output == context->error) {
  180. context->error = nullptr;
  181. context->error_fd = -1;
  182. }
  183. if (context->output && (context->error_fd == fileno(context->output))) {
  184. context->error_fd = -1;
  185. }
  186. if (context->error_fd == context->output_fd) {
  187. context->error_fd = -1;
  188. }
  189. // close error channel
  190. if (context->error) {
  191. if ((context->error != stderr) && (context->error != stdout)) {
  192. if (context->error_fd == fileno(context->error)) {
  193. context->error_fd = -1;
  194. }
  195. if (context->fds[1] == fileno(context->error)) {
  196. context->fds[1] = -1;
  197. }
  198. fclose(context->error);
  199. }
  200. context->error = nullptr;
  201. }
  202. if (context->error_fd >= 0) {
  203. if ((context->error_fd != fileno(stdout)) &&
  204. (context->error_fd != fileno(stderr))) {
  205. if (context->fds[1] == context->error_fd) context->fds[1] = -1;
  206. close(context->error_fd);
  207. }
  208. context->error_fd = -1;
  209. }
  210. }
  211. static void rotateLogs(android_logcat_context_internal* context) {
  212. int err;
  213. // Can't rotate logs if we're not outputting to a file
  214. if (!context->outputFileName) return;
  215. close_output(context);
  216. // Compute the maximum number of digits needed to count up to
  217. // maxRotatedLogs in decimal. eg:
  218. // maxRotatedLogs == 30
  219. // -> log10(30) == 1.477
  220. // -> maxRotationCountDigits == 2
  221. int maxRotationCountDigits =
  222. (context->maxRotatedLogs > 0)
  223. ? (int)(floor(log10(context->maxRotatedLogs) + 1))
  224. : 0;
  225. for (int i = context->maxRotatedLogs; i > 0; i--) {
  226. std::string file1 = android::base::StringPrintf(
  227. "%s.%.*d", context->outputFileName, maxRotationCountDigits, i);
  228. std::string file0;
  229. if (!(i - 1)) {
  230. file0 = android::base::StringPrintf("%s", context->outputFileName);
  231. } else {
  232. file0 =
  233. android::base::StringPrintf("%s.%.*d", context->outputFileName,
  234. maxRotationCountDigits, i - 1);
  235. }
  236. if (!file0.length() || !file1.length()) {
  237. perror("while rotating log files");
  238. break;
  239. }
  240. err = rename(file0.c_str(), file1.c_str());
  241. if (err < 0 && errno != ENOENT) {
  242. perror("while rotating log files");
  243. }
  244. }
  245. context->output_fd = openLogFile(context->outputFileName);
  246. if (context->output_fd < 0) {
  247. logcat_panic(context, HELP_FALSE, "couldn't open output file");
  248. return;
  249. }
  250. context->output = fdopen(context->output_fd, "web");
  251. if (!context->output) {
  252. logcat_panic(context, HELP_FALSE, "couldn't fdopen output file");
  253. return;
  254. }
  255. if (context->stderr_stdout) {
  256. close_error(context);
  257. context->error = context->output;
  258. context->error_fd = context->output_fd;
  259. }
  260. context->outByteCount = 0;
  261. }
  262. void printBinary(android_logcat_context_internal* context, struct log_msg* buf) {
  263. size_t size = buf->len();
  264. TEMP_FAILURE_RETRY(write(context->output_fd, buf, size));
  265. }
  266. static bool regexOk(android_logcat_context_internal* context,
  267. const AndroidLogEntry& entry) {
  268. if (!context->regex) return true;
  269. std::string messageString(entry.message, entry.messageLen);
  270. return context->regex->PartialMatch(messageString);
  271. }
  272. static void processBuffer(android_logcat_context_internal* context,
  273. log_device_t* dev, struct log_msg* buf) {
  274. int bytesWritten = 0;
  275. int err;
  276. AndroidLogEntry entry;
  277. char binaryMsgBuf[1024];
  278. if (dev->binary) {
  279. if (!context->eventTagMap && !context->hasOpenedEventTagMap) {
  280. context->eventTagMap = android_openEventTagMap(nullptr);
  281. context->hasOpenedEventTagMap = true;
  282. }
  283. err = android_log_processBinaryLogBuffer(
  284. &buf->entry_v1, &entry, context->eventTagMap, binaryMsgBuf,
  285. sizeof(binaryMsgBuf));
  286. // printf(">>> pri=%d len=%d msg='%s'\n",
  287. // entry.priority, entry.messageLen, entry.message);
  288. } else {
  289. err = android_log_processLogBuffer(&buf->entry_v1, &entry);
  290. }
  291. if ((err < 0) && !context->debug) return;
  292. if (android_log_shouldPrintLine(
  293. context->logformat, std::string(entry.tag, entry.tagLen).c_str(),
  294. entry.priority)) {
  295. bool match = regexOk(context, entry);
  296. context->printCount += match;
  297. if (match || context->printItAnyways) {
  298. bytesWritten = android_log_printLogLine(context->logformat,
  299. context->output_fd, &entry);
  300. if (bytesWritten < 0) {
  301. logcat_panic(context, HELP_FALSE, "output error");
  302. return;
  303. }
  304. }
  305. }
  306. context->outByteCount += bytesWritten;
  307. if (context->logRotateSizeKBytes > 0 &&
  308. (context->outByteCount / 1024) >= context->logRotateSizeKBytes) {
  309. rotateLogs(context);
  310. }
  311. }
  312. static void maybePrintStart(android_logcat_context_internal* context,
  313. log_device_t* dev, bool printDividers) {
  314. if (!dev->printed || printDividers) {
  315. if (context->devCount > 1 && !context->printBinary) {
  316. char buf[1024];
  317. snprintf(buf, sizeof(buf), "--------- %s %s\n",
  318. dev->printed ? "switch to" : "beginning of", dev->device);
  319. if (write(context->output_fd, buf, strlen(buf)) < 0) {
  320. logcat_panic(context, HELP_FALSE, "output error");
  321. return;
  322. }
  323. }
  324. dev->printed = true;
  325. }
  326. }
  327. static void setupOutputAndSchedulingPolicy(
  328. android_logcat_context_internal* context, bool blocking) {
  329. if (!context->outputFileName) return;
  330. if (blocking) {
  331. // Lower priority and set to batch scheduling if we are saving
  332. // the logs into files and taking continuous content.
  333. if ((set_sched_policy(0, SP_BACKGROUND) < 0) && context->error) {
  334. fprintf(context->error,
  335. "failed to set background scheduling policy\n");
  336. }
  337. struct sched_param param;
  338. memset(&param, 0, sizeof(param));
  339. if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
  340. fprintf(stderr, "failed to set to batch scheduler\n");
  341. }
  342. if ((setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) &&
  343. context->error) {
  344. fprintf(context->error, "failed set to priority\n");
  345. }
  346. }
  347. close_output(context);
  348. context->output_fd = openLogFile(context->outputFileName);
  349. if (context->output_fd < 0) {
  350. logcat_panic(context, HELP_FALSE, "couldn't open output file");
  351. return;
  352. }
  353. struct stat statbuf;
  354. if (fstat(context->output_fd, &statbuf) == -1) {
  355. close_output(context);
  356. logcat_panic(context, HELP_FALSE, "couldn't get output file stat\n");
  357. return;
  358. }
  359. if ((size_t)statbuf.st_size > SIZE_MAX || statbuf.st_size < 0) {
  360. close_output(context);
  361. logcat_panic(context, HELP_FALSE, "invalid output file stat\n");
  362. return;
  363. }
  364. context->output = fdopen(context->output_fd, "web");
  365. context->outByteCount = statbuf.st_size;
  366. }
  367. // clang-format off
  368. static void show_help(android_logcat_context_internal* context) {
  369. if (!context->error) return;
  370. const char* cmd = strrchr(context->argv[0], '/');
  371. cmd = cmd ? cmd + 1 : context->argv[0];
  372. fprintf(context->error, "Usage: %s [options] [filterspecs]\n", cmd);
  373. fprintf(context->error, "options include:\n"
  374. " -s Set default filter to silent. Equivalent to filterspec '*:S'\n"
  375. " -f <file>, --file=<file> Log to file. Default is stdout\n"
  376. " -r <kbytes>, --rotate-kbytes=<kbytes>\n"
  377. " Rotate log every kbytes. Requires -f option\n"
  378. " -n <count>, --rotate-count=<count>\n"
  379. " Sets max number of rotated logs to <count>, default 4\n"
  380. " --id=<id> If the signature id for logging to file changes, then clear\n"
  381. " the fileset and continue\n"
  382. " -v <format>, --format=<format>\n"
  383. " Sets log print format verb and adverbs, where <format> is:\n"
  384. " brief help long process raw tag thread threadtime time\n"
  385. " and individually flagged modifying adverbs can be added:\n"
  386. " color descriptive epoch monotonic printable uid\n"
  387. " usec UTC year zone\n"
  388. " Multiple -v parameters or comma separated list of format and\n"
  389. " format modifiers are allowed.\n"
  390. // private and undocumented nsec, no signal, too much noise
  391. // useful for -T or -t <timestamp> accurate testing though.
  392. " -D, --dividers Print dividers between each log buffer\n"
  393. " -c, --clear Clear (flush) the entire log and exit\n"
  394. " if Log to File specified, clear fileset instead\n"
  395. " -d Dump the log and then exit (don't block)\n"
  396. " -e <expr>, --regex=<expr>\n"
  397. " Only print lines where the log message matches <expr>\n"
  398. " where <expr> is a Perl-compatible regular expression\n"
  399. // Leave --head undocumented as alias for -m
  400. " -m <count>, --max-count=<count>\n"
  401. " Quit after printing <count> lines. This is meant to be\n"
  402. " paired with --regex, but will work on its own.\n"
  403. " --print Paired with --regex and --max-count to let content bypass\n"
  404. " regex filter but still stop at number of matches.\n"
  405. // Leave --tail undocumented as alias for -t
  406. " -t <count> Print only the most recent <count> lines (implies -d)\n"
  407. " -t '<time>' Print most recent lines since specified time (implies -d)\n"
  408. " -T <count> Print only the most recent <count> lines (does not imply -d)\n"
  409. " -T '<time>' Print most recent lines since specified time (not imply -d)\n"
  410. " count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'\n"
  411. " 'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format\n"
  412. " -g, --buffer-size Get the size of the ring buffer.\n"
  413. " -G <size>, --buffer-size=<size>\n"
  414. " Set size of log ring buffer, may suffix with K or M.\n"
  415. " -L, --last Dump logs from prior to last reboot\n"
  416. " -b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',\n"
  417. " 'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
  418. " Additionally, 'kernel' for userdebug and eng builds, and\n"
  419. " 'security' for Device Owner installations.\n"
  420. " Multiple -b parameters or comma separated list of buffers are\n"
  421. " allowed. Buffers interleaved. Default -b main,system,crash.\n"
  422. " -B, --binary Output the log in binary.\n"
  423. " -S, --statistics Output statistics.\n"
  424. " -p, --prune Print prune white and ~black list. Service is specified as\n"
  425. " UID, UID/PID or /PID. Weighed for quicker pruning if prefix\n"
  426. " with ~, otherwise weighed for longevity if unadorned. All\n"
  427. " other pruning activity is oldest first. Special case ~!\n"
  428. " represents an automatic quicker pruning for the noisiest\n"
  429. " UID as determined by the current statistics.\n"
  430. " -P '<list> ...', --prune='<list> ...'\n"
  431. " Set prune white and ~black list, using same format as\n"
  432. " listed above. Must be quoted.\n"
  433. " --pid=<pid> Only prints logs from the given pid.\n"
  434. // Check ANDROID_LOG_WRAP_DEFAULT_TIMEOUT value for match to 2 hours
  435. " --wrap Sleep for 2 hours or when buffer about to wrap whichever\n"
  436. " comes first. Improves efficiency of polling by providing\n"
  437. " an about-to-wrap wakeup.\n");
  438. fprintf(context->error, "\nfilterspecs are a series of \n"
  439. " <tag>[:priority]\n\n"
  440. "where <tag> is a log component tag (or * for all) and priority is:\n"
  441. " V Verbose (default for <tag>)\n"
  442. " D Debug (default for '*')\n"
  443. " I Info\n"
  444. " W Warn\n"
  445. " E Error\n"
  446. " F Fatal\n"
  447. " S Silent (suppress all output)\n"
  448. "\n'*' by itself means '*:D' and <tag> by itself means <tag>:V.\n"
  449. "If no '*' filterspec or -s on command line, all filter defaults to '*:V'.\n"
  450. "eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.\n"
  451. "\nIf not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.\n"
  452. "\nIf not specified with -v on command line, format is set from ANDROID_PRINTF_LOG\n"
  453. "or defaults to \"threadtime\"\n\n");
  454. }
  455. static void show_format_help(android_logcat_context_internal* context) {
  456. if (!context->error) return;
  457. fprintf(context->error,
  458. "-v <format>, --format=<format> options:\n"
  459. " Sets log print format verb and adverbs, where <format> is:\n"
  460. " brief long process raw tag thread threadtime time\n"
  461. " and individually flagged modifying adverbs can be added:\n"
  462. " color descriptive epoch monotonic printable uid usec UTC year zone\n"
  463. "\nSingle format verbs:\n"
  464. " brief — Display priority/tag and PID of the process issuing the message.\n"
  465. " long — Display all metadata fields, separate messages with blank lines.\n"
  466. " process — Display PID only.\n"
  467. " raw — Display the raw log message, with no other metadata fields.\n"
  468. " tag — Display the priority/tag only.\n"
  469. " thread — Display priority, PID and TID of process issuing the message.\n"
  470. " threadtime — Display the date, invocation time, priority, tag, and the PID\n"
  471. " and TID of the thread issuing the message. (the default format).\n"
  472. " time — Display the date, invocation time, priority/tag, and PID of the\n"
  473. " process issuing the message.\n"
  474. "\nAdverb modifiers can be used in combination:\n"
  475. " color — Display in highlighted color to match priority. i.e. \x1B[38;5;231mVERBOSE\n"
  476. " \x1B[38;5;75mDEBUG \x1B[38;5;40mINFO \x1B[38;5;166mWARNING \x1B[38;5;196mERROR FATAL\x1B[0m\n"
  477. " descriptive — events logs only, descriptions from event-log-tags database.\n"
  478. " epoch — Display time as seconds since Jan 1 1970.\n"
  479. " monotonic — Display time as cpu seconds since last boot.\n"
  480. " printable — Ensure that any binary logging content is escaped.\n"
  481. " uid — If permitted, display the UID or Android ID of logged process.\n"
  482. " usec — Display time down the microsecond precision.\n"
  483. " UTC — Display time as UTC.\n"
  484. " year — Add the year to the displayed time.\n"
  485. " zone — Add the local timezone to the displayed time.\n"
  486. " \"<zone>\" — Print using this public named timezone (experimental).\n\n"
  487. );
  488. }
  489. // clang-format on
  490. static int setLogFormat(android_logcat_context_internal* context,
  491. const char* formatString) {
  492. AndroidLogPrintFormat format;
  493. format = android_log_formatFromString(formatString);
  494. // invalid string?
  495. if (format == FORMAT_OFF) return -1;
  496. return android_log_setPrintFormat(context->logformat, format);
  497. }
  498. static std::pair<unsigned long, const char*> format_of_size(unsigned long value) {
  499. static const char multipliers[][3] = {{""}, {"Ki"}, {"Mi"}, {"Gi"}};
  500. size_t i;
  501. for (i = 0;
  502. (i < sizeof(multipliers) / sizeof(multipliers[0])) && (value >= 1024);
  503. value /= 1024, ++i)
  504. ;
  505. return std::make_pair(value, multipliers[i]);
  506. }
  507. // String to unsigned int, returns -1 if it fails
  508. static bool getSizeTArg(const char* ptr, size_t* val, size_t min = 0,
  509. size_t max = SIZE_MAX) {
  510. if (!ptr) return false;
  511. char* endp;
  512. errno = 0;
  513. size_t ret = (size_t)strtoll(ptr, &endp, 0);
  514. if (endp[0] || errno) return false;
  515. if ((ret > max) || (ret < min)) return false;
  516. *val = ret;
  517. return true;
  518. }
  519. static void logcat_panic(android_logcat_context_internal* context,
  520. enum helpType showHelp, const char* fmt, ...) {
  521. context->retval = EXIT_FAILURE;
  522. if (!context->error) {
  523. context->stop = true;
  524. return;
  525. }
  526. va_list args;
  527. va_start(args, fmt);
  528. vfprintf(context->error, fmt, args);
  529. va_end(args);
  530. switch (showHelp) {
  531. case HELP_TRUE:
  532. show_help(context);
  533. break;
  534. case HELP_FORMAT:
  535. show_format_help(context);
  536. break;
  537. case HELP_FALSE:
  538. default:
  539. break;
  540. }
  541. context->stop = true;
  542. }
  543. static char* parseTime(log_time& t, const char* cp) {
  544. char* ep = t.strptime(cp, "%m-%d %H:%M:%S.%q");
  545. if (ep) return ep;
  546. ep = t.strptime(cp, "%Y-%m-%d %H:%M:%S.%q");
  547. if (ep) return ep;
  548. return t.strptime(cp, "%s.%q");
  549. }
  550. // Find last logged line in <outputFileName>, or <outputFileName>.1
  551. static log_time lastLogTime(const char* outputFileName) {
  552. log_time retval(log_time::EPOCH);
  553. if (!outputFileName) return retval;
  554. std::string directory;
  555. const char* file = strrchr(outputFileName, '/');
  556. if (!file) {
  557. directory = ".";
  558. file = outputFileName;
  559. } else {
  560. directory = std::string(outputFileName, file - outputFileName);
  561. ++file;
  562. }
  563. std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(directory.c_str()),
  564. closedir);
  565. if (!dir.get()) return retval;
  566. log_time now(android_log_clockid());
  567. size_t len = strlen(file);
  568. log_time modulo(0, NS_PER_SEC);
  569. struct dirent* dp;
  570. while (!!(dp = readdir(dir.get()))) {
  571. if ((dp->d_type != DT_REG) || !!strncmp(dp->d_name, file, len) ||
  572. (dp->d_name[len] && ((dp->d_name[len] != '.') ||
  573. (strtoll(dp->d_name + 1, nullptr, 10) != 1)))) {
  574. continue;
  575. }
  576. std::string file_name = directory;
  577. file_name += "/";
  578. file_name += dp->d_name;
  579. std::string file;
  580. if (!android::base::ReadFileToString(file_name, &file)) continue;
  581. bool found = false;
  582. for (const auto& line : android::base::Split(file, "\n")) {
  583. log_time t(log_time::EPOCH);
  584. char* ep = parseTime(t, line.c_str());
  585. if (!ep || (*ep != ' ')) continue;
  586. // determine the time precision of the logs (eg: msec or usec)
  587. for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
  588. if (t.tv_nsec % (mod * 10)) {
  589. modulo.tv_nsec = mod;
  590. break;
  591. }
  592. }
  593. // We filter any times later than current as we may not have the
  594. // year stored with each log entry. Also, since it is possible for
  595. // entries to be recorded out of order (very rare) we select the
  596. // maximum we find just in case.
  597. if ((t < now) && (t > retval)) {
  598. retval = t;
  599. found = true;
  600. }
  601. }
  602. // We count on the basename file to be the definitive end, so stop here.
  603. if (!dp->d_name[len] && found) break;
  604. }
  605. if (retval == log_time::EPOCH) return retval;
  606. // tail_time prints matching or higher, round up by the modulo to prevent
  607. // a replay of the last entry we have just checked.
  608. retval += modulo;
  609. return retval;
  610. }
  611. const char* getenv(android_logcat_context_internal* context, const char* name) {
  612. if (!context->envp || !name || !*name) return nullptr;
  613. for (size_t len = strlen(name), i = 0; context->envp[i]; ++i) {
  614. if (strncmp(context->envp[i], name, len)) continue;
  615. if (context->envp[i][len] == '=') return &context->envp[i][len + 1];
  616. }
  617. return nullptr;
  618. }
  619. } // namespace android
  620. void reportErrorName(const char** current, const char* name,
  621. bool blockSecurity) {
  622. if (*current) return;
  623. if (!blockSecurity || (android_name_to_log_id(name) != LOG_ID_SECURITY)) {
  624. *current = name;
  625. }
  626. }
  627. static int __logcat(android_logcat_context_internal* context) {
  628. using namespace android;
  629. int err;
  630. bool hasSetLogFormat = false;
  631. bool clearLog = false;
  632. bool allSelected = false;
  633. bool getLogSize = false;
  634. bool getPruneList = false;
  635. bool printStatistics = false;
  636. bool printDividers = false;
  637. unsigned long setLogSize = 0;
  638. const char* setPruneList = nullptr;
  639. const char* setId = nullptr;
  640. int mode = ANDROID_LOG_RDONLY;
  641. std::string forceFilters;
  642. log_device_t* dev;
  643. struct logger_list* logger_list;
  644. size_t tail_lines = 0;
  645. log_time tail_time(log_time::EPOCH);
  646. size_t pid = 0;
  647. bool got_t = false;
  648. // object instantiations before goto's can happen
  649. log_device_t unexpected("unexpected", false);
  650. const char* openDeviceFail = nullptr;
  651. const char* clearFail = nullptr;
  652. const char* setSizeFail = nullptr;
  653. const char* getSizeFail = nullptr;
  654. int argc = context->argc;
  655. char* const* argv = context->argv;
  656. context->output = stdout;
  657. context->error = stderr;
  658. for (int i = 0; i < argc; ++i) {
  659. // Simulate shell stderr redirect parsing
  660. if ((argv[i][0] != '2') || (argv[i][1] != '>')) continue;
  661. // Append to file not implemented, just open file
  662. size_t skip = (argv[i][2] == '>') + 2;
  663. if (!strcmp(&argv[i][skip], "/dev/null")) {
  664. context->stderr_null = true;
  665. } else if (!strcmp(&argv[i][skip], "&1")) {
  666. context->stderr_stdout = true;
  667. } else {
  668. // stderr file redirections are not supported
  669. fprintf(context->stderr_stdout ? stdout : stderr,
  670. "stderr redirection to file %s unsupported, skipping\n",
  671. &argv[i][skip]);
  672. }
  673. // Only the first one
  674. break;
  675. }
  676. const char* filename = nullptr;
  677. for (int i = 0; i < argc; ++i) {
  678. // Simulate shell stdout redirect parsing
  679. if (argv[i][0] != '>') continue;
  680. // Append to file not implemented, just open file
  681. filename = &argv[i][(argv[i][1] == '>') + 1];
  682. // Only the first one
  683. break;
  684. }
  685. // Deal with setting up file descriptors and FILE pointers
  686. if (context->error_fd >= 0) { // Is an error file descriptor supplied?
  687. if (context->error_fd == context->output_fd) {
  688. context->stderr_stdout = true;
  689. } else if (context->stderr_null) { // redirection told us to close it
  690. close(context->error_fd);
  691. context->error_fd = -1;
  692. } else { // All Ok, convert error to a FILE pointer
  693. context->error = fdopen(context->error_fd, "web");
  694. if (!context->error) {
  695. context->retval = -errno;
  696. fprintf(context->stderr_stdout ? stdout : stderr,
  697. "Failed to fdopen(error_fd=%d) %s\n", context->error_fd,
  698. strerror(errno));
  699. goto exit;
  700. }
  701. }
  702. }
  703. if (context->output_fd >= 0) { // Is an output file descriptor supplied?
  704. if (filename) { // redirect to file, close supplied file descriptor.
  705. close(context->output_fd);
  706. context->output_fd = -1;
  707. } else { // All Ok, convert output to a FILE pointer
  708. context->output = fdopen(context->output_fd, "web");
  709. if (!context->output) {
  710. context->retval = -errno;
  711. fprintf(context->stderr_stdout ? stdout : context->error,
  712. "Failed to fdopen(output_fd=%d) %s\n",
  713. context->output_fd, strerror(errno));
  714. goto exit;
  715. }
  716. }
  717. }
  718. if (filename) { // We supplied an output file redirected in command line
  719. context->output = fopen(filename, "web");
  720. }
  721. // Deal with 2>&1
  722. if (context->stderr_stdout) context->error = context->output;
  723. // Deal with 2>/dev/null
  724. if (context->stderr_null) {
  725. context->error_fd = -1;
  726. context->error = nullptr;
  727. }
  728. // Only happens if output=stdout or output=filename
  729. if ((context->output_fd < 0) && context->output) {
  730. context->output_fd = fileno(context->output);
  731. }
  732. // Only happens if error=stdout || error=stderr
  733. if ((context->error_fd < 0) && context->error) {
  734. context->error_fd = fileno(context->error);
  735. }
  736. context->logformat = android_log_format_new();
  737. if (argc == 2 && !strcmp(argv[1], "--help")) {
  738. show_help(context);
  739. context->retval = EXIT_SUCCESS;
  740. goto exit;
  741. }
  742. // meant to catch comma-delimited values, but cast a wider
  743. // net for stability dealing with possible mistaken inputs.
  744. static const char delimiters[] = ",:; \t\n\r\f";
  745. optind = 0;
  746. while (true) {
  747. int option_index = 0;
  748. // list of long-argument only strings for later comparison
  749. static const char pid_str[] = "pid";
  750. static const char debug_str[] = "debug";
  751. static const char id_str[] = "id";
  752. static const char wrap_str[] = "wrap";
  753. static const char print_str[] = "print";
  754. // clang-format off
  755. static const struct option long_options[] = {
  756. { "binary", no_argument, nullptr, 'B' },
  757. { "buffer", required_argument, nullptr, 'b' },
  758. { "buffer-size", optional_argument, nullptr, 'g' },
  759. { "clear", no_argument, nullptr, 'c' },
  760. { debug_str, no_argument, nullptr, 0 },
  761. { "dividers", no_argument, nullptr, 'D' },
  762. { "file", required_argument, nullptr, 'f' },
  763. { "format", required_argument, nullptr, 'v' },
  764. // hidden and undocumented reserved alias for --regex
  765. { "grep", required_argument, nullptr, 'e' },
  766. // hidden and undocumented reserved alias for --max-count
  767. { "head", required_argument, nullptr, 'm' },
  768. { "help", no_argument, nullptr, 'h' },
  769. { id_str, required_argument, nullptr, 0 },
  770. { "last", no_argument, nullptr, 'L' },
  771. { "max-count", required_argument, nullptr, 'm' },
  772. { pid_str, required_argument, nullptr, 0 },
  773. { print_str, no_argument, nullptr, 0 },
  774. { "prune", optional_argument, nullptr, 'p' },
  775. { "regex", required_argument, nullptr, 'e' },
  776. { "rotate-count", required_argument, nullptr, 'n' },
  777. { "rotate-kbytes", required_argument, nullptr, 'r' },
  778. { "statistics", no_argument, nullptr, 'S' },
  779. // hidden and undocumented reserved alias for -t
  780. { "tail", required_argument, nullptr, 't' },
  781. // support, but ignore and do not document, the optional argument
  782. { wrap_str, optional_argument, nullptr, 0 },
  783. { nullptr, 0, nullptr, 0 }
  784. };
  785. // clang-format on
  786. int c = getopt_long(argc, argv, ":cdDhLt:T:gG:sQf:r:n:v:b:BSpP:m:e:", long_options,
  787. &option_index);
  788. if (c == -1) break;
  789. switch (c) {
  790. case 0:
  791. // only long options
  792. if (long_options[option_index].name == pid_str) {
  793. // ToDo: determine runtime PID_MAX?
  794. if (!getSizeTArg(optarg, &pid, 1)) {
  795. logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
  796. long_options[option_index].name, optarg);
  797. goto exit;
  798. }
  799. break;
  800. }
  801. if (long_options[option_index].name == wrap_str) {
  802. mode |= ANDROID_LOG_WRAP | ANDROID_LOG_RDONLY |
  803. ANDROID_LOG_NONBLOCK;
  804. // ToDo: implement API that supports setting a wrap timeout
  805. size_t dummy = ANDROID_LOG_WRAP_DEFAULT_TIMEOUT;
  806. if (optarg && !getSizeTArg(optarg, &dummy, 1)) {
  807. logcat_panic(context, HELP_TRUE, "%s %s out of range\n",
  808. long_options[option_index].name, optarg);
  809. goto exit;
  810. }
  811. if ((dummy != ANDROID_LOG_WRAP_DEFAULT_TIMEOUT) &&
  812. context->error) {
  813. fprintf(context->error,
  814. "WARNING: %s %u seconds, ignoring %zu\n",
  815. long_options[option_index].name,
  816. ANDROID_LOG_WRAP_DEFAULT_TIMEOUT, dummy);
  817. }
  818. break;
  819. }
  820. if (long_options[option_index].name == print_str) {
  821. context->printItAnyways = true;
  822. break;
  823. }
  824. if (long_options[option_index].name == debug_str) {
  825. context->debug = true;
  826. break;
  827. }
  828. if (long_options[option_index].name == id_str) {
  829. setId = (optarg && optarg[0]) ? optarg : nullptr;
  830. }
  831. break;
  832. case 's':
  833. // default to all silent
  834. android_log_addFilterRule(context->logformat, "*:s");
  835. break;
  836. case 'c':
  837. clearLog = true;
  838. mode |= ANDROID_LOG_WRONLY;
  839. break;
  840. case 'L':
  841. mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_PSTORE |
  842. ANDROID_LOG_NONBLOCK;
  843. break;
  844. case 'd':
  845. mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
  846. break;
  847. case 't':
  848. got_t = true;
  849. mode |= ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK;
  850. FALLTHROUGH_INTENDED;
  851. case 'T':
  852. if (strspn(optarg, "0123456789") != strlen(optarg)) {
  853. char* cp = parseTime(tail_time, optarg);
  854. if (!cp) {
  855. logcat_panic(context, HELP_FALSE, "-%c \"%s\" not in time format\n", c,
  856. optarg);
  857. goto exit;
  858. }
  859. if (*cp) {
  860. char ch = *cp;
  861. *cp = '\0';
  862. if (context->error) {
  863. fprintf(context->error, "WARNING: -%c \"%s\"\"%c%s\" time truncated\n",
  864. c, optarg, ch, cp + 1);
  865. }
  866. *cp = ch;
  867. }
  868. } else {
  869. if (!getSizeTArg(optarg, &tail_lines, 1)) {
  870. if (context->error) {
  871. fprintf(context->error, "WARNING: -%c %s invalid, setting to 1\n", c,
  872. optarg);
  873. }
  874. tail_lines = 1;
  875. }
  876. }
  877. break;
  878. case 'D':
  879. printDividers = true;
  880. break;
  881. case 'e':
  882. context->regex = new pcrecpp::RE(optarg);
  883. break;
  884. case 'm': {
  885. if (!getSizeTArg(optarg, &context->maxCount)) {
  886. logcat_panic(context, HELP_FALSE,
  887. "-%c \"%s\" isn't an integer greater than zero\n", c, optarg);
  888. goto exit;
  889. }
  890. } break;
  891. case 'g':
  892. if (!optarg) {
  893. getLogSize = true;
  894. break;
  895. }
  896. FALLTHROUGH_INTENDED;
  897. case 'G': {
  898. char* cp;
  899. if (strtoll(optarg, &cp, 0) > 0) {
  900. setLogSize = strtoll(optarg, &cp, 0);
  901. } else {
  902. setLogSize = 0;
  903. }
  904. switch (*cp) {
  905. case 'g':
  906. case 'G':
  907. setLogSize *= 1024;
  908. FALLTHROUGH_INTENDED;
  909. case 'm':
  910. case 'M':
  911. setLogSize *= 1024;
  912. FALLTHROUGH_INTENDED;
  913. case 'k':
  914. case 'K':
  915. setLogSize *= 1024;
  916. FALLTHROUGH_INTENDED;
  917. case '\0':
  918. break;
  919. default:
  920. setLogSize = 0;
  921. }
  922. if (!setLogSize) {
  923. logcat_panic(context, HELP_FALSE,
  924. "ERROR: -G <num><multiplier>\n");
  925. goto exit;
  926. }
  927. } break;
  928. case 'p':
  929. if (!optarg) {
  930. getPruneList = true;
  931. break;
  932. }
  933. FALLTHROUGH_INTENDED;
  934. case 'P':
  935. setPruneList = optarg;
  936. break;
  937. case 'b': {
  938. std::unique_ptr<char, void (*)(void*)> buffers(strdup(optarg), free);
  939. char* arg = buffers.get();
  940. unsigned idMask = 0;
  941. char* sv = nullptr; // protect against -ENOMEM above
  942. while (!!(arg = strtok_r(arg, delimiters, &sv))) {
  943. if (!strcmp(arg, "default")) {
  944. idMask |= (1 << LOG_ID_MAIN) | (1 << LOG_ID_SYSTEM) |
  945. (1 << LOG_ID_CRASH);
  946. } else if (!strcmp(arg, "all")) {
  947. allSelected = true;
  948. idMask = (unsigned)-1;
  949. } else {
  950. log_id_t log_id = android_name_to_log_id(arg);
  951. const char* name = android_log_id_to_name(log_id);
  952. if (!!strcmp(name, arg)) {
  953. logcat_panic(context, HELP_TRUE,
  954. "unknown buffer %s\n", arg);
  955. goto exit;
  956. }
  957. if (log_id == LOG_ID_SECURITY) allSelected = false;
  958. idMask |= (1 << log_id);
  959. }
  960. arg = nullptr;
  961. }
  962. for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
  963. const char* name = android_log_id_to_name((log_id_t)i);
  964. log_id_t log_id = android_name_to_log_id(name);
  965. if (log_id != (log_id_t)i) continue;
  966. if (!(idMask & (1 << i))) continue;
  967. bool found = false;
  968. for (dev = context->devices; dev; dev = dev->next) {
  969. if (!strcmp(name, dev->device)) {
  970. found = true;
  971. break;
  972. }
  973. if (!dev->next) break;
  974. }
  975. if (found) continue;
  976. bool binary = !strcmp(name, "events") ||
  977. !strcmp(name, "security") ||
  978. !strcmp(name, "stats");
  979. log_device_t* d = new log_device_t(name, binary);
  980. if (dev) {
  981. dev->next = d;
  982. dev = d;
  983. } else {
  984. context->devices = dev = d;
  985. }
  986. context->devCount++;
  987. }
  988. } break;
  989. case 'B':
  990. context->printBinary = 1;
  991. break;
  992. case 'f':
  993. if ((tail_time == log_time::EPOCH) && !tail_lines) {
  994. tail_time = lastLogTime(optarg);
  995. }
  996. // redirect output to a file
  997. context->outputFileName = optarg;
  998. break;
  999. case 'r':
  1000. if (!getSizeTArg(optarg, &context->logRotateSizeKBytes, 1)) {
  1001. logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -r\n", optarg);
  1002. goto exit;
  1003. }
  1004. break;
  1005. case 'n':
  1006. if (!getSizeTArg(optarg, &context->maxRotatedLogs, 1)) {
  1007. logcat_panic(context, HELP_TRUE, "Invalid parameter \"%s\" to -n\n", optarg);
  1008. goto exit;
  1009. }
  1010. break;
  1011. case 'v': {
  1012. if (!strcmp(optarg, "help") || !strcmp(optarg, "--help")) {
  1013. show_format_help(context);
  1014. context->retval = EXIT_SUCCESS;
  1015. goto exit;
  1016. }
  1017. std::unique_ptr<char, void (*)(void*)> formats(strdup(optarg), free);
  1018. char* arg = formats.get();
  1019. char* sv = nullptr; // protect against -ENOMEM above
  1020. while (!!(arg = strtok_r(arg, delimiters, &sv))) {
  1021. err = setLogFormat(context, arg);
  1022. if (err < 0) {
  1023. logcat_panic(context, HELP_FORMAT,
  1024. "Invalid parameter \"%s\" to -v\n", arg);
  1025. goto exit;
  1026. }
  1027. arg = nullptr;
  1028. if (err) hasSetLogFormat = true;
  1029. }
  1030. } break;
  1031. case 'Q':
  1032. #define LOGCAT_FILTER "androidboot.logcat="
  1033. #define CONSOLE_PIPE_OPTION "androidboot.consolepipe="
  1034. #define CONSOLE_OPTION "androidboot.console="
  1035. #define QEMU_PROPERTY "ro.kernel.qemu"
  1036. #define QEMU_CMDLINE "qemu.cmdline"
  1037. // This is a *hidden* option used to start a version of logcat
  1038. // in an emulated device only. It basically looks for
  1039. // androidboot.logcat= on the kernel command line. If
  1040. // something is found, it extracts a log filter and uses it to
  1041. // run the program. The logcat output will go to consolepipe if
  1042. // androiboot.consolepipe (e.g. qemu_pipe) is given, otherwise,
  1043. // it goes to androidboot.console (e.g. tty)
  1044. {
  1045. // if not in emulator, exit quietly
  1046. if (false == android::base::GetBoolProperty(QEMU_PROPERTY, false)) {
  1047. context->retval = EXIT_SUCCESS;
  1048. goto exit;
  1049. }
  1050. std::string cmdline = android::base::GetProperty(QEMU_CMDLINE, "");
  1051. if (cmdline.empty()) {
  1052. android::base::ReadFileToString("/proc/cmdline", &cmdline);
  1053. }
  1054. const char* logcatFilter = strstr(cmdline.c_str(), LOGCAT_FILTER);
  1055. // if nothing found or invalid filters, exit quietly
  1056. if (!logcatFilter) {
  1057. context->retval = EXIT_SUCCESS;
  1058. goto exit;
  1059. }
  1060. const char* p = logcatFilter + strlen(LOGCAT_FILTER);
  1061. const char* q = strpbrk(p, " \t\n\r");
  1062. if (!q) q = p + strlen(p);
  1063. forceFilters = std::string(p, q);
  1064. // redirect our output to the emulator console pipe or console
  1065. const char* consolePipe =
  1066. strstr(cmdline.c_str(), CONSOLE_PIPE_OPTION);
  1067. const char* console =
  1068. strstr(cmdline.c_str(), CONSOLE_OPTION);
  1069. if (consolePipe) {
  1070. p = consolePipe + strlen(CONSOLE_PIPE_OPTION);
  1071. } else if (console) {
  1072. p = console + strlen(CONSOLE_OPTION);
  1073. } else {
  1074. context->retval = EXIT_FAILURE;
  1075. goto exit;
  1076. }
  1077. q = strpbrk(p, " \t\n\r");
  1078. int len = q ? q - p : strlen(p);
  1079. std::string devname = "/dev/" + std::string(p, len);
  1080. std::string pipePurpose("pipe:logcat");
  1081. if (consolePipe) {
  1082. // example: "qemu_pipe,pipe:logcat"
  1083. // upon opening of /dev/qemu_pipe, the "pipe:logcat"
  1084. // string with trailing '\0' should be written to the fd
  1085. size_t pos = devname.find(',');
  1086. if (pos != std::string::npos) {
  1087. pipePurpose = devname.substr(pos + 1);
  1088. devname = devname.substr(0, pos);
  1089. }
  1090. }
  1091. cmdline.erase();
  1092. if (context->error) {
  1093. fprintf(context->error, "logcat using %s\n",
  1094. devname.c_str());
  1095. }
  1096. FILE* fp = fopen(devname.c_str(), "web");
  1097. devname.erase();
  1098. if (!fp) break;
  1099. if (consolePipe) {
  1100. // need the trailing '\0'
  1101. if(!android::base::WriteFully(fileno(fp), pipePurpose.c_str(),
  1102. pipePurpose.size() + 1)) {
  1103. fclose(fp);
  1104. context->retval = EXIT_FAILURE;
  1105. goto exit;
  1106. }
  1107. }
  1108. // close output and error channels, replace with console
  1109. android::close_output(context);
  1110. android::close_error(context);
  1111. context->stderr_stdout = true;
  1112. context->output = fp;
  1113. context->output_fd = fileno(fp);
  1114. if (context->stderr_null) break;
  1115. context->stderr_stdout = true;
  1116. context->error = fp;
  1117. context->error_fd = fileno(fp);
  1118. }
  1119. break;
  1120. case 'S':
  1121. printStatistics = true;
  1122. break;
  1123. case ':':
  1124. logcat_panic(context, HELP_TRUE, "Option -%c needs an argument\n", optopt);
  1125. goto exit;
  1126. case 'h':
  1127. show_help(context);
  1128. show_format_help(context);
  1129. goto exit;
  1130. default:
  1131. logcat_panic(context, HELP_TRUE, "Unrecognized Option %c\n", optopt);
  1132. goto exit;
  1133. }
  1134. }
  1135. if (context->maxCount && got_t) {
  1136. logcat_panic(context, HELP_TRUE,
  1137. "Cannot use -m (--max-count) and -t together\n");
  1138. goto exit;
  1139. }
  1140. if (context->printItAnyways && (!context->regex || !context->maxCount)) {
  1141. // One day it would be nice if --print -v color and --regex <expr>
  1142. // could play with each other and show regex highlighted content.
  1143. // clang-format off
  1144. if (context->error) {
  1145. fprintf(context->error, "WARNING: "
  1146. "--print ignored, to be used in combination with\n"
  1147. " "
  1148. "--regex <expr> and --max-count <N>\n");
  1149. }
  1150. context->printItAnyways = false;
  1151. }
  1152. if (!context->devices) {
  1153. dev = context->devices = new log_device_t("main", false);
  1154. context->devCount = 1;
  1155. if (android_name_to_log_id("system") == LOG_ID_SYSTEM) {
  1156. dev = dev->next = new log_device_t("system", false);
  1157. context->devCount++;
  1158. }
  1159. if (android_name_to_log_id("crash") == LOG_ID_CRASH) {
  1160. dev = dev->next = new log_device_t("crash", false);
  1161. context->devCount++;
  1162. }
  1163. }
  1164. if (!!context->logRotateSizeKBytes && !context->outputFileName) {
  1165. logcat_panic(context, HELP_TRUE, "-r requires -f as well\n");
  1166. goto exit;
  1167. }
  1168. if (!!setId) {
  1169. if (!context->outputFileName) {
  1170. logcat_panic(context, HELP_TRUE,
  1171. "--id='%s' requires -f as well\n", setId);
  1172. goto exit;
  1173. }
  1174. std::string file_name = android::base::StringPrintf(
  1175. "%s.id", context->outputFileName);
  1176. std::string file;
  1177. bool file_ok = android::base::ReadFileToString(file_name, &file);
  1178. android::base::WriteStringToFile(setId, file_name, S_IRUSR | S_IWUSR,
  1179. getuid(), getgid());
  1180. if (!file_ok || !file.compare(setId)) setId = nullptr;
  1181. }
  1182. if (!hasSetLogFormat) {
  1183. const char* logFormat = android::getenv(context, "ANDROID_PRINTF_LOG");
  1184. if (!!logFormat) {
  1185. std::unique_ptr<char, void (*)(void*)> formats(strdup(logFormat),
  1186. free);
  1187. char* sv = nullptr; // protect against -ENOMEM above
  1188. char* arg = formats.get();
  1189. while (!!(arg = strtok_r(arg, delimiters, &sv))) {
  1190. err = setLogFormat(context, arg);
  1191. // environment should not cause crash of logcat
  1192. if ((err < 0) && context->error) {
  1193. fprintf(context->error,
  1194. "invalid format in ANDROID_PRINTF_LOG '%s'\n", arg);
  1195. }
  1196. arg = nullptr;
  1197. if (err > 0) hasSetLogFormat = true;
  1198. }
  1199. }
  1200. if (!hasSetLogFormat) {
  1201. setLogFormat(context, "threadtime");
  1202. }
  1203. }
  1204. if (forceFilters.size()) {
  1205. err = android_log_addFilterString(context->logformat,
  1206. forceFilters.c_str());
  1207. if (err < 0) {
  1208. logcat_panic(context, HELP_FALSE,
  1209. "Invalid filter expression in logcat args\n");
  1210. goto exit;
  1211. }
  1212. } else if (argc == optind) {
  1213. // Add from environment variable
  1214. const char* env_tags_orig = android::getenv(context, "ANDROID_LOG_TAGS");
  1215. if (!!env_tags_orig) {
  1216. err = android_log_addFilterString(context->logformat,
  1217. env_tags_orig);
  1218. if (err < 0) {
  1219. logcat_panic(context, HELP_TRUE,
  1220. "Invalid filter expression in ANDROID_LOG_TAGS\n");
  1221. goto exit;
  1222. }
  1223. }
  1224. } else {
  1225. // Add from commandline
  1226. for (int i = optind ; i < argc ; i++) {
  1227. // skip stderr redirections of _all_ kinds
  1228. if ((argv[i][0] == '2') && (argv[i][1] == '>')) continue;
  1229. // skip stdout redirections of _all_ kinds
  1230. if (argv[i][0] == '>') continue;
  1231. err = android_log_addFilterString(context->logformat, argv[i]);
  1232. if (err < 0) {
  1233. logcat_panic(context, HELP_TRUE,
  1234. "Invalid filter expression '%s'\n", argv[i]);
  1235. goto exit;
  1236. }
  1237. }
  1238. }
  1239. dev = context->devices;
  1240. if (tail_time != log_time::EPOCH) {
  1241. logger_list = android_logger_list_alloc_time(mode, tail_time, pid);
  1242. } else {
  1243. logger_list = android_logger_list_alloc(mode, tail_lines, pid);
  1244. }
  1245. // We have three orthogonal actions below to clear, set log size and
  1246. // get log size. All sharing the same iteration loop.
  1247. while (dev) {
  1248. dev->logger_list = logger_list;
  1249. dev->logger = android_logger_open(logger_list,
  1250. android_name_to_log_id(dev->device));
  1251. if (!dev->logger) {
  1252. reportErrorName(&openDeviceFail, dev->device, allSelected);
  1253. dev = dev->next;
  1254. continue;
  1255. }
  1256. if (clearLog || setId) {
  1257. if (context->outputFileName) {
  1258. int maxRotationCountDigits =
  1259. (context->maxRotatedLogs > 0) ?
  1260. (int)(floor(log10(context->maxRotatedLogs) + 1)) :
  1261. 0;
  1262. for (int i = context->maxRotatedLogs ; i >= 0 ; --i) {
  1263. std::string file;
  1264. if (!i) {
  1265. file = android::base::StringPrintf(
  1266. "%s", context->outputFileName);
  1267. } else {
  1268. file = android::base::StringPrintf("%s.%.*d",
  1269. context->outputFileName, maxRotationCountDigits, i);
  1270. }
  1271. if (!file.length()) {
  1272. perror("while clearing log files");
  1273. reportErrorName(&clearFail, dev->device, allSelected);
  1274. break;
  1275. }
  1276. err = unlink(file.c_str());
  1277. if (err < 0 && errno != ENOENT && !clearFail) {
  1278. perror("while clearing log files");
  1279. reportErrorName(&clearFail, dev->device, allSelected);
  1280. }
  1281. }
  1282. } else if (android_logger_clear(dev->logger)) {
  1283. reportErrorName(&clearFail, dev->device, allSelected);
  1284. }
  1285. }
  1286. if (setLogSize) {
  1287. if (android_logger_set_log_size(dev->logger, setLogSize)) {
  1288. reportErrorName(&setSizeFail, dev->device, allSelected);
  1289. }
  1290. }
  1291. if (getLogSize) {
  1292. long size = android_logger_get_log_size(dev->logger);
  1293. long readable = android_logger_get_log_readable_size(dev->logger);
  1294. if ((size < 0) || (readable < 0)) {
  1295. reportErrorName(&getSizeFail, dev->device, allSelected);
  1296. } else {
  1297. auto size_format = format_of_size(size);
  1298. auto readable_format = format_of_size(readable);
  1299. std::string str = android::base::StringPrintf(
  1300. "%s: ring buffer is %lu %sB (%lu %sB consumed),"
  1301. " max entry is %d B, max payload is %d B\n",
  1302. dev->device,
  1303. size_format.first, size_format.second,
  1304. readable_format.first, readable_format.second,
  1305. (int)LOGGER_ENTRY_MAX_LEN,
  1306. (int)LOGGER_ENTRY_MAX_PAYLOAD);
  1307. TEMP_FAILURE_RETRY(write(context->output_fd,
  1308. str.data(), str.length()));
  1309. }
  1310. }
  1311. dev = dev->next;
  1312. }
  1313. context->retval = EXIT_SUCCESS;
  1314. // report any errors in the above loop and exit
  1315. if (openDeviceFail) {
  1316. logcat_panic(context, HELP_FALSE,
  1317. "Unable to open log device '%s'\n", openDeviceFail);
  1318. goto close;
  1319. }
  1320. if (clearFail) {
  1321. logcat_panic(context, HELP_FALSE,
  1322. "failed to clear the '%s' log\n", clearFail);
  1323. goto close;
  1324. }
  1325. if (setSizeFail) {
  1326. logcat_panic(context, HELP_FALSE,
  1327. "failed to set the '%s' log size\n", setSizeFail);
  1328. goto close;
  1329. }
  1330. if (getSizeFail) {
  1331. logcat_panic(context, HELP_FALSE,
  1332. "failed to get the readable '%s' log size", getSizeFail);
  1333. goto close;
  1334. }
  1335. if (setPruneList) {
  1336. size_t len = strlen(setPruneList);
  1337. // extra 32 bytes are needed by android_logger_set_prune_list
  1338. size_t bLen = len + 32;
  1339. char* buf = nullptr;
  1340. if (asprintf(&buf, "%-*s", (int)(bLen - 1), setPruneList) > 0) {
  1341. buf[len] = '\0';
  1342. if (android_logger_set_prune_list(logger_list, buf, bLen)) {
  1343. logcat_panic(context, HELP_FALSE,
  1344. "failed to set the prune list");
  1345. }
  1346. free(buf);
  1347. } else {
  1348. logcat_panic(context, HELP_FALSE,
  1349. "failed to set the prune list (alloc)");
  1350. }
  1351. goto close;
  1352. }
  1353. if (printStatistics || getPruneList) {
  1354. size_t len = 8192;
  1355. char* buf;
  1356. for (int retry = 32; (retry >= 0) && ((buf = new char[len]));
  1357. delete[] buf, buf = nullptr, --retry) {
  1358. if (getPruneList) {
  1359. android_logger_get_prune_list(logger_list, buf, len);
  1360. } else {
  1361. android_logger_get_statistics(logger_list, buf, len);
  1362. }
  1363. buf[len - 1] = '\0';
  1364. if (atol(buf) < 3) {
  1365. delete[] buf;
  1366. buf = nullptr;
  1367. break;
  1368. }
  1369. size_t ret = atol(buf) + 1;
  1370. if (ret <= len) {
  1371. len = ret;
  1372. break;
  1373. }
  1374. len = ret;
  1375. }
  1376. if (!buf) {
  1377. logcat_panic(context, HELP_FALSE, "failed to read data");
  1378. goto close;
  1379. }
  1380. // remove trailing FF
  1381. char* cp = buf + len - 1;
  1382. *cp = '\0';
  1383. bool truncated = *--cp != '\f';
  1384. if (!truncated) *cp = '\0';
  1385. // squash out the byte count
  1386. cp = buf;
  1387. if (!truncated) {
  1388. while (isdigit(*cp)) ++cp;
  1389. if (*cp == '\n') ++cp;
  1390. }
  1391. len = strlen(cp);
  1392. TEMP_FAILURE_RETRY(write(context->output_fd, cp, len));
  1393. delete[] buf;
  1394. goto close;
  1395. }
  1396. if (getLogSize || setLogSize || clearLog) goto close;
  1397. setupOutputAndSchedulingPolicy(context, !(mode & ANDROID_LOG_NONBLOCK));
  1398. if (context->stop) goto close;
  1399. // LOG_EVENT_INT(10, 12345);
  1400. // LOG_EVENT_LONG(11, 0x1122334455667788LL);
  1401. // LOG_EVENT_STRING(0, "whassup, doc?");
  1402. dev = nullptr;
  1403. while (!context->stop &&
  1404. (!context->maxCount || (context->printCount < context->maxCount))) {
  1405. struct log_msg log_msg;
  1406. int ret = android_logger_list_read(logger_list, &log_msg);
  1407. if (!ret) {
  1408. logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
  1409. break;
  1410. }
  1411. if (ret < 0) {
  1412. if (ret == -EAGAIN) break;
  1413. if (ret == -EIO) {
  1414. logcat_panic(context, HELP_FALSE, "read: unexpected EOF!\n");
  1415. break;
  1416. }
  1417. if (ret == -EINVAL) {
  1418. logcat_panic(context, HELP_FALSE, "read: unexpected length.\n");
  1419. break;
  1420. }
  1421. logcat_panic(context, HELP_FALSE, "logcat read failure\n");
  1422. break;
  1423. }
  1424. log_device_t* d;
  1425. for (d = context->devices; d; d = d->next) {
  1426. if (android_name_to_log_id(d->device) == log_msg.id()) break;
  1427. }
  1428. if (!d) {
  1429. context->devCount = 2; // set to Multiple
  1430. d = &unexpected;
  1431. d->binary = log_msg.id() == LOG_ID_EVENTS;
  1432. }
  1433. if (dev != d) {
  1434. dev = d;
  1435. maybePrintStart(context, dev, printDividers);
  1436. if (context->stop) break;
  1437. }
  1438. if (context->printBinary) {
  1439. printBinary(context, &log_msg);
  1440. } else {
  1441. processBuffer(context, dev, &log_msg);
  1442. }
  1443. }
  1444. close:
  1445. // Short and sweet. Implemented generic version in android_logcat_destroy.
  1446. while (!!(dev = context->devices)) {
  1447. context->devices = dev->next;
  1448. delete dev;
  1449. }
  1450. android_logger_list_free(logger_list);
  1451. exit:
  1452. // close write end of pipe to help things along
  1453. if (context->output_fd == context->fds[1]) {
  1454. android::close_output(context);
  1455. }
  1456. if (context->error_fd == context->fds[1]) {
  1457. android::close_error(context);
  1458. }
  1459. if (context->fds[1] >= 0) {
  1460. // NB: should be closed by the above
  1461. int save_errno = errno;
  1462. close(context->fds[1]);
  1463. errno = save_errno;
  1464. context->fds[1] = -1;
  1465. }
  1466. context->thread_stopped = true;
  1467. return context->retval;
  1468. }
  1469. // Can block
  1470. int android_logcat_run_command(android_logcat_context ctx,
  1471. int output, int error,
  1472. int argc, char* const* argv,
  1473. char* const* envp) {
  1474. android_logcat_context_internal* context = ctx;
  1475. context->output_fd = output;
  1476. context->error_fd = error;
  1477. context->argc = argc;
  1478. context->argv = argv;
  1479. context->envp = envp;
  1480. context->stop = false;
  1481. context->thread_stopped = false;
  1482. return __logcat(context);
  1483. }
  1484. // Finished with context
  1485. int android_logcat_destroy(android_logcat_context* ctx) {
  1486. android_logcat_context_internal* context = *ctx;
  1487. if (!context) return -EBADF;
  1488. *ctx = nullptr;
  1489. context->stop = true;
  1490. while (context->thread_stopped == false) {
  1491. // Makes me sad, replace thread_stopped with semaphore. Short lived.
  1492. sched_yield();
  1493. }
  1494. delete context->regex;
  1495. context->argv_hold.clear();
  1496. context->args.clear();
  1497. context->envp_hold.clear();
  1498. context->envs.clear();
  1499. if (context->fds[0] >= 0) {
  1500. close(context->fds[0]);
  1501. context->fds[0] = -1;
  1502. }
  1503. android::close_output(context);
  1504. android::close_error(context);
  1505. if (context->fds[1] >= 0) {
  1506. // NB: this should be closed by close_output, but just in case...
  1507. close(context->fds[1]);
  1508. context->fds[1] = -1;
  1509. }
  1510. android_closeEventTagMap(context->eventTagMap);
  1511. // generic cleanup of devices list to handle all possible dirty cases
  1512. log_device_t* dev;
  1513. while (!!(dev = context->devices)) {
  1514. struct logger_list* logger_list = dev->logger_list;
  1515. if (logger_list) {
  1516. for (log_device_t* d = dev; d; d = d->next) {
  1517. if (d->logger_list == logger_list) d->logger_list = nullptr;
  1518. }
  1519. android_logger_list_free(logger_list);
  1520. }
  1521. context->devices = dev->next;
  1522. delete dev;
  1523. }
  1524. int retval = context->retval;
  1525. free(context);
  1526. return retval;
  1527. }