xref: /aosp_15_r20/external/compiler-rt/test/lsan/TestCases/swapcontext.cc (revision 7c3d14c8b49c529e04be81a3ce6f5cc23712e4c6)
1*7c3d14c8STreehugger Robot // We can't unwind stack if we're running coroutines on heap-allocated
2*7c3d14c8STreehugger Robot // memory. Make sure we don't report these leaks.
3*7c3d14c8STreehugger Robot 
4*7c3d14c8STreehugger Robot // RUN: %clangxx_lsan %s -o %t
5*7c3d14c8STreehugger Robot // RUN: %run %t 2>&1
6*7c3d14c8STreehugger Robot // RUN: not %run %t foo 2>&1 | FileCheck %s
7*7c3d14c8STreehugger Robot 
8*7c3d14c8STreehugger Robot #include <stdio.h>
9*7c3d14c8STreehugger Robot #if defined(__APPLE__)
10*7c3d14c8STreehugger Robot // Note: ucontext.h is deprecated on OSX, so this test may stop working
11*7c3d14c8STreehugger Robot // someday. We define _XOPEN_SOURCE to keep using ucontext.h for now.
12*7c3d14c8STreehugger Robot #define _XOPEN_SOURCE 1
13*7c3d14c8STreehugger Robot #endif
14*7c3d14c8STreehugger Robot #include <ucontext.h>
15*7c3d14c8STreehugger Robot #include <unistd.h>
16*7c3d14c8STreehugger Robot 
17*7c3d14c8STreehugger Robot const int kStackSize = 1 << 20;
18*7c3d14c8STreehugger Robot 
Child()19*7c3d14c8STreehugger Robot void Child() {
20*7c3d14c8STreehugger Robot   int child_stack;
21*7c3d14c8STreehugger Robot   printf("Child: %p\n", &child_stack);
22*7c3d14c8STreehugger Robot   int *leaked = new int[666];
23*7c3d14c8STreehugger Robot }
24*7c3d14c8STreehugger Robot 
main(int argc,char * argv[])25*7c3d14c8STreehugger Robot int main(int argc, char *argv[]) {
26*7c3d14c8STreehugger Robot   char stack_memory[kStackSize + 1];
27*7c3d14c8STreehugger Robot   char *heap_memory = new char[kStackSize + 1];
28*7c3d14c8STreehugger Robot   char *child_stack = (argc > 1) ? stack_memory : heap_memory;
29*7c3d14c8STreehugger Robot 
30*7c3d14c8STreehugger Robot   printf("Child stack: %p\n", child_stack);
31*7c3d14c8STreehugger Robot   ucontext_t orig_context;
32*7c3d14c8STreehugger Robot   ucontext_t child_context;
33*7c3d14c8STreehugger Robot   getcontext(&child_context);
34*7c3d14c8STreehugger Robot   child_context.uc_stack.ss_sp = child_stack;
35*7c3d14c8STreehugger Robot   child_context.uc_stack.ss_size = kStackSize / 2;
36*7c3d14c8STreehugger Robot   child_context.uc_link = &orig_context;
37*7c3d14c8STreehugger Robot   makecontext(&child_context, Child, 0);
38*7c3d14c8STreehugger Robot   if (swapcontext(&orig_context, &child_context) < 0) {
39*7c3d14c8STreehugger Robot     perror("swapcontext");
40*7c3d14c8STreehugger Robot     return 1;
41*7c3d14c8STreehugger Robot   }
42*7c3d14c8STreehugger Robot 
43*7c3d14c8STreehugger Robot   delete[] heap_memory;
44*7c3d14c8STreehugger Robot   return 0;
45*7c3d14c8STreehugger Robot }
46*7c3d14c8STreehugger Robot 
47*7c3d14c8STreehugger Robot // CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 2664 byte(s) leaked in 1 allocation(s)
48