blob: 736a29266746f642bdc86a580bcdc7f14626f309 [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 Srbeckyb461b532020-07-13 17:45:22 +0000138 InstructionSet isa = GetIsa();
139 switch (isa) {
David Srbecky194f5552020-07-07 01:10:07 +0100140 case InstructionSet::kX86:
David Srbeckyb461b532020-07-13 17:45:22 +0000141 return {FindTool("clang"), "--compile", "-target", "i386-linux-gnu"};
David Srbecky194f5552020-07-07 01:10:07 +0100142 case InstructionSet::kX86_64:
David Srbeckyb461b532020-07-13 17:45:22 +0000143 return {FindTool("clang"), "--compile", "-target", "x86_64-linux-gnu"};
David Srbecky194f5552020-07-07 01:10:07 +0100144 default:
David Srbeckyb461b532020-07-13 17:45:22 +0000145 LOG(FATAL) << "Unknown instruction set: " << isa;
146 UNREACHABLE();
David Srbecky194f5552020-07-07 01:10:07 +0100147 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700148 }
149
David Srbeckyd6e14e02020-07-01 13:19:17 +0100150 virtual std::vector<std::string> GetDisassemblerCommand() {
David Srbecky194f5552020-07-07 01:10:07 +0100151 switch (GetIsa()) {
152 case InstructionSet::kThumb2:
David Srbeckyb461b532020-07-13 17:45:22 +0000153 return {FindTool("llvm-objdump"), "--disassemble", "-triple", "thumbv7a-linux-gnueabi"};
David Srbecky194f5552020-07-07 01:10:07 +0100154 default:
David Srbeckyb461b532020-07-13 17:45:22 +0000155 return {FindTool("llvm-objdump"), "--disassemble", "--no-show-raw-insn"};
David Srbecky194f5552020-07-07 01:10:07 +0100156 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700157 }
158
David Srbeckyd6e14e02020-07-01 13:19:17 +0100159 bool Assemble(const std::string& asm_file, const std::string& obj_file) {
160 std::vector<std::string> args = GetAssemblerCommand();
161 args.insert(args.end(), {"-o", obj_file, asm_file});
162 std::string output;
David Srbecky194f5552020-07-07 01:10:07 +0100163 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess();
164 if (!ok) {
165 LOG(ERROR) << "Assembler error:\n" << output;
166 }
167 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700168 }
169
David Srbeckyd6e14e02020-07-01 13:19:17 +0100170 bool Disassemble(const std::string& obj_file, std::string* output) {
171 std::vector<std::string> args = GetDisassemblerCommand();
172 args.insert(args.end(), {obj_file});
David Srbecky194f5552020-07-07 01:10:07 +0100173 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess();
174 if (!ok) {
175 LOG(ERROR) << "Disassembler error:\n" << *output;
176 }
177 *output = Replace(*output, "\t", " ");
178 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700179 }
180
David Srbeckyd6e14e02020-07-01 13:19:17 +0100181 std::vector<uint8_t> ReadFile(const std::string& filename) {
182 std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str()));
183 CHECK(file.get() != nullptr);
184 std::vector<uint8_t> data(file->GetLength());
185 bool success = file->ReadFully(&data[0], data.size());
186 CHECK(success) << filename;
187 return data;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700188 }
189
David Srbeckyd6e14e02020-07-01 13:19:17 +0100190 void WriteFile(const std::string& filename, const void* data, size_t size) {
191 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
192 CHECK(file.get() != nullptr);
193 bool success = file->WriteFully(data, size);
194 CHECK(success) << filename;
195 CHECK_EQ(file->FlushClose(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700196 }
197
David Srbeckyd6e14e02020-07-01 13:19:17 +0100198 // Helper method which reads the content of .text section from ELF file.
199 template<bool IsElf64>
200 void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) {
201 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
202 std::vector<uint8_t> data = ReadFile(filename);
203 ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data)));
204 const typename ElfTypes::Shdr* text = reader.GetSection(".text");
205 CHECK(text != nullptr);
206 *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700207 }
208
David Srbeckyd6e14e02020-07-01 13:19:17 +0100209 // Helper method to create an ELF file containing only the given code in the .text section.
210 template<bool IsElf64>
211 void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) {
212 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
213 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
214 CHECK(file.get() != nullptr);
215 FileOutputStream out(file.get());
216 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
217 builder->Start(/* write_program_headers= */ false);
218 builder->GetText()->Start();
219 builder->GetText()->WriteFully(code.data(), code.size());
220 builder->GetText()->End();
221 builder->End();
222 CHECK(builder->Good());
223 CHECK_EQ(file->Close(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700224 }
225
226 static std::string GetRootPath() {
227 // 1) Check ANDROID_BUILD_TOP
228 char* build_top = getenv("ANDROID_BUILD_TOP");
229 if (build_top != nullptr) {
230 return std::string(build_top) + "/";
231 }
232
233 // 2) Do cwd
234 char temp[1024];
235 return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
236 }
237
David Srbecky194f5552020-07-07 01:10:07 +0100238 std::string Replace(const std::string& str, const std::string& from, const std::string& to) {
239 std::string output;
240 size_t pos = 0;
241 for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) {
242 output += str.substr(pos, match - pos);
243 output += to;
244 pos = match + from.size();
245 }
246 output += str.substr(pos, str.size() - pos);
247 return output;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700248 }
249
David Srbeckyd6e14e02020-07-01 13:19:17 +0100250 std::optional<ScratchDir> scratch_dir_;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700251 std::string android_data_;
David Srbeckyd6e14e02020-07-01 13:19:17 +0100252 DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700253};
254
255} // namespace art
256
257#endif // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_