chromium/base/cpu_unittest.cc

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
#pragma allow_unsafe_buffers
#endif

#include "base/cpu.h"

#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/memory/protected_memory_buildflags.h"
#include "base/strings/string_util.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"

// Tests whether we can run extended instructions represented by the CPU
// information. This test actually executes some extended instructions (such as
// MMX, SSE, etc.) supported by the CPU and sees we can run them without
// "undefined instruction" exceptions. That is, this test succeeds when this
// test finishes without a crash.
TEST(CPU, RunExtendedInstructions) {}

// For https://crbug.com/249713
TEST(CPU, BrandAndVendorContainsNoNUL) {}

#if defined(ARCH_CPU_X86_FAMILY)
// Tests that we compute the correct CPU family and model based on the vendor
// and CPUID signature.
TEST(CPU, X86FamilyAndModel) {}
#endif  // defined(ARCH_CPU_X86_FAMILY)

#if defined(ARCH_CPU_ARM_FAMILY) && \
    (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))
TEST(CPU, ARMImplementerAndPartNumber) {
  base::CPU cpu;

  const std::string& cpu_brand = cpu.cpu_brand();

  // Some devices, including on the CQ, do not report a cpu_brand
  // https://crbug.com/1166533 and https://crbug.com/1167123.
  EXPECT_EQ(cpu_brand, base::TrimWhitespaceASCII(cpu_brand, base::TRIM_ALL));
  EXPECT_GT(cpu.implementer(), 0u);
  EXPECT_GT(cpu.part_number(), 0u);
}
#endif  // defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_LINUX) ||
        // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS))

#if BUILDFLAG(PROTECTED_MEMORY_ENABLED)
TEST(CPUDeathTest, VerifyModifyingCPUInstanceNoAllocationCrashes) {
  const base::CPU& cpu = base::CPU::GetInstanceNoAllocation();
  uint8_t* const bytes =
      const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&cpu));

  // We try and flip a couple of bits and expect the test to die immediately.
  // Checks are limited to every 15th byte, otherwise the tests run into
  // time-outs.
  for (size_t byte_index = 0; byte_index < sizeof(cpu); byte_index += 15) {
    const size_t local_bit_index = byte_index % 8;
    EXPECT_CHECK_DEATH_WITH(bytes[byte_index] ^= (0x01 << local_bit_index), "");
  }
}
#endif