#include "base/stack_canary_linux.h"
#include <dlfcn.h>
#include <stdint.h>
#include <sys/mman.h>
#include "base/bits.h"
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/page_size.h"
#include "base/rand_util.h"
#include "build/build_config.h"
namespace base {
#if defined(LIBC_GLIBC)
#if defined(ARCH_CPU_ARM_FAMILY)
extern "C" {
extern uintptr_t __stack_chk_guard;
}
#endif
#if !defined(NDEBUG)
static bool g_emit_debug_message = false;
extern "C" {
typedef __attribute__((noreturn)) void(GLibcStackChkFailFunction)();
__attribute__((visibility("default"), noinline, noreturn)) void
__stack_chk_fail() {
if (g_emit_debug_message) {
RAW_LOG(
FATAL,
"Stack smashing detected. The canary was changed during runtime "
"(see crbug.com/1206626). You may need to mark your function with "
"the no_stack_protector attribute, or just exit() before stack "
"smashing occurs. You can also disable this canary-changing feature "
"by adding --change-stack-guard-on-fork=disable to the command line.");
}
GLibcStackChkFailFunction* glibc_stack_chk_fail =
reinterpret_cast<GLibcStackChkFailFunction*>(
dlsym(RTLD_NEXT, "__stack_chk_fail"));
(*glibc_stack_chk_fail)();
}
}
#endif
void NO_STACK_PROTECTOR ResetStackCanaryIfPossible() {
uintptr_t canary;
base::RandBytes(&canary, sizeof(canary));
canary &= ~static_cast<uintptr_t>(0xff);
#if defined(ARCH_CPU_X86_64)
asm volatile("movq %q0,%%fs:%P1" : : "er"(canary), "i"(0x28));
#elif defined(ARCH_CPU_X86)
asm volatile("movl %0,%%gs:%P1" : : "ir"(canary), "i"(0x14));
#elif defined(ARCH_CPU_ARM_FAMILY)
size_t page_size = base::GetPageSize();
uintptr_t __stack_chk_guard_page = base::bits::AlignDown(
reinterpret_cast<uintptr_t>(&__stack_chk_guard), page_size);
PCHECK(0 == mprotect(reinterpret_cast<void*>(__stack_chk_guard_page),
page_size, PROT_READ | PROT_WRITE));
__stack_chk_guard = canary;
PCHECK(0 == mprotect(reinterpret_cast<void*>(__stack_chk_guard_page),
page_size, PROT_READ));
#endif
}
void SetStackSmashingEmitsDebugMessage() {
#if !defined(NDEBUG)
g_emit_debug_message = true;
#endif
}
#else
void ResetStackCanaryIfPossible() {}
void SetStackSmashingEmitsDebugMessage() {}
#endif
}