blob: 1567367b675755e5776f0660f96d1b4580349fda [file] [log] [blame]
Andreas Gampe03b9ee42015-04-24 21:41:45 -07001/*
2 * Copyright (C) 2014 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#ifndef ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
18#define ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
19
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070020#include <sys/stat.h>
Andreas Gampe03b9ee42015-04-24 21:41:45 -070021#include <cstdio>
22#include <cstdlib>
23#include <fstream>
24#include <iterator>
Andreas Gampe03b9ee42015-04-24 21:41:45 -070025
Andreas Gampe9186ced2016-12-12 14:28:21 -080026#include "android-base/strings.h"
27
David Srbeckyd6e14e02020-07-01 13:19:17 +010028#include "base/os.h"
David Sehrc431b9d2018-03-02 12:01:51 -080029#include "base/utils.h"
David Srbeckyd6e14e02020-07-01 13:19:17 +010030#include "common_runtime_test.h" // For ScratchDir.
31#include "elf/elf_builder.h"
32#include "elf/elf_debug_reader.h"
David Sehr97c381e2017-02-01 15:09:58 -080033#include "exec_utils.h"
David Srbeckyd6e14e02020-07-01 13:19:17 +010034#include "stream/file_output_stream.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010035
Andreas Gampe03b9ee42015-04-24 21:41:45 -070036namespace art {
37
David Srbeckyd6e14e02020-07-01 13:19:17 +010038// If you want to take a look at the differences between the ART assembler and clang,
39// set this flag to true. The disassembled files will then remain in the tmp directory.
Andreas Gampe03b9ee42015-04-24 21:41:45 -070040static constexpr bool kKeepDisassembledFiles = false;
41
Andreas Gampe03b9ee42015-04-24 21:41:45 -070042// We put this into a class as gtests are self-contained, so this helper needs to be in an h-file.
David Srbeckyd6e14e02020-07-01 13:19:17 +010043class AssemblerTestBase : public testing::Test {
Andreas Gampe03b9ee42015-04-24 21:41:45 -070044 public:
David Srbeckyd6e14e02020-07-01 13:19:17 +010045 AssemblerTestBase() {}
46
47 void SetUp() override {
48 // Fake a runtime test for ScratchDir.
49 CommonArtTest::SetUpAndroidRootEnvVars();
Neil Fuller26c43772018-11-23 17:56:43 +000050 CommonRuntimeTest::SetUpAndroidDataDir(android_data_);
David Srbeckyd6e14e02020-07-01 13:19:17 +010051 scratch_dir_.emplace(/*keep_files=*/ kKeepDisassembledFiles);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070052 }
53
David Srbeckyd6e14e02020-07-01 13:19:17 +010054 void TearDown() override {
Andreas Gampe03b9ee42015-04-24 21:41:45 -070055 // We leave temporaries in case this failed so we can debug issues.
Neil Fuller26c43772018-11-23 17:56:43 +000056 CommonRuntimeTest::TearDownAndroidDataDir(android_data_, false);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070057 }
58
59 // This is intended to be run as a test.
60 bool CheckTools() {
David Srbeckyd6e14e02020-07-01 13:19:17 +010061 for (auto cmd : { GetAssemblerCommand()[0], GetDisassemblerCommand()[0] }) {
62 if (!OS::FileExists(cmd.c_str())) {
63 LOG(ERROR) << "Could not find " << cmd;
Andreas Gampe03b9ee42015-04-24 21:41:45 -070064 return false;
65 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -070066 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -070067 return true;
68 }
69
70 // Driver() assembles and compares the results. If the results are not equal and we have a
71 // disassembler, disassemble both and check whether they have the same mnemonics (in which case
72 // we just warn).
David Srbeckyd6e14e02020-07-01 13:19:17 +010073 void Driver(const std::vector<uint8_t>& art_code,
Andreas Gampe2e965ac2016-11-03 17:24:15 -070074 const std::string& assembly_text,
75 const std::string& test_name) {
David Srbeckyd6e14e02020-07-01 13:19:17 +010076 ASSERT_NE(assembly_text.length(), 0U) << "Empty assembly";
77 InstructionSet isa = GetIsa();
78 auto test_path = [&](const char* ext) { return scratch_dir_->GetPath() + test_name + ext; };
Andreas Gampe03b9ee42015-04-24 21:41:45 -070079
David Srbeckyd6e14e02020-07-01 13:19:17 +010080 // Create file containing the reference source code.
81 std::string ref_asm_file = test_path(".ref.S");
82 WriteFile(ref_asm_file, assembly_text.data(), assembly_text.size());
Andreas Gampe03b9ee42015-04-24 21:41:45 -070083
David Srbeckyd6e14e02020-07-01 13:19:17 +010084 // Assemble reference object file.
85 std::string ref_obj_file = test_path(".ref.o");
86 ASSERT_TRUE(Assemble(ref_asm_file.c_str(), ref_obj_file.c_str()));
87
88 // Read the code produced by assembler from the ELF file.
89 std::vector<uint8_t> ref_code;
90 if (Is64BitInstructionSet(isa)) {
91 ReadElf</*IsElf64=*/true>(ref_obj_file, &ref_code);
92 } else {
93 ReadElf</*IsElf64=*/false>(ref_obj_file, &ref_code);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070094 }
95
David Srbeckyd6e14e02020-07-01 13:19:17 +010096 // Compare the ART generated code to the expected reference code.
97 if (art_code == ref_code) {
98 return; // Success!
99 }
100
101 // Create ELF file containing the ART code.
102 std::string art_obj_file = test_path(".art.o");
103 if (Is64BitInstructionSet(isa)) {
104 WriteElf</*IsElf64=*/true>(art_obj_file, isa, art_code);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700105 } else {
David Srbeckyd6e14e02020-07-01 13:19:17 +0100106 WriteElf</*IsElf64=*/false>(art_obj_file, isa, art_code);
107 }
108
109 // Disassemble both object files, and check that the outputs match.
110 std::string art_disassembly;
111 ASSERT_TRUE(Disassemble(art_obj_file, &art_disassembly));
112 art_disassembly = Replace(art_disassembly, art_obj_file, test_path("<extension-redacted>"));
113 std::string ref_disassembly;
114 ASSERT_TRUE(Disassemble(ref_obj_file, &ref_disassembly));
115 ref_disassembly = Replace(ref_disassembly, ref_obj_file, test_path("<extension-redacted>"));
116 ASSERT_EQ(art_disassembly, ref_disassembly) << "Outputs (and disassembly) not identical.";
117
118 // ART produced different (but valid) code than the reference assembler, report it.
119 if (art_code.size() > ref_code.size()) {
120 EXPECT_TRUE(false) << "ART code is larger then the reference code, but the disassembly"
121 "of machine code is equal: this means that ART is generating sub-optimal encoding! "
122 "ART code size=" << art_code.size() << ", reference code size=" << ref_code.size();
123 } else if (art_code.size() < ref_code.size()) {
124 EXPECT_TRUE(false) << "ART code is smaller than the reference code. Too good to be true?";
125 } else {
126 LOG(INFO) << "Reference assembler chose a different encoding than ART (of the same size)";
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700127 }
128 }
129
130 protected:
David Srbeckyd6e14e02020-07-01 13:19:17 +0100131 virtual InstructionSet GetIsa() = 0;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700132
David Srbeckyd6e14e02020-07-01 13:19:17 +0100133 std::string FindTool(const std::string& tool_name) {
David Srbecky194f5552020-07-07 01:10:07 +0100134 return CommonArtTest::GetAndroidTool(tool_name.c_str(), GetIsa());
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700135 }
136
David Srbeckyd6e14e02020-07-01 13:19:17 +0100137 virtual std::vector<std::string> GetAssemblerCommand() {
David Srbecky194f5552020-07-07 01:10:07 +0100138 switch (GetIsa()) {
139 case InstructionSet::kX86:
140 return {FindTool("as"), "--32"};
141 case InstructionSet::kX86_64:
142 return {FindTool("as"), "--64"};
143 default:
144 return {FindTool("as")};
145 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700146 }
147
David Srbeckyd6e14e02020-07-01 13:19:17 +0100148 virtual std::vector<std::string> GetDisassemblerCommand() {
David Srbecky194f5552020-07-07 01:10:07 +0100149 switch (GetIsa()) {
150 case InstructionSet::kThumb2:
151 return {FindTool("objdump"), "--disassemble", "-M", "force-thumb"};
152 default:
153 return {FindTool("objdump"), "--disassemble", "--no-show-raw-insn"};
154 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700155 }
156
David Srbeckyd6e14e02020-07-01 13:19:17 +0100157 bool Assemble(const std::string& asm_file, const std::string& obj_file) {
158 std::vector<std::string> args = GetAssemblerCommand();
159 args.insert(args.end(), {"-o", obj_file, asm_file});
160 std::string output;
David Srbecky194f5552020-07-07 01:10:07 +0100161 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess();
162 if (!ok) {
163 LOG(ERROR) << "Assembler error:\n" << output;
164 }
165 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700166 }
167
David Srbeckyd6e14e02020-07-01 13:19:17 +0100168 bool Disassemble(const std::string& obj_file, std::string* output) {
169 std::vector<std::string> args = GetDisassemblerCommand();
170 args.insert(args.end(), {obj_file});
David Srbecky194f5552020-07-07 01:10:07 +0100171 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess();
172 if (!ok) {
173 LOG(ERROR) << "Disassembler error:\n" << *output;
174 }
175 *output = Replace(*output, "\t", " ");
176 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700177 }
178
David Srbeckyd6e14e02020-07-01 13:19:17 +0100179 std::vector<uint8_t> ReadFile(const std::string& filename) {
180 std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str()));
181 CHECK(file.get() != nullptr);
182 std::vector<uint8_t> data(file->GetLength());
183 bool success = file->ReadFully(&data[0], data.size());
184 CHECK(success) << filename;
185 return data;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700186 }
187
David Srbeckyd6e14e02020-07-01 13:19:17 +0100188 void WriteFile(const std::string& filename, const void* data, size_t size) {
189 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
190 CHECK(file.get() != nullptr);
191 bool success = file->WriteFully(data, size);
192 CHECK(success) << filename;
193 CHECK_EQ(file->FlushClose(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700194 }
195
David Srbeckyd6e14e02020-07-01 13:19:17 +0100196 // Helper method which reads the content of .text section from ELF file.
197 template<bool IsElf64>
198 void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) {
199 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
200 std::vector<uint8_t> data = ReadFile(filename);
201 ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data)));
202 const typename ElfTypes::Shdr* text = reader.GetSection(".text");
203 CHECK(text != nullptr);
204 *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700205 }
206
David Srbeckyd6e14e02020-07-01 13:19:17 +0100207 // Helper method to create an ELF file containing only the given code in the .text section.
208 template<bool IsElf64>
209 void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) {
210 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
211 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
212 CHECK(file.get() != nullptr);
213 FileOutputStream out(file.get());
214 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
215 builder->Start(/* write_program_headers= */ false);
216 builder->GetText()->Start();
217 builder->GetText()->WriteFully(code.data(), code.size());
218 builder->GetText()->End();
219 builder->End();
220 CHECK(builder->Good());
221 CHECK_EQ(file->Close(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700222 }
223
224 static std::string GetRootPath() {
225 // 1) Check ANDROID_BUILD_TOP
226 char* build_top = getenv("ANDROID_BUILD_TOP");
227 if (build_top != nullptr) {
228 return std::string(build_top) + "/";
229 }
230
231 // 2) Do cwd
232 char temp[1024];
233 return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
234 }
235
David Srbecky194f5552020-07-07 01:10:07 +0100236 std::string Replace(const std::string& str, const std::string& from, const std::string& to) {
237 std::string output;
238 size_t pos = 0;
239 for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) {
240 output += str.substr(pos, match - pos);
241 output += to;
242 pos = match + from.size();
243 }
244 output += str.substr(pos, str.size() - pos);
245 return output;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700246 }
247
David Srbeckyd6e14e02020-07-01 13:19:17 +0100248 std::optional<ScratchDir> scratch_dir_;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700249 std::string android_data_;
David Srbeckyd6e14e02020-07-01 13:19:17 +0100250 DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700251};
252
253} // namespace art
254
255#endif // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_