• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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       EXPECT_TRUE(false) << "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       EXPECT_TRUE(false) << "ART code is smaller than the reference code. Too good to be true?";
129     } else {
130       LOG(INFO) << "Reference assembler chose a different encoding than ART (of the same size)";
131     }
132   }
133 
134  protected:
135   virtual InstructionSet GetIsa() = 0;
136 
FindTool(const std::string & tool_name)137   std::string FindTool(const std::string& tool_name) {
138     return CommonArtTest::GetAndroidTool(tool_name.c_str(), GetIsa());
139   }
140 
GetAssemblerCommand()141   virtual std::vector<std::string> GetAssemblerCommand() {
142     InstructionSet isa = GetIsa();
143     switch (isa) {
144       case InstructionSet::kX86:
145         return {FindTool("clang"), "--compile", "-target", "i386-linux-gnu"};
146       case InstructionSet::kX86_64:
147         return {FindTool("clang"), "--compile", "-target", "x86_64-linux-gnu"};
148       default:
149         LOG(FATAL) << "Unknown instruction set: " << isa;
150         UNREACHABLE();
151     }
152   }
153 
GetDisassemblerCommand()154   virtual std::vector<std::string> GetDisassemblerCommand() {
155     switch (GetIsa()) {
156       case InstructionSet::kThumb2:
157         return {FindTool("llvm-objdump"),
158                 "--disassemble",
159                 "--no-print-imm-hex",
160                 "--triple",
161                 "thumbv7a-linux-gnueabi"};
162       default:
163         return {
164             FindTool("llvm-objdump"), "--disassemble", "--no-print-imm-hex", "--no-show-raw-insn"};
165     }
166   }
167 
Assemble(const std::string & asm_file,const std::string & obj_file)168   bool Assemble(const std::string& asm_file, const std::string& obj_file) {
169     std::vector<std::string> args = GetAssemblerCommand();
170     args.insert(args.end(), {"-o", obj_file, asm_file});
171     std::string output;
172     bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, &output).StandardSuccess();
173     if (!ok) {
174       LOG(ERROR) << "Assembler error:\n" << output;
175     }
176     return ok;
177   }
178 
Disassemble(const std::string & obj_file,std::string * output)179   bool Disassemble(const std::string& obj_file, std::string* output) {
180     std::vector<std::string> args = GetDisassemblerCommand();
181     args.insert(args.end(), {obj_file});
182     bool ok = CommonArtTestImpl::ForkAndExec(args, [](){ return true; }, output).StandardSuccess();
183     if (!ok) {
184       LOG(ERROR) << "Disassembler error:\n" << *output;
185     }
186     *output = Replace(*output, "\t", " ");
187     return ok;
188   }
189 
ReadFile(const std::string & filename)190   std::vector<uint8_t> ReadFile(const std::string& filename) {
191     std::unique_ptr<File> file(OS::OpenFileForReading(filename.c_str()));
192     CHECK(file.get() != nullptr);
193     std::vector<uint8_t> data(file->GetLength());
194     bool success = file->ReadFully(&data[0], data.size());
195     CHECK(success) << filename;
196     return data;
197   }
198 
WriteFile(const std::string & filename,const void * data,size_t size)199   void WriteFile(const std::string& filename, const void* data, size_t size) {
200     std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
201     CHECK(file.get() != nullptr);
202     bool success = file->WriteFully(data, size);
203     CHECK(success) << filename;
204     CHECK_EQ(file->FlushClose(), 0);
205   }
206 
207   // Helper method which reads the content of .text section from ELF file.
208   template<bool IsElf64>
ReadElf(const std::string & filename,std::vector<uint8_t> * code)209   void ReadElf(const std::string& filename, /*out*/ std::vector<uint8_t>* code) {
210     using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
211     std::vector<uint8_t> data = ReadFile(filename);
212     ElfDebugReader<ElfTypes> reader((ArrayRef<const uint8_t>(data)));
213     const typename ElfTypes::Shdr* text = reader.GetSection(".text");
214     CHECK(text != nullptr);
215     *code = std::vector<uint8_t>(&data[text->sh_offset], &data[text->sh_offset + text->sh_size]);
216   }
217 
218   // Helper method to create an ELF file containing only the given code in the .text section.
219   template<bool IsElf64>
WriteElf(const std::string & filename,InstructionSet isa,const std::vector<uint8_t> & code)220   void WriteElf(const std::string& filename, InstructionSet isa, const std::vector<uint8_t>& code) {
221     using ElfTypes = typename std::conditional<IsElf64, ElfTypes64, ElfTypes32>::type;
222     std::unique_ptr<File> file(OS::CreateEmptyFile(filename.c_str()));
223     CHECK(file.get() != nullptr);
224     FileOutputStream out(file.get());
225     std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(isa, &out));
226     builder->Start(/* write_program_headers= */ false);
227     builder->GetText()->Start();
228     builder->GetText()->WriteFully(code.data(), code.size());
229     builder->GetText()->End();
230     builder->End();
231     CHECK(builder->Good());
232     CHECK_EQ(file->Close(), 0);
233   }
234 
GetRootPath()235   static std::string GetRootPath() {
236     // 1) Check ANDROID_BUILD_TOP
237     char* build_top = getenv("ANDROID_BUILD_TOP");
238     if (build_top != nullptr) {
239       return std::string(build_top) + "/";
240     }
241 
242     // 2) Do cwd
243     char temp[1024];
244     return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
245   }
246 
Replace(const std::string & str,const std::string & from,const std::string & to)247   std::string Replace(const std::string& str, const std::string& from, const std::string& to) {
248     std::string output;
249     size_t pos = 0;
250     for (auto match = str.find(from); match != str.npos; match = str.find(from, pos)) {
251       output += str.substr(pos, match - pos);
252       output += to;
253       pos = match + from.size();
254     }
255     output += str.substr(pos, str.size() - pos);
256     return output;
257   }
258 
259   // Remove comments emitted by objdump.
StripComments(const std::string & str)260   std::string StripComments(const std::string& str) {
261     return std::regex_replace(str, std::regex(" +# .*"), "");
262   }
263 
264   std::optional<ScratchDir> scratch_dir_;
265   std::string android_data_;
266   DISALLOW_COPY_AND_ASSIGN(AssemblerTestBase);
267 };
268 
269 }  // namespace art
270 
271 #endif  // ART_COMPILER_UTILS_ASSEMBLER_TEST_BASE_H_
272