forked from LineageOS/android_system_core
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdebuggerd_test.cpp
3305 lines (2763 loc) · 104 KB
/
debuggerd_test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dirent.h>
#include <dlfcn.h>
#include <err.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/prctl.h>
#include <malloc.h>
#include <pthread.h>
#include <setjmp.h>
#include <stdlib.h>
#include <sys/capability.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
#include <regex>
#include <set>
#include <string>
#include <thread>
#include <android/crash_detail.h>
#include <android/dlext.h>
#include <android/fdsan.h>
#include <android/set_abort_message.h>
#include <bionic/malloc.h>
#include <bionic/mte.h>
#include <bionic/reserved_signals.h>
#include <android-base/cmsg.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/test_utils.h>
#include <android-base/unique_fd.h>
#include <cutils/sockets.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <unwindstack/Elf.h>
#include <unwindstack/Memory.h>
#include <libminijail.h>
#include <scoped_minijail.h>
#include "crash_test.h"
#include "debuggerd/handler.h"
#include "gtest/gtest.h"
#include "protocol.h"
#include "tombstoned/tombstoned.h"
#include "util.h"
using namespace std::chrono_literals;
using android::base::SendFileDescriptors;
using android::base::unique_fd;
using ::testing::HasSubstr;
#if defined(__LP64__)
#define ARCH_SUFFIX "64"
#else
#define ARCH_SUFFIX ""
#endif
constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
#define TIMEOUT(seconds, expr) \
[&]() { \
struct sigaction old_sigaction; \
struct sigaction new_sigaction = {}; \
new_sigaction.sa_handler = [](int) {}; \
if (sigaction(SIGALRM, &new_sigaction, &old_sigaction) != 0) { \
err(1, "sigaction failed"); \
} \
alarm(seconds * android::base::HwTimeoutMultiplier()); \
auto value = expr; \
int saved_errno = errno; \
if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
err(1, "sigaction failed"); \
} \
alarm(0); \
errno = saved_errno; \
return value; \
}()
// Backtrace frame dump could contain:
// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
// or
// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
ASSERT_MATCH(result, \
R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
InterceptResponse* response, DebuggerdDumpType intercept_type) {
intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
if (intercept_fd->get() == -1) {
FAIL() << "failed to contact tombstoned: " << strerror(errno);
}
InterceptRequest req = {
.dump_type = intercept_type,
.pid = target_pid,
};
unique_fd output_pipe_write;
if (!Pipe(output_fd, &output_pipe_write)) {
FAIL() << "failed to create output pipe: " << strerror(errno);
}
std::string pipe_size_str;
int pipe_buffer_size;
if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
}
pipe_size_str = android::base::Trim(pipe_size_str);
if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
FAIL() << "failed to parse pipe max size";
}
if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
FAIL() << "failed to set pipe size: " << strerror(errno);
}
ASSERT_GE(pipe_buffer_size, 1024 * 1024);
ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
output_pipe_write.reset();
if (rc != sizeof(req)) {
FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
}
rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), response, sizeof(*response)));
if (rc == -1) {
FAIL() << "failed to read response from tombstoned: " << strerror(errno);
} else if (rc == 0) {
FAIL() << "failed to read response from tombstoned (EOF)";
} else if (rc != sizeof(*response)) {
FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(*response)
<< ", received " << rc;
}
}
static bool pac_supported() {
#if defined(__aarch64__)
return getauxval(AT_HWCAP) & HWCAP_PACA;
#else
return false;
#endif
}
class CrasherTest : public ::testing::Test {
public:
pid_t crasher_pid = -1;
bool previous_wait_for_debugger;
unique_fd crasher_pipe;
unique_fd intercept_fd;
CrasherTest();
~CrasherTest();
void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
// Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
void FinishIntercept(int* result);
void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
void StartCrasher(const std::string& crash_type);
void FinishCrasher();
void AssertDeath(int signo);
static void Trap(void* ptr);
};
CrasherTest::CrasherTest() {
previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
android::base::SetProperty(kWaitForDebuggerKey, "0");
// Clear the old property too, just in case someone's been using it
// on this device. (We only document the new name, but we still support
// the old name so we don't break anyone's existing setups.)
android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
}
CrasherTest::~CrasherTest() {
if (crasher_pid != -1) {
kill(crasher_pid, SIGKILL);
int status;
TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
}
android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
}
void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
if (crasher_pid == -1) {
FAIL() << "crasher hasn't been started";
}
InterceptResponse response = {};
tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &response, intercept_type);
ASSERT_EQ(InterceptStatus::kRegistered, response.status)
<< "Error message: " << response.error_message;
}
void CrasherTest::FinishIntercept(int* result) {
InterceptResponse response;
ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
if (rc == -1) {
FAIL() << "failed to read response from tombstoned: " << strerror(errno);
} else if (rc == 0) {
*result = -1;
} else if (rc != sizeof(response)) {
FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
<< ", received " << rc;
} else {
*result = response.status == InterceptStatus::kStarted ? 1 : 0;
}
}
void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
unique_fd read_pipe;
unique_fd crasher_read_pipe;
if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
FAIL() << "failed to create pipe: " << strerror(errno);
}
crasher_pid = forker();
if (crasher_pid == -1) {
FAIL() << "fork failed: " << strerror(errno);
} else if (crasher_pid == 0) {
char dummy;
crasher_pipe.reset();
TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
function();
_exit(0);
}
}
void CrasherTest::FinishCrasher() {
if (crasher_pipe == -1) {
FAIL() << "crasher pipe uninitialized";
}
ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
if (rc == -1) {
FAIL() << "failed to write to crasher pipe: " << strerror(errno);
} else if (rc == 0) {
FAIL() << "crasher pipe was closed";
}
}
void CrasherTest::AssertDeath(int signo) {
int status;
pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
if (pid != crasher_pid) {
printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
strerror(errno));
sleep(100);
FAIL() << "failed to wait for crasher: " << strerror(errno);
}
if (signo == 0) {
ASSERT_TRUE(WIFEXITED(status)) << "Terminated due to unexpected signal " << WTERMSIG(status);
ASSERT_EQ(0, WEXITSTATUS(signo));
} else {
ASSERT_FALSE(WIFEXITED(status));
ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
ASSERT_EQ(signo, WTERMSIG(status));
}
crasher_pid = -1;
}
static void ConsumeFd(unique_fd fd, std::string* output) {
ASSERT_TRUE(android::base::ReadFdToString(fd, output));
}
class LogcatCollector {
public:
LogcatCollector() { system("logcat -c"); }
void Collect(std::string* output) {
FILE* cmd_stdout = popen("logcat -d '*:S DEBUG'", "r");
ASSERT_NE(cmd_stdout, nullptr);
unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(cmd_stdout))));
ConsumeFd(std::move(tmp_fd), output);
pclose(cmd_stdout);
}
};
TEST_F(CrasherTest, smoke) {
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
*reinterpret_cast<volatile char*>(0xdead) = '1';
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0x0+dead)");
if (mte_supported()) {
// Test that the default TAGGED_ADDR_CTRL value is set.
ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)"
R"( \(PR_TAGGED_ADDR_ENABLE, PR_MTE_TCF_SYNC, mask 0xfffe\))");
}
if (pac_supported()) {
// Test that the default PAC_ENABLED_KEYS value is set.
ASSERT_MATCH(result, R"(pac_enabled_keys: 000000000000000f)"
R"( \(PR_PAC_APIAKEY, PR_PAC_APIBKEY, PR_PAC_APDAKEY, PR_PAC_APDBKEY\))");
}
}
TEST_F(CrasherTest, tagged_fault_addr) {
#if !defined(__aarch64__)
GTEST_SKIP() << "Requires aarch64";
#endif
// HWASan crashes with SIGABRT on tag mismatch.
SKIP_WITH_HWASAN;
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
*reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
// The address can either be tagged (new kernels) or untagged (old kernels).
ASSERT_MATCH(
result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0x[01]00000000000dead)");
}
void CrasherTest::Trap(void* ptr) {
void (*volatile f)(void*) = nullptr;
__asm__ __volatile__("" : : "r"(f) : "memory");
f(ptr);
}
TEST_F(CrasherTest, heap_addr_in_register) {
#if defined(__i386__)
GTEST_SKIP() << "architecture does not pass arguments in registers";
#endif
// The memory dump in HWASan crashes sadly shows the memory near the registers
// in the HWASan dump function, rather the faulting context. This is a known
// issue.
SKIP_WITH_HWASAN;
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
// Crash with a heap pointer in the first argument register.
Trap(malloc(1));
});
StartIntercept(&output_fd);
FinishCrasher();
int status;
ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
// Don't test the signal number because different architectures use different signals for
// __builtin_trap().
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
#if defined(__aarch64__)
ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
#elif defined(__arm__)
ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
#elif defined(__riscv)
ASSERT_MATCH(result, "memory near a0 \\(\\[anon:");
#elif defined(__x86_64__)
ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
#else
ASSERT_TRUE(false) << "unsupported architecture";
#endif
}
#if defined(__aarch64__)
static void SetTagCheckingLevelSync() {
if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
abort();
}
}
static void SetTagCheckingLevelAsync() {
if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_ASYNC) == 0) {
abort();
}
}
#endif
struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(0, 16, 131072));
TEST_P(SizeParamCrasherTest, mte_uaf) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
// Any UAF on a zero-sized allocation will be out-of-bounds so it won't be reported.
if (GetParam() == 0) {
return;
}
LogcatCollector logcat_collector;
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile int* p = (volatile int*)malloc(GetParam());
free((void *)p);
p[0] = 42;
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::vector<std::string> log_sources(2);
ConsumeFd(std::move(output_fd), &log_sources[0]);
logcat_collector.Collect(&log_sources[1]);
// Tag dump only available in the tombstone, not logcat.
ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
for (const auto& result : log_sources) {
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
std::to_string(GetParam()) + R"(-byte allocation)");
ASSERT_MATCH(result, R"(deallocated by thread .*?\n.*#00 pc)");
ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
}
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile int* p = (volatile int*)malloc(GetParam());
free((void *)p);
p[-1] = 42;
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_P(SizeParamCrasherTest, mte_overflow) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
LogcatCollector logcat_collector;
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile char* p = (volatile char*)malloc(GetParam());
p[GetParam()] = 42;
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::vector<std::string> log_sources(2);
ConsumeFd(std::move(output_fd), &log_sources[0]);
logcat_collector.Collect(&log_sources[1]);
// Tag dump only in tombstone, not logcat, and tagging is not used for
// overflow protection in the scudo secondary (guard pages are used instead).
if (GetParam() < 0x10000) {
ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
}
for (const auto& result : log_sources) {
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
std::to_string(GetParam()) + R"(-byte allocation)");
ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
}
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_P(SizeParamCrasherTest, mte_underflow) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile int* p = (volatile int*)malloc(GetParam());
p[-1] = 42;
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
std::to_string(GetParam()) + R"(-byte allocation)");
ASSERT_MATCH(result, R"((^|\s)allocated by thread .*
#00 pc)");
ASSERT_MATCH(result, "Memory tags around the fault address");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
__attribute__((noinline)) void mte_illegal_setjmp_helper(jmp_buf& jump_buf) {
// This frame is at least 8 bytes for storing and restoring the LR before the
// setjmp below. So this can never get an empty stack frame, even if we omit
// the frame pointer. So, the SP of this is always less (numerically) than the
// calling function frame.
setjmp(jump_buf);
}
TEST_F(CrasherTest, DISABLED_mte_illegal_setjmp) {
// This setjmp is illegal because it jumps back into a function that already returned.
// Quoting man 3 setjmp:
// If the function which called setjmp() returns before longjmp() is
// called, the behavior is undefined. Some kind of subtle or
// unsubtle chaos is sure to result.
// https://man7.org/linux/man-pages/man3/longjmp.3.html
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
jmp_buf jump_buf;
mte_illegal_setjmp_helper(jump_buf);
longjmp(jump_buf, 1);
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGABRT);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
// In our test-case, we have a NEGATIVE stack adjustment, which is being
// interpreted as unsigned integer, and thus is "too large".
// TODO(fmayer): fix the error message for this
ASSERT_MATCH(result, R"(memtag_handle_longjmp: stack adjustment too large)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, mte_async) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelAsync();
volatile int* p = (volatile int*)malloc(16);
p[-1] = 42;
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code [89] \(SEGV_MTE[AS]ERR\), fault addr)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, mte_multiple_causes) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
LogcatCollector logcat_collector;
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
SetTagCheckingLevelSync();
// Make two allocations with the same tag and close to one another. Check for both properties
// with a bounds check -- this relies on the fact that only if the allocations have the same tag
// would they be measured as closer than 128 bytes to each other. Otherwise they would be about
// (some non-zero value << 56) apart.
//
// The out-of-bounds access will be considered either an overflow of one or an underflow of the
// other.
std::set<uintptr_t> allocs;
for (int i = 0; i != 4096; ++i) {
uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
auto it = allocs.insert(alloc).first;
if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
*reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
}
if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
*reinterpret_cast<int*>(alloc + 16) = 42;
}
}
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::vector<std::string> log_sources(2);
ConsumeFd(std::move(output_fd), &log_sources[0]);
logcat_collector.Collect(&log_sources[1]);
// Tag dump only in the tombstone, not logcat.
ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
for (const auto& result : log_sources) {
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
ASSERT_THAT(result, HasSubstr("Note: multiple potential causes for this crash were detected, "
"listing them in decreasing order of likelihood."));
// Adjacent untracked allocations may cause us to see the wrong underflow here (or only
// overflows), so we can't match explicitly for an underflow message.
ASSERT_MATCH(result,
R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
// Ensure there's at least two allocation traces (one for each cause).
ASSERT_MATCH(
result,
R"((^|\s)allocated by thread .*?\n.*#00 pc(.|\n)*?(^|\s)allocated by thread .*?\n.*#00 pc)");
}
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
#if defined(__aarch64__)
constexpr size_t kTagGranuleSize = 16;
static uintptr_t CreateTagMapping() {
// Some of the MTE tag dump tests assert that there is an inaccessible page to the left and right
// of the PROT_MTE page, so map three pages and set the two guard pages to PROT_NONE.
size_t page_size = getpagesize();
void* mapping = mmap(nullptr, page_size * 3, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
uintptr_t mapping_uptr = reinterpret_cast<uintptr_t>(mapping);
if (mapping == MAP_FAILED) {
return 0;
}
mprotect(reinterpret_cast<void*>(mapping_uptr + page_size), page_size,
PROT_READ | PROT_WRITE | PROT_MTE);
// Stripe the mapping, where even granules get tag '1', and odd granules get tag '0'.
for (uintptr_t offset = 0; offset < page_size; offset += 2 * kTagGranuleSize) {
uintptr_t tagged_addr = mapping_uptr + page_size + offset + (1ULL << 56);
__asm__ __volatile__(".arch_extension mte; stg %0, [%0]" : : "r"(tagged_addr) : "memory");
}
return mapping_uptr + page_size;
}
#endif
TEST_F(CrasherTest, mte_register_tag_dump) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
Trap(reinterpret_cast<void *>(CreateTagMapping()));
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(memory near x0:
.*
.*
01.............0 0000000000000000 0000000000000000 ................
00.............0)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, mte_fault_tag_dump_front_truncated) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
p[0] = 0; // Untagged pointer, tagged memory.
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(Memory tags around the fault address.*
\s*=>0x[0-9a-f]+000:\[1\] 0 1 0)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, mte_fault_tag_dump) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
p[320] = 0; // Untagged pointer, tagged memory.
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(Memory tags around the fault address.*
\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
\s*=>0x[0-9a-f]+: 1 0 1 0 \[1\] 0 1 0 1 0 1 0 1 0 1 0
\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
)");
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, mte_fault_tag_dump_rear_truncated) {
#if defined(__aarch64__)
if (!mte_supported()) {
GTEST_SKIP() << "Requires MTE";
}
int intercept_result;
unique_fd output_fd;
StartProcess([&]() {
SetTagCheckingLevelSync();
size_t page_size = getpagesize();
volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
p[page_size - kTagGranuleSize * 2] = 0; // Untagged pointer, tagged memory.
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(Memory tags around the fault address)");
ASSERT_MATCH(result,
R"(\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
\s*=>0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 \[1\] 0
)"); // Ensure truncation happened and there's a newline after the tag fault.
#else
GTEST_SKIP() << "Requires aarch64";
#endif
}
TEST_F(CrasherTest, LD_PRELOAD) {
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
setenv("LD_PRELOAD", "nonexistent.so", 1);
*reinterpret_cast<volatile char*>(0xdead) = '1';
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0x0+dead)");
}
TEST_F(CrasherTest, abort) {
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
abort();
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGABRT);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_BACKTRACE_FRAME(result, "abort");
}
TEST_F(CrasherTest, signal) {
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
while (true) {
sleep(1);
}
});
StartIntercept(&output_fd);
FinishCrasher();
ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
AssertDeath(SIGSEGV);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(
result,
R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
ASSERT_MATCH(result, R"(backtrace:)");
}
TEST_F(CrasherTest, abort_message) {
int intercept_result;
unique_fd output_fd;
StartProcess([]() {
// Arrived at experimentally;
// logd truncates at 4062.
// strlen("Abort message: ''") is 17.
// That's 4045, but we also want a NUL.
char buf[4045 + 1];
memset(buf, 'x', sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
android_set_abort_message(buf);
abort();
});
StartIntercept(&output_fd);
FinishCrasher();
AssertDeath(SIGABRT);
FinishIntercept(&intercept_result);
ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
std::string result;
ConsumeFd(std::move(output_fd), &result);
ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
}
static char g_crash_detail_value_changes[] = "crash_detail_value";
static char g_crash_detail_value[] = "crash_detail_value";
static char g_crash_detail_value2[] = "crash_detail_value2";
inline crash_detail_t* _Nullable android_register_crash_detail_strs(const char* _Nonnull name,
const char* _Nonnull data) {
return android_crash_detail_register(name, strlen(name), data, strlen(data));
}
TEST_F(CrasherTest, crash_detail_single) {
int intercept_result;
unique_fd output_fd;