blob: de19d660a787fb0933fd2dc4682b831813d36101 [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>
Yi Kongfde4c272021-09-09 15:41:10 +080025#include <regex>
Andreas Gampe03b9ee42015-04-24 21:41:45 -070026
Andreas Gampe9186ced2016-12-12 14:28:21 -080027#include "android-base/strings.h"
28
David Srbeckyd6e14e02020-07-01 13:19:17 +010029#include "base/os.h"
David Sehrc431b9d2018-03-02 12:01:51 -080030#include "base/utils.h"
David Srbeckyd6e14e02020-07-01 13:19:17 +010031#include "common_runtime_test.h" // For ScratchDir.
32#include "elf/elf_builder.h"
33#include "elf/elf_debug_reader.h"
David Sehr97c381e2017-02-01 15:09:58 -080034#include "exec_utils.h"
David Srbeckyd6e14e02020-07-01 13:19:17 +010035#include "stream/file_output_stream.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010036
Andreas Gampe03b9ee42015-04-24 21:41:45 -070037namespace art {
38
David Srbeckyd6e14e02020-07-01 13:19:17 +010039// If you want to take a look at the differences between the ART assembler and clang,
40// set this flag to true. The disassembled files will then remain in the tmp directory.
Andreas Gampe03b9ee42015-04-24 21:41:45 -070041static constexpr bool kKeepDisassembledFiles = false;
42
Andreas Gampe03b9ee42015-04-24 21:41:45 -070043// 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 +010044class AssemblerTestBase : public testing::Test {
Andreas Gampe03b9ee42015-04-24 21:41:45 -070045 public:
David Srbeckyd6e14e02020-07-01 13:19:17 +010046 AssemblerTestBase() {}
47
48 void SetUp() override {
49 // Fake a runtime test for ScratchDir.
50 CommonArtTest::SetUpAndroidRootEnvVars();
Neil Fuller26c43772018-11-23 17:56:43 +000051 CommonRuntimeTest::SetUpAndroidDataDir(android_data_);
David Srbeckyd6e14e02020-07-01 13:19:17 +010052 scratch_dir_.emplace(/*keep_files=*/ kKeepDisassembledFiles);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070053 }
54
David Srbeckyd6e14e02020-07-01 13:19:17 +010055 void TearDown() override {
Andreas Gampe03b9ee42015-04-24 21:41:45 -070056 // We leave temporaries in case this failed so we can debug issues.
Neil Fuller26c43772018-11-23 17:56:43 +000057 CommonRuntimeTest::TearDownAndroidDataDir(android_data_, false);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070058 }
59
60 // This is intended to be run as a test.
61 bool CheckTools() {
Stefano Cianciulli944df152022-06-29 08:48:55 +000062 for (const std::string& cmd : { GetAssemblerCommand()[0], GetDisassemblerCommand()[0] }) {
David Srbeckyd6e14e02020-07-01 13:19:17 +010063 if (!OS::FileExists(cmd.c_str())) {
64 LOG(ERROR) << "Could not find " << cmd;
Andreas Gampe03b9ee42015-04-24 21:41:45 -070065 return false;
66 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -070067 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -070068 return true;
69 }
70
71 // Driver() assembles and compares the results. If the results are not equal and we have a
72 // disassembler, disassemble both and check whether they have the same mnemonics (in which case
73 // we just warn).
David Srbeckyd6e14e02020-07-01 13:19:17 +010074 void Driver(const std::vector<uint8_t>& art_code,
Andreas Gampe2e965ac2016-11-03 17:24:15 -070075 const std::string& assembly_text,
76 const std::string& test_name) {
David Srbeckyd6e14e02020-07-01 13:19:17 +010077 ASSERT_NE(assembly_text.length(), 0U) << "Empty assembly";
78 InstructionSet isa = GetIsa();
79 auto test_path = [&](const char* ext) { return scratch_dir_->GetPath() + test_name + ext; };
Andreas Gampe03b9ee42015-04-24 21:41:45 -070080
David Srbeckyd6e14e02020-07-01 13:19:17 +010081 // Create file containing the reference source code.
82 std::string ref_asm_file = test_path(".ref.S");
83 WriteFile(ref_asm_file, assembly_text.data(), assembly_text.size());
Andreas Gampe03b9ee42015-04-24 21:41:45 -070084
David Srbeckyd6e14e02020-07-01 13:19:17 +010085 // Assemble reference object file.
86 std::string ref_obj_file = test_path(".ref.o");
87 ASSERT_TRUE(Assemble(ref_asm_file.c_str(), ref_obj_file.c_str()));
88
89 // Read the code produced by assembler from the ELF file.
90 std::vector<uint8_t> ref_code;
91 if (Is64BitInstructionSet(isa)) {
92 ReadElf</*IsElf64=*/true>(ref_obj_file, &ref_code);
93 } else {
94 ReadElf</*IsElf64=*/false>(ref_obj_file, &ref_code);
Andreas Gampe03b9ee42015-04-24 21:41:45 -070095 }
96
David Srbeckyd6e14e02020-07-01 13:19:17 +010097 // Compare the ART generated code to the expected reference code.
98 if (art_code == ref_code) {
99 return; // Success!
100 }
101
102 // Create ELF file containing the ART code.
103 std::string art_obj_file = test_path(".art.o");
104 if (Is64BitInstructionSet(isa)) {
105 WriteElf</*IsElf64=*/true>(art_obj_file, isa, art_code);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700106 } else {
David Srbeckyd6e14e02020-07-01 13:19:17 +0100107 WriteElf</*IsElf64=*/false>(art_obj_file, isa, art_code);
108 }
109
110 // Disassemble both object files, and check that the outputs match.
111 std::string art_disassembly;
112 ASSERT_TRUE(Disassemble(art_obj_file, &art_disassembly));
113 art_disassembly = Replace(art_disassembly, art_obj_file, test_path("<extension-redacted>"));
Yi Kongfde4c272021-09-09 15:41:10 +0800114 art_disassembly = StripComments(art_disassembly);
David Srbeckyd6e14e02020-07-01 13:19:17 +0100115 std::string ref_disassembly;
116 ASSERT_TRUE(Disassemble(ref_obj_file, &ref_disassembly));
117 ref_disassembly = Replace(ref_disassembly, ref_obj_file, test_path("<extension-redacted>"));
Yi Kongfde4c272021-09-09 15:41:10 +0800118 ref_disassembly = StripComments(ref_disassembly);
David Srbeckyd6e14e02020-07-01 13:19:17 +0100119 ASSERT_EQ(art_disassembly, ref_disassembly) << "Outputs (and disassembly) not identical.";
120
121 // ART produced different (but valid) code than the reference assembler, report it.
122 if (art_code.size() > ref_code.size()) {
123 EXPECT_TRUE(false) << "ART code is larger then the reference code, but the disassembly"
124 "of machine code is equal: this means that ART is generating sub-optimal encoding! "
125 "ART code size=" << art_code.size() << ", reference code size=" << ref_code.size();
126 } else if (art_code.size() < ref_code.size()) {
127 EXPECT_TRUE(false) << "ART code is smaller than the reference code. Too good to be true?";
128 } else {
129 LOG(INFO) << "Reference assembler chose a different encoding than ART (of the same size)";
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700130 }
131 }
132
133 protected:
David Srbeckyd6e14e02020-07-01 13:19:17 +0100134 virtual InstructionSet GetIsa() = 0;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700135
David Srbeckyd6e14e02020-07-01 13:19:17 +0100136 std::string FindTool(const std::string& tool_name) {
David Srbecky194f5552020-07-07 01:10:07 +0100137 return CommonArtTest::GetAndroidTool(tool_name.c_str(), GetIsa());
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700138 }
139
David Srbeckyd6e14e02020-07-01 13:19:17 +0100140 virtual std::vector<std::string> GetAssemblerCommand() {
David Srbeckyb461b532020-07-13 17:45:22 +0000141 InstructionSet isa = GetIsa();
142 switch (isa) {
David Srbecky194f5552020-07-07 01:10:07 +0100143 case InstructionSet::kX86:
David Srbeckyb461b532020-07-13 17:45:22 +0000144 return {FindTool("clang"), "--compile", "-target", "i386-linux-gnu"};
David Srbecky194f5552020-07-07 01:10:07 +0100145 case InstructionSet::kX86_64:
David Srbeckyb461b532020-07-13 17:45:22 +0000146 return {FindTool("clang"), "--compile", "-target", "x86_64-linux-gnu"};
David Srbecky194f5552020-07-07 01:10:07 +0100147 default:
David Srbeckyb461b532020-07-13 17:45:22 +0000148 LOG(FATAL) << "Unknown instruction set: " << isa;
149 UNREACHABLE();
David Srbecky194f5552020-07-07 01:10:07 +0100150 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700151 }
152
David Srbeckyd6e14e02020-07-01 13:19:17 +0100153 virtual std::vector<std::string> GetDisassemblerCommand() {
David Srbecky194f5552020-07-07 01:10:07 +0100154 switch (GetIsa()) {
155 case InstructionSet::kThumb2:
Stephen Hines331c8e32020-09-11 17:03:58 -0700156 return {FindTool("llvm-objdump"), "--disassemble", "--triple", "thumbv7a-linux-gnueabi"};
David Srbecky194f5552020-07-07 01:10:07 +0100157 default:
David Srbeckyb461b532020-07-13 17:45:22 +0000158 return {FindTool("llvm-objdump"), "--disassemble", "--no-show-raw-insn"};
David Srbecky194f5552020-07-07 01:10:07 +0100159 }
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700160 }
161
David Srbeckyd6e14e02020-07-01 13:19:17 +0100162 bool Assemble(const std::string& asm_file, const std::string& obj_file) {
163 std::vector<std::string> args = GetAssemblerCommand();
164 args.insert(args.end(), {"-o", obj_file, asm_file});
165 std::string output;
David Srbecky194f5552020-07-07 01:10:07 +0100166 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess();
167 if (!ok) {
168 LOG(ERROR) << "Assembler error:\n" << output;
169 }
170 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700171 }
172
David Srbeckyd6e14e02020-07-01 13:19:17 +0100173 bool Disassemble(const std::string& obj_file, std::string* output) {
174 std::vector<std::string> args = GetDisassemblerCommand();
175 args.insert(args.end(), {obj_file});
David Srbecky194f5552020-07-07 01:10:07 +0100176 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess();
177 if (!ok) {
178 LOG(ERROR) << "Disassembler error:\n" << *output;
179 }
180 *output = Replace(*output, "\t", " ");
181 return ok;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700182 }
183
David Srbeckyd6e14e02020-07-01 13:19:17 +0100184 std::vector<uint8_t> ReadFile(const std::string& filename) {
185 std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str()));
186 CHECK(file.get() != nullptr);
187 std::vector<uint8_t> data(file->GetLength());
188 bool success = file->ReadFully(&data[0], data.size());
189 CHECK(success) << filename;
190 return data;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700191 }
192
David Srbeckyd6e14e02020-07-01 13:19:17 +0100193 void WriteFile(const std::string& filename, const void* data, size_t size) {
194 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
195 CHECK(file.get() != nullptr);
196 bool success = file->WriteFully(data, size);
197 CHECK(success) << filename;
198 CHECK_EQ(file->FlushClose(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700199 }
200
David Srbeckyd6e14e02020-07-01 13:19:17 +0100201 // Helper method which reads the content of .text section from ELF file.
202 template<bool IsElf64>
203 void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) {
204 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
205 std::vector<uint8_t> data = ReadFile(filename);
206 ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data)));
207 const typename ElfTypes::Shdr* text = reader.GetSection(".text");
208 CHECK(text != nullptr);
209 *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700210 }
211
David Srbeckyd6e14e02020-07-01 13:19:17 +0100212 // Helper method to create an ELF file containing only the given code in the .text section.
213 template<bool IsElf64>
214 void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) {
215 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
216 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
217 CHECK(file.get() != nullptr);
218 FileOutputStream out(file.get());
219 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
220 builder->Start(/* write_program_headers= */ false);
221 builder->GetText()->Start();
222 builder->GetText()->WriteFully(code.data(), code.size());
223 builder->GetText()->End();
224 builder->End();
225 CHECK(builder->Good());
226 CHECK_EQ(file->Close(), 0);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700227 }
228
229 static std::string GetRootPath() {
230 // 1) Check ANDROID_BUILD_TOP
231 char* build_top = getenv("ANDROID_BUILD_TOP");
232 if (build_top != nullptr) {
233 return std::string(build_top) + "/";
234 }
235
236 // 2) Do cwd
237 char temp[1024];
238 return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
239 }
240
David Srbecky194f5552020-07-07 01:10:07 +0100241 std::string Replace(const std::string& str, const std::string& from, const std::string& to) {
242 std::string output;
243 size_t pos = 0;
244 for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) {
245 output += str.substr(pos, match - pos);
246 output += to;
247 pos = match + from.size();
248 }
249 output += str.substr(pos, str.size() - pos);
250 return output;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700251 }
252
Yi Kongfde4c272021-09-09 15:41:10 +0800253 // Remove comments emitted by objdump.
254 std::string StripComments(const std::string& str) {
Yi Kong7fae86c2021-09-11 01:42:49 +0800255 return std::regex_replace(str, std::regex(" +# .*"), "");
Yi Kongfde4c272021-09-09 15:41:10 +0800256 }
257
David Srbeckyd6e14e02020-07-01 13:19:17 +0100258 std::optional<ScratchDir> scratch_dir_;
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700259 std::string android_data_;
David Srbeckyd6e14e02020-07-01 13:19:17 +0100260 DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase);
Andreas Gampe03b9ee42015-04-24 21:41:45 -0700261};
262
263} // namespace art
264
265#endif // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_