1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "gtest/gtest.h"
18 
19 #include "berberis/base/exec_region_elf_backed.h"
20 
21 #include <dlfcn.h>
22 
23 namespace berberis {
24 
25 namespace {
26 
TEST(ExecRegionElfBacked,Smoke)27 TEST(ExecRegionElfBacked, Smoke) {
28   const char buf[] = "deadbeef";
29 
30   ExecRegion exec = ExecRegionElfBackedFactory::Create(sizeof(buf));
31   const uint8_t* code = exec.begin();
32   ASSERT_NE(nullptr, code);
33 
34   exec.Write(code, buf, sizeof(buf));
35   ASSERT_EQ('f', code[7]);
36 
37   exec.Detach();
38   ASSERT_EQ('f', code[7]);
39 
40   exec.Free();
41 }
42 
TEST(ExecRegionElfBacked,PltIsExecutable_b_254823538)43 TEST(ExecRegionElfBacked, PltIsExecutable_b_254823538) {
44   // DlClose calls .plt section for __cxa_finalize
45   // This test makes sure it is called without incidents
46   // http://b/254823538
47   void* handle = dlopen("libberberis_exec_region.so", RTLD_NOW);
48   EXPECT_NE(handle, nullptr) << dlerror();
49   dlclose(handle);
50 }
51 
TEST(ExecRegionElfBacked,TwoRegionsHaveDifferentAddresses)52 TEST(ExecRegionElfBacked, TwoRegionsHaveDifferentAddresses) {
53   auto region1 = ExecRegionElfBackedFactory::Create(1);
54   auto region2 = ExecRegionElfBackedFactory::Create(1);
55   EXPECT_NE(region1.begin(), region2.begin());
56   region1.Free();
57   region2.Free();
58 }
59 
TEST(ExecRegionElfBacked,RegionOfDifferentSizes)60 TEST(ExecRegionElfBacked, RegionOfDifferentSizes) {
61   auto region = ExecRegionElfBackedFactory::Create(ExecRegionElfBackedFactory::kExecRegionSize);
62   region.Free();
63   // Anything bigger should result it CHECK fail.
64   EXPECT_DEATH(
65       (void)ExecRegionElfBackedFactory::Create(ExecRegionElfBackedFactory::kExecRegionSize + 1),
66       "");
67 }
68 
69 }  // namespace
70 
71 }  // namespace berberis
72