#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <limits>
#include <memory>
#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
#include "base/files/file_util.h"
#include "base/memory/free_deleter.h"
#include "base/sanitizer_buildflags.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_POSIX)
#include <sys/mman.h>
#include <unistd.h>
#endif
using std::nothrow;
using std::numeric_limits;
namespace {
template <typename Type>
NOINLINE Type HideValueFromCompiler(Type value) {
#if defined(__GNUC__)
__asm__ volatile ("" : "+r" (value));
#endif
return value;
}
void OverflowTestsSoftExpectTrue(bool overflow_detected) {
if (!overflow_detected) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
BUILDFLAG(IS_APPLE)
printf("Platform has overflow: %s\n",
!overflow_detected ? "yes." : "no.");
#else
EXPECT_TRUE(overflow_detected);
#endif
}
}
#if BUILDFLAG(IS_APPLE) || defined(ADDRESS_SANITIZER) || \
defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER) || \
BUILDFLAG(IS_HWASAN) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
#define MAYBE_NewOverflow DISABLED_NewOverflow
#else
#define MAYBE_NewOverflow NewOverflow
#endif
TEST(SecurityTest, MAYBE_NewOverflow) {
const size_t kArraySize = 4096;
[[maybe_unused]] const size_t kDynamicArraySize =
HideValueFromCompiler(kArraySize);
const size_t kMaxSizeT = std::numeric_limits<size_t>::max();
const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
{
std::unique_ptr<char[][kArraySize]> array_pointer(
new (nothrow) char[kDynamicArraySize2][kArraySize]);
char* volatile p = reinterpret_cast<char*>(array_pointer.get());
OverflowTestsSoftExpectTrue(!p);
}
#if BUILDFLAG(IS_WIN) && defined(ARCH_CPU_64_BITS)
#else
{
std::unique_ptr<char[][kArraySize2]> array_pointer(
new (nothrow) char[kDynamicArraySize][kArraySize2]);
char* volatile p = reinterpret_cast<char*>(array_pointer.get());
OverflowTestsSoftExpectTrue(!p);
}
#endif
}
}