1 /* 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 20 #include <sys/stat.h> 21 #include <cstdio> 22 #include <cstdlib> 23 #include <fstream> 24 #include <iterator> 25 #include <regex> 26 27 #include "android-base/strings.h" 28 29 #include "base/macros.h" 30 #include "base/os.h" 31 #include "base/utils.h" 32 #include "common_runtime_test.h" // For ScratchDir. 33 #include "elf/elf_builder.h" 34 #include "elf/elf_debug_reader.h" 35 #include "exec_utils.h" 36 #include "stream/file_output_stream.h" 37 38 namespace art HIDDEN { 39 40 // If you want to take a look at the differences between the ART assembler and clang, 41 // set this flag to true. The disassembled files will then remain in the tmp directory. 42 static constexpr bool kKeepDisassembledFiles = false; 43 44 // We put this into a class as gtests are self-contained, so this helper needs to be in an h-file. 45 class AssemblerTestBase : public testing::Test { 46 public: AssemblerTestBase()47 AssemblerTestBase() {} 48 SetUp()49 void SetUp() override { 50 // Fake a runtime test for ScratchDir. 51 CommonArtTest::SetUpAndroidRootEnvVars(); 52 CommonRuntimeTest::SetUpAndroidDataDir(android_data_); 53 scratch_dir_.emplace(/*keep_files=*/ kKeepDisassembledFiles); 54 } 55 TearDown()56 void TearDown() override { 57 // We leave temporaries in case this failed so we can debug issues. 58 CommonRuntimeTest::TearDownAndroidDataDir(android_data_, false); 59 } 60 61 // This is intended to be run as a test. CheckTools()62 bool CheckTools() { 63 for (const std::string& cmd : { GetAssemblerCommand()[0], GetDisassemblerCommand()[0] }) { 64 if (!OS::FileExists(cmd.c_str())) { 65 LOG(ERROR) << "Could not find " << cmd; 66 return false; 67 } 68 } 69 return true; 70 } 71 72 // Driver() assembles and compares the results. If the results are not equal and we have a 73 // disassembler, disassemble both and check whether they have the same mnemonics (in which case 74 // we just warn). Driver(const std::vector<uint8_t> & art_code,const std::string & assembly_text,const std::string & test_name)75 void Driver(const std::vector<uint8_t>& art_code, 76 const std::string& assembly_text, 77 const std::string& test_name) { 78 ASSERT_NE(assembly_text.length(), 0U) << "Empty assembly"; 79 InstructionSet isa = GetIsa(); 80 auto test_path = [&](const char* ext) { return scratch_dir_->GetPath() + test_name + ext; }; 81 82 // Create file containing the reference source code. 83 std::string ref_asm_file = test_path(".ref.S"); 84 WriteFile(ref_asm_file, assembly_text.data(), assembly_text.size()); 85 86 // Assemble reference object file. 87 std::string ref_obj_file = test_path(".ref.o"); 88 ASSERT_TRUE(Assemble(ref_asm_file, ref_obj_file)); 89 90 // Read the code produced by assembler from the ELF file. 91 std::vector<uint8_t> ref_code; 92 if (Is64BitInstructionSet(isa)) { 93 ReadElf</*IsElf64=*/true>(ref_obj_file, &ref_code); 94 } else { 95 ReadElf</*IsElf64=*/false>(ref_obj_file, &ref_code); 96 } 97 98 // Compare the ART generated code to the expected reference code. 99 if (art_code == ref_code) { 100 return; // Success! 101 } 102 103 // Create ELF file containing the ART code. 104 std::string art_obj_file = test_path(".art.o"); 105 if (Is64BitInstructionSet(isa)) { 106 WriteElf</*IsElf64=*/true>(art_obj_file, isa, art_code); 107 } else { 108 WriteElf</*IsElf64=*/false>(art_obj_file, isa, art_code); 109 } 110 111 // Disassemble both object files, and check that the outputs match. 112 std::string art_disassembly; 113 ASSERT_TRUE(Disassemble(art_obj_file, &art_disassembly)); 114 art_disassembly = Replace(art_disassembly, art_obj_file, test_path("<extension-redacted>")); 115 art_disassembly = StripComments(art_disassembly); 116 std::string ref_disassembly; 117 ASSERT_TRUE(Disassemble(ref_obj_file, &ref_disassembly)); 118 ref_disassembly = Replace(ref_disassembly, ref_obj_file, test_path("<extension-redacted>")); 119 ref_disassembly = StripComments(ref_disassembly); 120 ASSERT_EQ(art_disassembly, ref_disassembly) << "Outputs (and disassembly) not identical."; 121 122 // ART produced different (but valid) code than the reference assembler, report it. 123 if (art_code.size() > ref_code.size()) { 124 ADD_FAILURE() << "ART code is larger then the reference code, but the disassembly" 125 "of machine code is equal: this means that ART is generating sub-optimal encoding! " 126 "ART code size=" << art_code.size() << ", reference code size=" << ref_code.size(); 127 } else if (art_code.size() < ref_code.size()) { 128 ADD_FAILURE() << "ART code is smaller than the reference code. Too good to be true?"; 129 } else if (require_same_encoding_) { 130 ADD_FAILURE() << "Reference assembler chose a different encoding than ART (of the same size)" 131 " but the test is set up to require the same encoding"; 132 } else { 133 LOG(INFO) << "Reference assembler chose a different encoding than ART (of the same size)"; 134 } 135 } 136 137 protected: 138 virtual InstructionSet GetIsa() = 0; 139 FindTool(const std::string & tool_name)140 std::string FindTool(const std::string& tool_name) { 141 return CommonArtTest::GetAndroidTool(tool_name.c_str(), GetIsa()); 142 } 143 GetAssemblerCommand()144 virtual std::vector<std::string> GetAssemblerCommand() { 145 InstructionSet isa = GetIsa(); 146 switch (isa) { 147 case InstructionSet::kRiscv64: 148 // TODO(riscv64): Support compression (RV32C) in assembler and tests (add `c` to `-march=`). 149 return {FindTool("clang"), 150 "--compile", 151 "-target", 152 "riscv64-linux-gnu", 153 "-march=rv64imafdcv_zba_zbb_zca_zcd_zcb", 154 // Force the assembler to fully emit branch instructions instead of leaving 155 // offsets unresolved with relocation information for the linker. 156 "-mno-relax"}; 157 case InstructionSet::kX86: 158 return {FindTool("clang"), "--compile", "-target", "i386-linux-gnu"}; 159 case InstructionSet::kX86_64: 160 return {FindTool("clang"), "--compile", "-target", "x86_64-linux-gnu"}; 161 default: 162 LOG(FATAL) << "Unknown instruction set: " << isa; 163 UNREACHABLE(); 164 } 165 } 166 GetDisassemblerCommand()167 virtual std::vector<std::string> GetDisassemblerCommand() { 168 switch (GetIsa()) { 169 case InstructionSet::kThumb2: 170 return {FindTool("llvm-objdump"), 171 "--disassemble", 172 "--no-print-imm-hex", 173 "--triple", 174 "thumbv7a-linux-gnueabi"}; 175 case InstructionSet::kRiscv64: 176 return {FindTool("llvm-objdump"), 177 "--disassemble", 178 "--no-print-imm-hex", 179 "--no-show-raw-insn", 180 // Disassemble Standard Extensions supported by the assembler. 181 "--mattr=+F,+D,+A,+C,+V,+Zba,+Zbb,+Zca,+Zcd,+Zcb", 182 "-M", 183 "no-aliases"}; 184 default: 185 return { 186 FindTool("llvm-objdump"), "--disassemble", "--no-print-imm-hex", "--no-show-raw-insn"}; 187 } 188 } 189 Assemble(const std::string & asm_file,const std::string & obj_file)190 bool Assemble(const std::string& asm_file, const std::string& obj_file) { 191 std::vector<std::string> args = GetAssemblerCommand(); 192 args.insert(args.end(), {"-o", obj_file, asm_file}); 193 std::string output; 194 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess(); 195 if (!ok) { 196 LOG(ERROR) << "Assembler error:\n" << output; 197 } 198 return ok; 199 } 200 Disassemble(const std::string & obj_file,std::string * output)201 bool Disassemble(const std::string& obj_file, std::string* output) { 202 std::vector<std::string> args = GetDisassemblerCommand(); 203 args.insert(args.end(), {obj_file}); 204 bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess(); 205 if (!ok) { 206 LOG(ERROR) << "Disassembler error:\n" << *output; 207 } 208 *output = Replace(*output, "\t", " "); 209 return ok; 210 } 211 ReadFile(const std::string & filename)212 std::vector<uint8_t> ReadFile(const std::string& filename) { 213 std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str())); 214 CHECK(file.get() != nullptr); 215 std::vector<uint8_t> data(file->GetLength()); 216 bool success = file->ReadFully(&data[0], data.size()); 217 CHECK(success) << filename; 218 return data; 219 } 220 WriteFile(const std::string & filename,const void * data,size_t size)221 void WriteFile(const std::string& filename, const void* data, size_t size) { 222 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str())); 223 CHECK(file.get() != nullptr); 224 bool success = file->WriteFully(data, size); 225 CHECK(success) << filename; 226 CHECK_EQ(file->FlushClose(), 0); 227 } 228 229 // Helper method which reads the content of .text section from ELF file. 230 template<bool IsElf64> ReadElf(const std::string & filename,std::vector<uint8_t> * code)231 void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) { 232 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type; 233 std::vector<uint8_t> data = ReadFile(filename); 234 ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data))); 235 const typename ElfTypes::Shdr* text = reader.GetSection(".text"); 236 CHECK(text != nullptr); 237 *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]); 238 } 239 240 // Helper method to create an ELF file containing only the given code in the .text section. 241 template<bool IsElf64> WriteElf(const std::string & filename,InstructionSet isa,const std::vector<uint8_t> & code)242 void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) { 243 using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type; 244 std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str())); 245 CHECK(file.get() != nullptr); 246 FileOutputStream out(file.get()); 247 std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out)); 248 builder->Start(/* write_program_headers= */ false); 249 builder->GetText()->Start(); 250 builder->GetText()->WriteFully(code.data(), code.size()); 251 builder->GetText()->End(); 252 builder->End(); 253 CHECK(builder->Good()); 254 CHECK_EQ(file->Close(), 0); 255 } 256 GetRootPath()257 static std::string GetRootPath() { 258 // 1) Check ANDROID_BUILD_TOP 259 char* build_top = getenv("ANDROID_BUILD_TOP"); 260 if (build_top != nullptr) { 261 return std::string(build_top) + "/"; 262 } 263 264 // 2) Do cwd 265 char temp[1024]; 266 return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string(""); 267 } 268 Replace(const std::string & str,const std::string & from,const std::string & to)269 std::string Replace(const std::string& str, const std::string& from, const std::string& to) { 270 std::string output; 271 size_t pos = 0; 272 for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) { 273 output += str.substr(pos, match - pos); 274 output += to; 275 pos = match + from.size(); 276 } 277 output += str.substr(pos, str.size() - pos); 278 return output; 279 } 280 281 // Remove comments emitted by objdump. StripComments(const std::string & str)282 std::string StripComments(const std::string& str) { 283 return std::regex_replace(str, std::regex(" +# .*"), ""); 284 } 285 286 std::optional<ScratchDir> scratch_dir_; 287 std::string android_data_; 288 bool require_same_encoding_ = true; 289 DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase); 290 }; 291 292 } // namespace art 293 294 #endif // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_ 295