1 /*
2 * Copyright (C) 2014 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 #include <ctype.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <poll.h>
21 #include <signal.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27
28 #include <string>
29
30 #include <android-base/file.h>
31 #include <android-base/macros.h>
32 #include <android-base/stringprintf.h>
33 #include <cutils/sockets.h>
34 #include <gtest/gtest.h>
35 #include <private/android_filesystem_config.h>
36 #include <private/android_logger.h>
37 #ifdef __ANDROID__
38 #include <selinux/selinux.h>
39 #endif
40
41 #include "../LogReader.h" // pickup LOGD_SNDTIMEO
42
43 #ifdef __ANDROID__
send_to_control(char * buf,size_t len)44 static void send_to_control(char* buf, size_t len) {
45 int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
46 SOCK_STREAM);
47 if (sock >= 0) {
48 if (write(sock, buf, strlen(buf) + 1) > 0) {
49 ssize_t ret;
50 while ((ret = read(sock, buf, len)) > 0) {
51 if (((size_t)ret == len) || (len < PAGE_SIZE)) {
52 break;
53 }
54 len -= ret;
55 buf += ret;
56
57 struct pollfd p = {.fd = sock, .events = POLLIN, .revents = 0 };
58
59 ret = poll(&p, 1, 20);
60 if ((ret <= 0) || !(p.revents & POLLIN)) {
61 break;
62 }
63 }
64 }
65 close(sock);
66 }
67 }
68
69 /*
70 * returns statistics
71 */
my_android_logger_get_statistics(char * buf,size_t len)72 static void my_android_logger_get_statistics(char* buf, size_t len) {
73 snprintf(buf, len, "getStatistics 0 1 2 3 4");
74 send_to_control(buf, len);
75 }
76
alloc_statistics(char ** buffer,size_t * length)77 static void alloc_statistics(char** buffer, size_t* length) {
78 size_t len = 8192;
79 char* buf;
80
81 for (int retry = 32; (retry >= 0); delete[] buf, --retry) {
82 buf = new char[len];
83 my_android_logger_get_statistics(buf, len);
84
85 buf[len - 1] = '\0';
86 size_t ret = atol(buf) + 1;
87 if (ret < 4) {
88 delete[] buf;
89 buf = nullptr;
90 break;
91 }
92 bool check = ret <= len;
93 len = ret;
94 if (check) {
95 break;
96 }
97 len += len / 8; // allow for some slop
98 }
99 *buffer = buf;
100 *length = len;
101 }
102
find_benchmark_spam(char * cp)103 static char* find_benchmark_spam(char* cp) {
104 // liblog_benchmarks has been run designed to SPAM. The signature of
105 // a noisiest UID statistics is:
106 //
107 // Chattiest UIDs in main log buffer: Size Pruned
108 // UID PACKAGE BYTES LINES
109 // 0 root 54164 147569
110 //
111 char* benchmark = nullptr;
112 do {
113 static const char signature[] = "\n0 root ";
114
115 benchmark = strstr(cp, signature);
116 if (!benchmark) {
117 break;
118 }
119 cp = benchmark + sizeof(signature);
120 while (isspace(*cp)) {
121 ++cp;
122 }
123 benchmark = cp;
124 #ifdef DEBUG
125 char* end = strstr(benchmark, "\n");
126 if (end == nullptr) {
127 end = benchmark + strlen(benchmark);
128 }
129 fprintf(stderr, "parse for spam counter in \"%.*s\"\n",
130 (int)(end - benchmark), benchmark);
131 #endif
132 // content
133 while (isdigit(*cp)) {
134 ++cp;
135 }
136 while (isspace(*cp)) {
137 ++cp;
138 }
139 // optional +/- field?
140 if ((*cp == '-') || (*cp == '+')) {
141 while (isdigit(*++cp) || (*cp == '.') || (*cp == '%') ||
142 (*cp == 'X')) {
143 ;
144 }
145 while (isspace(*cp)) {
146 ++cp;
147 }
148 }
149 // number of entries pruned
150 unsigned long value = 0;
151 while (isdigit(*cp)) {
152 value = value * 10ULL + *cp - '0';
153 ++cp;
154 }
155 if (value > 10UL) {
156 break;
157 }
158 benchmark = nullptr;
159 } while (*cp);
160 return benchmark;
161 }
162 #endif
163
TEST(logd,statistics)164 TEST(logd, statistics) {
165 #ifdef __ANDROID__
166 size_t len;
167 char* buf;
168
169 // Drop cache so that any access problems can be discovered.
170 if (!android::base::WriteStringToFile("3\n", "/proc/sys/vm/drop_caches")) {
171 GTEST_LOG_(INFO) << "Could not open trigger dropping inode cache";
172 }
173
174 alloc_statistics(&buf, &len);
175
176 ASSERT_TRUE(nullptr != buf);
177
178 // remove trailing FF
179 char* cp = buf + len - 1;
180 *cp = '\0';
181 bool truncated = *--cp != '\f';
182 if (!truncated) {
183 *cp = '\0';
184 }
185
186 // squash out the byte count
187 cp = buf;
188 if (!truncated) {
189 while (isdigit(*cp) || (*cp == '\n')) {
190 ++cp;
191 }
192 }
193
194 fprintf(stderr, "%s", cp);
195
196 EXPECT_LT((size_t)64, strlen(cp));
197
198 EXPECT_EQ(0, truncated);
199
200 char* main_logs = strstr(cp, "\nChattiest UIDs in main ");
201 EXPECT_TRUE(nullptr != main_logs);
202
203 char* radio_logs = strstr(cp, "\nChattiest UIDs in radio ");
204 if (!radio_logs)
205 GTEST_LOG_(INFO) << "Value of: nullptr != radio_logs\n"
206 "Actual: false\n"
207 "Expected: false\n";
208
209 char* system_logs = strstr(cp, "\nChattiest UIDs in system ");
210 EXPECT_TRUE(nullptr != system_logs);
211
212 char* events_logs = strstr(cp, "\nChattiest UIDs in events ");
213 EXPECT_TRUE(nullptr != events_logs);
214
215 // Check if there is any " u0_a#### " as this means packagelistparser broken
216 char* used_getpwuid = nullptr;
217 int used_getpwuid_len;
218 char* uid_name = cp;
219 static const char getpwuid_prefix[] = " u0_a";
220 while ((uid_name = strstr(uid_name, getpwuid_prefix)) != nullptr) {
221 used_getpwuid = uid_name + 1;
222 uid_name += strlen(getpwuid_prefix);
223 while (isdigit(*uid_name)) ++uid_name;
224 used_getpwuid_len = uid_name - used_getpwuid;
225 if (isspace(*uid_name)) break;
226 used_getpwuid = nullptr;
227 }
228 EXPECT_TRUE(nullptr == used_getpwuid);
229 if (used_getpwuid) {
230 fprintf(stderr, "libpackagelistparser failed to pick up %.*s\n",
231 used_getpwuid_len, used_getpwuid);
232 }
233
234 delete[] buf;
235 #else
236 GTEST_LOG_(INFO) << "This test does nothing.\n";
237 #endif
238 }
239
240 #ifdef __ANDROID__
caught_signal(int)241 static void caught_signal(int /* signum */) {
242 }
243
dump_log_msg(const char * prefix,log_msg * msg,int lid)244 static void dump_log_msg(const char* prefix, log_msg* msg, int lid) {
245 std::cout << std::flush;
246 std::cerr << std::flush;
247 fflush(stdout);
248 fflush(stderr);
249 EXPECT_GE(msg->entry.hdr_size, sizeof(logger_entry));
250
251 fprintf(stderr, "%s: [%u] ", prefix, msg->len());
252 fprintf(stderr, "hdr_size=%u ", msg->entry.hdr_size);
253 fprintf(stderr, "pid=%u tid=%u %u.%09u ", msg->entry.pid, msg->entry.tid, msg->entry.sec,
254 msg->entry.nsec);
255 lid = msg->entry.lid;
256
257 switch (lid) {
258 case 0:
259 fprintf(stderr, "lid=main ");
260 break;
261 case 1:
262 fprintf(stderr, "lid=radio ");
263 break;
264 case 2:
265 fprintf(stderr, "lid=events ");
266 break;
267 case 3:
268 fprintf(stderr, "lid=system ");
269 break;
270 case 4:
271 fprintf(stderr, "lid=crash ");
272 break;
273 case 5:
274 fprintf(stderr, "lid=security ");
275 break;
276 case 6:
277 fprintf(stderr, "lid=kernel ");
278 break;
279 default:
280 if (lid >= 0) {
281 fprintf(stderr, "lid=%d ", lid);
282 }
283 }
284
285 unsigned int len = msg->entry.len;
286 fprintf(stderr, "msg[%u]={", len);
287 unsigned char* cp = reinterpret_cast<unsigned char*>(msg->msg());
288 if (!cp) {
289 static const unsigned char garbage[] = "<INVALID>";
290 cp = const_cast<unsigned char*>(garbage);
291 len = strlen(reinterpret_cast<const char*>(garbage));
292 }
293 while (len) {
294 unsigned char* p = cp;
295 while (*p && (((' ' <= *p) && (*p < 0x7F)) || (*p == '\n'))) {
296 ++p;
297 }
298 if (((p - cp) > 3) && !*p && ((unsigned int)(p - cp) < len)) {
299 fprintf(stderr, "\"");
300 while (*cp) {
301 if (*cp != '\n') {
302 fprintf(stderr, "%c", *cp);
303 } else {
304 fprintf(stderr, "\\n");
305 }
306 ++cp;
307 --len;
308 }
309 fprintf(stderr, "\"");
310 } else {
311 fprintf(stderr, "%02x", *cp);
312 }
313 ++cp;
314 if (--len) {
315 fprintf(stderr, ", ");
316 }
317 }
318 fprintf(stderr, "}\n");
319 fflush(stderr);
320 }
321 #endif
322
323 #ifdef __ANDROID__
324 // BAD ROBOT
325 // Benchmark threshold are generally considered bad form unless there is
326 // is some human love applied to the continued maintenance and whether the
327 // thresholds are tuned on a per-target basis. Here we check if the values
328 // are more than double what is expected. Doubling will not prevent failure
329 // on busy or low-end systems that could have a tendency to stretch values.
330 //
331 // The primary goal of this test is to simulate a spammy app (benchmark
332 // being the worst) and check to make sure the logger can deal with it
333 // appropriately by checking all the statistics are in an expected range.
334 //
TEST(logd,benchmark)335 TEST(logd, benchmark) {
336 size_t len;
337 char* buf;
338
339 alloc_statistics(&buf, &len);
340 bool benchmark_already_run = buf && find_benchmark_spam(buf);
341 delete[] buf;
342
343 if (benchmark_already_run) {
344 fprintf(stderr,
345 "WARNING: spam already present and too much history\n"
346 " false OK for prune by worst UID check\n");
347 }
348
349 FILE* fp;
350
351 // Introduce some extreme spam for the worst UID filter
352 ASSERT_TRUE(
353 nullptr !=
354 (fp = popen("/data/nativetest/liblog-benchmarks/liblog-benchmarks"
355 " BM_log_maximum_retry"
356 " BM_log_maximum"
357 " BM_clock_overhead"
358 " BM_log_print_overhead"
359 " BM_log_latency"
360 " BM_log_delay",
361 "r")));
362
363 char buffer[5120];
364
365 static const char* benchmarks[] = {
366 "BM_log_maximum_retry ", "BM_log_maximum ", "BM_clock_overhead ",
367 "BM_log_print_overhead ", "BM_log_latency ", "BM_log_delay "
368 };
369 static const unsigned int log_maximum_retry = 0;
370 static const unsigned int log_maximum = 1;
371 static const unsigned int clock_overhead = 2;
372 static const unsigned int log_print_overhead = 3;
373 static const unsigned int log_latency = 4;
374 static const unsigned int log_delay = 5;
375
376 unsigned long ns[arraysize(benchmarks)];
377
378 memset(ns, 0, sizeof(ns));
379
380 while (fgets(buffer, sizeof(buffer), fp)) {
381 for (unsigned i = 0; i < arraysize(ns); ++i) {
382 char* cp = strstr(buffer, benchmarks[i]);
383 if (!cp) {
384 continue;
385 }
386 sscanf(cp, "%*s %lu %lu", &ns[i], &ns[i]);
387 fprintf(stderr, "%-22s%8lu\n", benchmarks[i], ns[i]);
388 }
389 }
390 int ret = pclose(fp);
391
392 if (!WIFEXITED(ret) || (WEXITSTATUS(ret) == 127)) {
393 fprintf(stderr,
394 "WARNING: "
395 "/data/nativetest/liblog-benchmarks/liblog-benchmarks missing\n"
396 " can not perform test\n");
397 return;
398 }
399
400 EXPECT_GE(200000UL, ns[log_maximum_retry]); // 104734 user
401 EXPECT_NE(0UL, ns[log_maximum_retry]); // failure to parse
402
403 EXPECT_GE(90000UL, ns[log_maximum]); // 46913 user
404 EXPECT_NE(0UL, ns[log_maximum]); // failure to parse
405
406 EXPECT_GE(4096UL, ns[clock_overhead]); // 4095
407 EXPECT_NE(0UL, ns[clock_overhead]); // failure to parse
408
409 EXPECT_GE(250000UL, ns[log_print_overhead]); // 126886 user
410 EXPECT_NE(0UL, ns[log_print_overhead]); // failure to parse
411
412 EXPECT_GE(10000000UL,
413 ns[log_latency]); // 1453559 user space (background cgroup)
414 EXPECT_NE(0UL, ns[log_latency]); // failure to parse
415
416 EXPECT_GE(20000000UL, ns[log_delay]); // 10500289 user
417 EXPECT_NE(0UL, ns[log_delay]); // failure to parse
418
419 alloc_statistics(&buf, &len);
420
421 bool collected_statistics = !!buf;
422 EXPECT_EQ(true, collected_statistics);
423
424 ASSERT_TRUE(nullptr != buf);
425
426 char* benchmark_statistics_found = find_benchmark_spam(buf);
427 ASSERT_TRUE(benchmark_statistics_found != nullptr);
428
429 // Check how effective the SPAM filter is, parse out Now size.
430 // 0 root 54164 147569
431 // ^-- benchmark_statistics_found
432
433 unsigned long nowSpamSize = atol(benchmark_statistics_found);
434
435 delete[] buf;
436
437 ASSERT_NE(0UL, nowSpamSize);
438
439 // Determine if we have the spam filter enabled
440 int sock = socket_local_client("logd", ANDROID_SOCKET_NAMESPACE_RESERVED,
441 SOCK_STREAM);
442
443 ASSERT_TRUE(sock >= 0);
444
445 static const char getPruneList[] = "getPruneList";
446 if (write(sock, getPruneList, sizeof(getPruneList)) > 0) {
447 char buffer[80];
448 memset(buffer, 0, sizeof(buffer));
449 read(sock, buffer, sizeof(buffer));
450 char* cp = strchr(buffer, '\n');
451 if (!cp || (cp[1] != '~') || (cp[2] != '!')) {
452 close(sock);
453 fprintf(stderr,
454 "WARNING: "
455 "Logger has SPAM filtration turned off \"%s\"\n",
456 buffer);
457 return;
458 }
459 } else {
460 int save_errno = errno;
461 close(sock);
462 FAIL() << "Can not send " << getPruneList << " to logger -- "
463 << strerror(save_errno);
464 }
465
466 static const unsigned long expected_absolute_minimum_log_size = 65536UL;
467 unsigned long totalSize = expected_absolute_minimum_log_size;
468 static const char getSize[] = { 'g', 'e', 't', 'L', 'o', 'g',
469 'S', 'i', 'z', 'e', ' ', LOG_ID_MAIN + '0',
470 '\0' };
471 if (write(sock, getSize, sizeof(getSize)) > 0) {
472 char buffer[80];
473 memset(buffer, 0, sizeof(buffer));
474 read(sock, buffer, sizeof(buffer));
475 totalSize = atol(buffer);
476 if (totalSize < expected_absolute_minimum_log_size) {
477 fprintf(stderr,
478 "WARNING: "
479 "Logger had unexpected referenced size \"%s\"\n",
480 buffer);
481 totalSize = expected_absolute_minimum_log_size;
482 }
483 }
484 close(sock);
485
486 // logd allows excursions to 110% of total size
487 totalSize = (totalSize * 11) / 10;
488
489 // 50% threshold for SPAM filter (<20% typical, lots of engineering margin)
490 ASSERT_GT(totalSize, nowSpamSize * 2);
491 }
492 #endif
493
494 // b/26447386 confirm fixed
timeout_negative(const char * command)495 void timeout_negative(const char* command) {
496 #ifdef __ANDROID__
497 log_msg msg_wrap, msg_timeout;
498 bool content_wrap = false, content_timeout = false, written = false;
499 unsigned int alarm_wrap = 0, alarm_timeout = 0;
500 // A few tries to get it right just in case wrap kicks in due to
501 // content providers being active during the test.
502 int i = 3;
503
504 while (--i) {
505 int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
506 SOCK_SEQPACKET);
507 ASSERT_LT(0, fd);
508
509 std::string ask(command);
510
511 struct sigaction ignore, old_sigaction;
512 memset(&ignore, 0, sizeof(ignore));
513 ignore.sa_handler = caught_signal;
514 sigemptyset(&ignore.sa_mask);
515 sigaction(SIGALRM, &ignore, &old_sigaction);
516 unsigned int old_alarm = alarm(3);
517
518 size_t len = ask.length() + 1;
519 written = write(fd, ask.c_str(), len) == (ssize_t)len;
520 if (!written) {
521 alarm(old_alarm);
522 sigaction(SIGALRM, &old_sigaction, nullptr);
523 close(fd);
524 continue;
525 }
526
527 // alarm triggers at 50% of the --wrap time out
528 content_wrap = recv(fd, msg_wrap.buf, sizeof(msg_wrap), 0) > 0;
529
530 alarm_wrap = alarm(5);
531
532 // alarm triggers at 133% of the --wrap time out
533 content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
534 if (!content_timeout) { // make sure we hit dumpAndClose
535 content_timeout =
536 recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
537 }
538
539 if (old_alarm > 0) {
540 unsigned int time_spent = 3 - alarm_wrap;
541 if (old_alarm > time_spent + 1) {
542 old_alarm -= time_spent;
543 } else {
544 old_alarm = 2;
545 }
546 }
547 alarm_timeout = alarm(old_alarm);
548 sigaction(SIGALRM, &old_sigaction, nullptr);
549
550 close(fd);
551
552 if (content_wrap && alarm_wrap && content_timeout && alarm_timeout) {
553 break;
554 }
555 }
556
557 if (content_wrap) {
558 dump_log_msg("wrap", &msg_wrap, -1);
559 }
560
561 if (content_timeout) {
562 dump_log_msg("timeout", &msg_timeout, -1);
563 }
564
565 EXPECT_TRUE(written);
566 EXPECT_TRUE(content_wrap);
567 EXPECT_NE(0U, alarm_wrap);
568 EXPECT_TRUE(content_timeout);
569 EXPECT_NE(0U, alarm_timeout);
570 #else
571 command = nullptr;
572 GTEST_LOG_(INFO) << "This test does nothing.\n";
573 #endif
574 }
575
TEST(logd,timeout_no_start)576 TEST(logd, timeout_no_start) {
577 timeout_negative("dumpAndClose lids=0,1,2,3,4,5 timeout=6");
578 }
579
TEST(logd,timeout_start_epoch)580 TEST(logd, timeout_start_epoch) {
581 timeout_negative(
582 "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=0.000000000");
583 }
584
585 #ifdef ENABLE_FLAKY_TESTS
586 // b/26447386 refined behavior
TEST(logd,timeout)587 TEST(logd, timeout) {
588 #ifdef __ANDROID__
589 // b/33962045 This test interferes with other log reader tests that
590 // follow because of file descriptor socket persistence in the same
591 // process. So let's fork it to isolate it from giving us pain.
592
593 pid_t pid = fork();
594
595 if (pid) {
596 siginfo_t info = {};
597 ASSERT_EQ(0, TEMP_FAILURE_RETRY(waitid(P_PID, pid, &info, WEXITED)));
598 ASSERT_EQ(0, info.si_status);
599 return;
600 }
601
602 log_msg msg_wrap, msg_timeout;
603 bool content_wrap = false, content_timeout = false, written = false;
604 unsigned int alarm_wrap = 0, alarm_timeout = 0;
605 // A few tries to get it right just in case wrap kicks in due to
606 // content providers being active during the test.
607 int i = 5;
608 log_time start(android_log_clockid());
609 start.tv_sec -= 30; // reach back a moderate period of time
610
611 while (--i) {
612 int fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
613 SOCK_SEQPACKET);
614 int save_errno = errno;
615 if (fd < 0) {
616 fprintf(stderr, "failed to open /dev/socket/logdr %s\n",
617 strerror(save_errno));
618 _exit(fd);
619 }
620
621 std::string ask = android::base::StringPrintf(
622 "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=%" PRIu32
623 ".%09" PRIu32,
624 start.tv_sec, start.tv_nsec);
625
626 struct sigaction ignore, old_sigaction;
627 memset(&ignore, 0, sizeof(ignore));
628 ignore.sa_handler = caught_signal;
629 sigemptyset(&ignore.sa_mask);
630 sigaction(SIGALRM, &ignore, &old_sigaction);
631 unsigned int old_alarm = alarm(3);
632
633 size_t len = ask.length() + 1;
634 written = write(fd, ask.c_str(), len) == (ssize_t)len;
635 if (!written) {
636 alarm(old_alarm);
637 sigaction(SIGALRM, &old_sigaction, nullptr);
638 close(fd);
639 continue;
640 }
641
642 // alarm triggers at 50% of the --wrap time out
643 content_wrap = recv(fd, msg_wrap.buf, sizeof(msg_wrap), 0) > 0;
644
645 alarm_wrap = alarm(5);
646
647 // alarm triggers at 133% of the --wrap time out
648 content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
649 if (!content_timeout) { // make sure we hit dumpAndClose
650 content_timeout =
651 recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
652 }
653
654 if (old_alarm > 0) {
655 unsigned int time_spent = 3 - alarm_wrap;
656 if (old_alarm > time_spent + 1) {
657 old_alarm -= time_spent;
658 } else {
659 old_alarm = 2;
660 }
661 }
662 alarm_timeout = alarm(old_alarm);
663 sigaction(SIGALRM, &old_sigaction, nullptr);
664
665 close(fd);
666
667 if (!content_wrap && !alarm_wrap && content_timeout && alarm_timeout) {
668 break;
669 }
670
671 // modify start time in case content providers are relatively
672 // active _or_ inactive during the test.
673 if (content_timeout) {
674 log_time msg(msg_timeout.entry.sec, msg_timeout.entry.nsec);
675 if (msg < start) {
676 fprintf(stderr, "%u.%09u < %u.%09u\n", msg_timeout.entry.sec,
677 msg_timeout.entry.nsec, (unsigned)start.tv_sec,
678 (unsigned)start.tv_nsec);
679 _exit(-1);
680 }
681 if (msg > start) {
682 start = msg;
683 start.tv_sec += 30;
684 log_time now = log_time(android_log_clockid());
685 if (start > now) {
686 start = now;
687 --start.tv_sec;
688 }
689 }
690 } else {
691 start.tv_sec -= 120; // inactive, reach further back!
692 }
693 }
694
695 if (content_wrap) {
696 dump_log_msg("wrap", &msg_wrap, -1);
697 }
698
699 if (content_timeout) {
700 dump_log_msg("timeout", &msg_timeout, -1);
701 }
702
703 if (content_wrap || !content_timeout) {
704 fprintf(stderr, "start=%" PRIu32 ".%09" PRIu32 "\n", start.tv_sec,
705 start.tv_nsec);
706 }
707
708 EXPECT_TRUE(written);
709 EXPECT_FALSE(content_wrap);
710 EXPECT_EQ(0U, alarm_wrap);
711 EXPECT_TRUE(content_timeout);
712 EXPECT_NE(0U, alarm_timeout);
713
714 _exit(!written + content_wrap + alarm_wrap + !content_timeout +
715 !alarm_timeout);
716 #else
717 GTEST_LOG_(INFO) << "This test does nothing.\n";
718 #endif
719 }
720 #endif
721
722 // b/27242723 confirmed fixed
TEST(logd,SNDTIMEO)723 TEST(logd, SNDTIMEO) {
724 #ifdef __ANDROID__
725 static const unsigned sndtimeo =
726 LOGD_SNDTIMEO; // <sigh> it has to be done!
727 static const unsigned sleep_time = sndtimeo + 3;
728 static const unsigned alarm_time = sleep_time + 5;
729
730 int fd;
731
732 ASSERT_TRUE(
733 (fd = socket_local_client("logdr", ANDROID_SOCKET_NAMESPACE_RESERVED,
734 SOCK_SEQPACKET)) > 0);
735
736 struct sigaction ignore, old_sigaction;
737 memset(&ignore, 0, sizeof(ignore));
738 ignore.sa_handler = caught_signal;
739 sigemptyset(&ignore.sa_mask);
740 sigaction(SIGALRM, &ignore, &old_sigaction);
741 unsigned int old_alarm = alarm(alarm_time);
742
743 static const char ask[] = "stream lids=0,1,2,3,4,5,6"; // all sources
744 bool reader_requested = write(fd, ask, sizeof(ask)) == sizeof(ask);
745 EXPECT_TRUE(reader_requested);
746
747 log_msg msg;
748 bool read_one = recv(fd, msg.buf, sizeof(msg), 0) > 0;
749
750 EXPECT_TRUE(read_one);
751 if (read_one) {
752 dump_log_msg("user", &msg, -1);
753 }
754
755 fprintf(stderr, "Sleep for >%d seconds logd SO_SNDTIMEO ...\n", sndtimeo);
756 sleep(sleep_time);
757
758 // flush will block if we did not trigger. if it did, last entry returns 0
759 int recv_ret;
760 do {
761 recv_ret = recv(fd, msg.buf, sizeof(msg), 0);
762 } while (recv_ret > 0);
763 int save_errno = (recv_ret < 0) ? errno : 0;
764
765 EXPECT_NE(0U, alarm(old_alarm));
766 sigaction(SIGALRM, &old_sigaction, nullptr);
767
768 EXPECT_EQ(0, recv_ret);
769 if (recv_ret > 0) {
770 dump_log_msg("user", &msg, -1);
771 }
772 EXPECT_EQ(0, save_errno);
773
774 close(fd);
775 #else
776 GTEST_LOG_(INFO) << "This test does nothing.\n";
777 #endif
778 }
779
TEST(logd,getEventTag_list)780 TEST(logd, getEventTag_list) {
781 #ifdef __ANDROID__
782 char buffer[256];
783 memset(buffer, 0, sizeof(buffer));
784 snprintf(buffer, sizeof(buffer), "getEventTag name=*");
785 send_to_control(buffer, sizeof(buffer));
786 buffer[sizeof(buffer) - 1] = '\0';
787 char* cp;
788 long ret = strtol(buffer, &cp, 10);
789 EXPECT_GT(ret, 4096);
790 #else
791 GTEST_LOG_(INFO) << "This test does nothing.\n";
792 #endif
793 }
794
TEST(logd,getEventTag_42)795 TEST(logd, getEventTag_42) {
796 #ifdef __ANDROID__
797 char buffer[256];
798 memset(buffer, 0, sizeof(buffer));
799 snprintf(buffer, sizeof(buffer), "getEventTag id=42");
800 send_to_control(buffer, sizeof(buffer));
801 buffer[sizeof(buffer) - 1] = '\0';
802 char* cp;
803 long ret = strtol(buffer, &cp, 10);
804 EXPECT_GT(ret, 16);
805 EXPECT_TRUE(strstr(buffer, "\t(to life the universe etc|3)") != nullptr);
806 EXPECT_TRUE(strstr(buffer, "answer") != nullptr);
807 #else
808 GTEST_LOG_(INFO) << "This test does nothing.\n";
809 #endif
810 }
811
TEST(logd,getEventTag_newentry)812 TEST(logd, getEventTag_newentry) {
813 #ifdef __ANDROID__
814 char buffer[256];
815 memset(buffer, 0, sizeof(buffer));
816 log_time now(CLOCK_MONOTONIC);
817 char name[64];
818 snprintf(name, sizeof(name), "a%" PRIu64, now.nsec());
819 snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"(new|1)\"",
820 name);
821 send_to_control(buffer, sizeof(buffer));
822 buffer[sizeof(buffer) - 1] = '\0';
823 char* cp;
824 long ret = strtol(buffer, &cp, 10);
825 EXPECT_GT(ret, 16);
826 EXPECT_TRUE(strstr(buffer, "\t(new|1)") != nullptr);
827 EXPECT_TRUE(strstr(buffer, name) != nullptr);
828 // ToDo: also look for this in /data/misc/logd/event-log-tags and
829 // /dev/event-log-tags.
830 #else
831 GTEST_LOG_(INFO) << "This test does nothing.\n";
832 #endif
833 }
834
835 #ifdef __ANDROID__
get4LE(const uint8_t * src)836 static inline uint32_t get4LE(const uint8_t* src) {
837 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
838 }
839
get4LE(const char * src)840 static inline uint32_t get4LE(const char* src) {
841 return get4LE(reinterpret_cast<const uint8_t*>(src));
842 }
843 #endif
844
__android_log_btwrite_multiple__helper(int count)845 void __android_log_btwrite_multiple__helper(int count) {
846 #ifdef __ANDROID__
847 log_time ts(CLOCK_MONOTONIC);
848 usleep(100);
849 log_time ts1(CLOCK_MONOTONIC);
850
851 // We fork to create a unique pid for the submitted log messages
852 // so that we do not collide with the other _multiple_ tests.
853
854 pid_t pid = fork();
855
856 if (pid == 0) {
857 // child
858 for (int i = count; i; --i) {
859 ASSERT_LT(
860 0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
861 usleep(100);
862 }
863 ASSERT_LT(0,
864 __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
865 usleep(1000000);
866
867 _exit(0);
868 }
869
870 siginfo_t info = {};
871 ASSERT_EQ(0, TEMP_FAILURE_RETRY(waitid(P_PID, pid, &info, WEXITED)));
872 ASSERT_EQ(0, info.si_status);
873
874 struct logger_list* logger_list;
875 ASSERT_TRUE(nullptr !=
876 (logger_list = android_logger_list_open(
877 LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
878 0, pid)));
879
880 int expected_count = (count < 2) ? count : 2;
881 int expected_chatty_count = (count <= 2) ? 0 : 1;
882 int expected_identical_count = (count < 2) ? 0 : (count - 2);
883 static const int expected_expire_count = 0;
884
885 count = 0;
886 int second_count = 0;
887 int chatty_count = 0;
888 int identical_count = 0;
889 int expire_count = 0;
890
891 for (;;) {
892 log_msg log_msg;
893 if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
894
895 if ((log_msg.entry.pid != pid) || (log_msg.entry.len < (4 + 1 + 8)) ||
896 (log_msg.id() != LOG_ID_EVENTS))
897 continue;
898
899 char* eventData = log_msg.msg();
900 if (!eventData) continue;
901
902 uint32_t tag = get4LE(eventData);
903
904 if ((eventData[4] == EVENT_TYPE_LONG) &&
905 (log_msg.entry.len == (4 + 1 + 8))) {
906 if (tag != 0) continue;
907
908 log_time tx(eventData + 4 + 1);
909 if (ts == tx) {
910 ++count;
911 } else if (ts1 == tx) {
912 ++second_count;
913 }
914 } else if (eventData[4] == EVENT_TYPE_STRING) {
915 if (tag != CHATTY_LOG_TAG) continue;
916 ++chatty_count;
917 // int len = get4LE(eventData + 4 + 1);
918 log_msg.buf[LOGGER_ENTRY_MAX_LEN] = '\0';
919 const char* cp;
920 if ((cp = strstr(eventData + 4 + 1 + 4, " identical "))) {
921 unsigned val = 0;
922 sscanf(cp, " identical %u lines", &val);
923 identical_count += val;
924 } else if ((cp = strstr(eventData + 4 + 1 + 4, " expire "))) {
925 unsigned val = 0;
926 sscanf(cp, " expire %u lines", &val);
927 expire_count += val;
928 }
929 }
930 }
931
932 android_logger_list_close(logger_list);
933
934 EXPECT_EQ(expected_count, count);
935 EXPECT_EQ(1, second_count);
936 EXPECT_EQ(expected_chatty_count, chatty_count);
937 EXPECT_EQ(expected_identical_count, identical_count);
938 EXPECT_EQ(expected_expire_count, expire_count);
939 #else
940 count = 0;
941 GTEST_LOG_(INFO) << "This test does nothing.\n";
942 #endif
943 }
944
TEST(logd,multiple_test_1)945 TEST(logd, multiple_test_1) {
946 __android_log_btwrite_multiple__helper(1);
947 }
948
TEST(logd,multiple_test_2)949 TEST(logd, multiple_test_2) {
950 __android_log_btwrite_multiple__helper(2);
951 }
952
TEST(logd,multiple_test_3)953 TEST(logd, multiple_test_3) {
954 __android_log_btwrite_multiple__helper(3);
955 }
956
TEST(logd,multiple_test_10)957 TEST(logd, multiple_test_10) {
958 __android_log_btwrite_multiple__helper(10);
959 }
960