1//===--- RunOnNewStack.cpp - Crash Recovery -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Support/ProgramStack.h"
10#include "llvm/Config/config.h"
11#include "llvm/Support/Compiler.h"
12
13#ifdef LLVM_ON_UNIX
14# include <sys/resource.h> // for getrlimit
15#endif
16
17#ifdef _MSC_VER
18# include <intrin.h> // for _AddressOfReturnAddress
19#endif
20
21#include "llvm/Support/thread.h"
22
23#include <cstdlib>
24
25using namespace llvm;
26
27uintptr_t llvm::getStackPointer() {
28#if __GNUC__ || __has_builtin(__builtin_frame_address)
29 return (uintptr_t)__builtin_frame_address(0);
30#elif defined(_MSC_VER)
31 return (uintptr_t)_AddressOfReturnAddress();
32#else
33 volatile char CharOnStack = 0;
34 // The volatile store here is intended to escape the local variable, to
35 // prevent the compiler from optimizing CharOnStack into anything other
36 // than a char on the stack.
37 //
38 // Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.
39 char *volatile Ptr = &CharOnStack;
40 return (uintptr_t)Ptr;
41#endif
42}
43
44unsigned llvm::getDefaultStackSize() {
45#ifdef LLVM_ON_UNIX
46 rlimit RL;
47 getrlimit(RLIMIT_STACK, rlimits: &RL);
48 return RL.rlim_cur;
49#else
50 // Clang recursively parses, instantiates templates, and evaluates constant
51 // expressions. We've found 8MiB to be a reasonable stack size given the way
52 // Clang works and the way C++ is commonly written.
53 return 8 << 20;
54#endif
55}
56
57void llvm::runOnNewStack(unsigned StackSize, function_ref<void()> Fn) {
58 llvm::thread Thread(
59 StackSize == 0 ? std::nullopt : std::optional<unsigned>(StackSize), Fn);
60 Thread.join();
61}
62