blob: 05ac70ed74bf98beef65276401512a54f88f3d56 [file] [log] [blame]
Andreas Gampe5a4fa822014-03-31 16:50:12 -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_H_
18#define ART_COMPILER_UTILS_ASSEMBLER_TEST_H_
19
20#include "assembler.h"
21
Andreas Gampeb40c6a72014-05-02 14:25:12 -070022#include "common_runtime_test.h" // For ScratchFile
Andreas Gampe5a4fa822014-03-31 16:50:12 -070023
24#include <cstdio>
25#include <cstdlib>
26#include <fstream>
27#include <iostream>
28#include <iterator>
29#include <sys/stat.h>
30
31namespace art {
32
Andreas Gampeb40c6a72014-05-02 14:25:12 -070033// Use a glocal static variable to keep the same name for all test data. Else we'll just spam the
34// temp directory.
35static std::string tmpnam_;
36
Andreas Gampe5a4fa822014-03-31 16:50:12 -070037template<typename Ass, typename Reg, typename Imm>
38class AssemblerTest : public testing::Test {
39 public:
40 Ass* GetAssembler() {
41 return assembler_.get();
42 }
43
44 typedef std::string (*TestFn)(Ass* assembler);
45
46 void DriverFn(TestFn f, std::string test_name) {
47 Driver(f(assembler_.get()), test_name);
48 }
49
50 // This driver assumes the assembler has already been called.
51 void DriverStr(std::string assembly_string, std::string test_name) {
52 Driver(assembly_string, test_name);
53 }
54
55 std::string RepeatR(void (Ass::*f)(Reg), std::string fmt) {
56 const std::vector<Reg*> registers = GetRegisters();
57 std::string str;
58 for (auto reg : registers) {
59 (assembler_.get()->*f)(*reg);
60 std::string base = fmt;
61
62 size_t reg_index = base.find("{reg}");
63 if (reg_index != std::string::npos) {
64 std::ostringstream sreg;
65 sreg << *reg;
66 std::string reg_string = sreg.str();
67 base.replace(reg_index, 5, reg_string);
68 }
69
70 if (str.size() > 0) {
71 str += "\n";
72 }
73 str += base;
74 }
75 // Add a newline at the end.
76 str += "\n";
77 return str;
78 }
79
80 std::string RepeatRR(void (Ass::*f)(Reg, Reg), std::string fmt) {
81 const std::vector<Reg*> registers = GetRegisters();
82 std::string str;
83 for (auto reg1 : registers) {
84 for (auto reg2 : registers) {
85 (assembler_.get()->*f)(*reg1, *reg2);
86 std::string base = fmt;
87
88 size_t reg1_index = base.find("{reg1}");
89 if (reg1_index != std::string::npos) {
90 std::ostringstream sreg;
91 sreg << *reg1;
92 std::string reg_string = sreg.str();
93 base.replace(reg1_index, 6, reg_string);
94 }
95
96 size_t reg2_index = base.find("{reg2}");
97 if (reg2_index != std::string::npos) {
98 std::ostringstream sreg;
99 sreg << *reg2;
100 std::string reg_string = sreg.str();
101 base.replace(reg2_index, 6, reg_string);
102 }
103
104 if (str.size() > 0) {
105 str += "\n";
106 }
107 str += base;
108 }
109 }
110 // Add a newline at the end.
111 str += "\n";
112 return str;
113 }
114
115 std::string RepeatRI(void (Ass::*f)(Reg, const Imm&), size_t imm_bytes, std::string fmt) {
116 const std::vector<Reg*> registers = GetRegisters();
117 std::string str;
118 std::vector<int64_t> imms = CreateImmediateValues(imm_bytes);
119 for (auto reg : registers) {
120 for (int64_t imm : imms) {
121 Imm* new_imm = CreateImmediate(imm);
122 (assembler_.get()->*f)(*reg, *new_imm);
123 delete new_imm;
124 std::string base = fmt;
125
126 size_t reg_index = base.find("{reg}");
127 if (reg_index != std::string::npos) {
128 std::ostringstream sreg;
129 sreg << *reg;
130 std::string reg_string = sreg.str();
131 base.replace(reg_index, 5, reg_string);
132 }
133
134 size_t imm_index = base.find("{imm}");
135 if (imm_index != std::string::npos) {
136 std::ostringstream sreg;
137 sreg << imm;
138 std::string imm_string = sreg.str();
139 base.replace(imm_index, 5, imm_string);
140 }
141
142 if (str.size() > 0) {
143 str += "\n";
144 }
145 str += base;
146 }
147 }
148 // Add a newline at the end.
149 str += "\n";
150 return str;
151 }
152
153 std::string RepeatI(void (Ass::*f)(const Imm&), size_t imm_bytes, std::string fmt) {
154 std::string str;
155 std::vector<int64_t> imms = CreateImmediateValues(imm_bytes);
156 for (int64_t imm : imms) {
157 Imm* new_imm = CreateImmediate(imm);
158 (assembler_.get()->*f)(*new_imm);
159 delete new_imm;
160 std::string base = fmt;
161
162 size_t imm_index = base.find("{imm}");
163 if (imm_index != std::string::npos) {
164 std::ostringstream sreg;
165 sreg << imm;
166 std::string imm_string = sreg.str();
167 base.replace(imm_index, 5, imm_string);
168 }
169
170 if (str.size() > 0) {
171 str += "\n";
172 }
173 str += base;
174 }
175 // Add a newline at the end.
176 str += "\n";
177 return str;
178 }
179
180 // This is intended to be run as a test.
181 bool CheckTools() {
182 if (!FileExists(GetAssemblerCommand())) {
183 return false;
184 }
185 LOG(INFO) << "Chosen assembler command: " << GetAssemblerCommand();
186
187 if (!FileExists(GetObjdumpCommand())) {
188 return false;
189 }
190 LOG(INFO) << "Chosen objdump command: " << GetObjdumpCommand();
191
192 // Disassembly is optional.
193 std::string disassembler = GetDisassembleCommand();
194 if (disassembler.length() != 0) {
195 if (!FileExists(disassembler)) {
196 return false;
197 }
198 LOG(INFO) << "Chosen disassemble command: " << GetDisassembleCommand();
199 } else {
200 LOG(INFO) << "No disassembler given.";
201 }
202
203 return true;
204 }
205
206 protected:
207 void SetUp() OVERRIDE {
208 assembler_.reset(new Ass());
209
Andreas Gampeb40c6a72014-05-02 14:25:12 -0700210 // Fake a runtime test for ScratchFile
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700211 CommonRuntimeTest::SetUpAndroidData(android_data_);
Andreas Gampeb40c6a72014-05-02 14:25:12 -0700212
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700213 SetUpHelpers();
214 }
215
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700216 void TearDown() OVERRIDE {
217 // We leave temporaries in case this failed so we can debug issues.
218 CommonRuntimeTest::TearDownAndroidData(android_data_, false);
219 tmpnam_ = "";
220 }
221
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700222 // Override this to set up any architecture-specific things, e.g., register vectors.
223 virtual void SetUpHelpers() {}
224
225 virtual std::vector<Reg*> GetRegisters() = 0;
226
227 // Get the typically used name for this architecture, e.g., aarch64, x86_64, ...
228 virtual std::string GetArchitectureString() = 0;
229
230 // Get the name of the assembler, e.g., "as" by default.
231 virtual std::string GetAssemblerCmdName() {
232 return "as";
233 }
234
235 // Switches to the assembler command. Default none.
236 virtual std::string GetAssemblerParameters() {
237 return "";
238 }
239
240 // Return the host assembler command for this test.
241 virtual std::string GetAssemblerCommand() {
242 // Already resolved it once?
243 if (resolved_assembler_cmd_.length() != 0) {
244 return resolved_assembler_cmd_;
245 }
246
247 std::string line = FindTool(GetAssemblerCmdName());
248 if (line.length() == 0) {
249 return line;
250 }
251
252 resolved_assembler_cmd_ = line + GetAssemblerParameters();
253
254 return line;
255 }
256
257 // Get the name of the objdump, e.g., "objdump" by default.
258 virtual std::string GetObjdumpCmdName() {
259 return "objdump";
260 }
261
262 // Switches to the objdump command. Default is " -h".
263 virtual std::string GetObjdumpParameters() {
264 return " -h";
265 }
266
267 // Return the host objdump command for this test.
268 virtual std::string GetObjdumpCommand() {
269 // Already resolved it once?
270 if (resolved_objdump_cmd_.length() != 0) {
271 return resolved_objdump_cmd_;
272 }
273
274 std::string line = FindTool(GetObjdumpCmdName());
275 if (line.length() == 0) {
276 return line;
277 }
278
279 resolved_objdump_cmd_ = line + GetObjdumpParameters();
280
281 return line;
282 }
283
284 // Get the name of the objdump, e.g., "objdump" by default.
285 virtual std::string GetDisassembleCmdName() {
286 return "objdump";
287 }
288
289 // Switches to the objdump command. As it's a binary, one needs to push the architecture and
290 // such to objdump, so it's architecture-specific and there is no default.
291 virtual std::string GetDisassembleParameters() = 0;
292
293 // Return the host disassembler command for this test.
294 virtual std::string GetDisassembleCommand() {
295 // Already resolved it once?
296 if (resolved_disassemble_cmd_.length() != 0) {
297 return resolved_disassemble_cmd_;
298 }
299
300 std::string line = FindTool(GetDisassembleCmdName());
301 if (line.length() == 0) {
302 return line;
303 }
304
305 resolved_disassemble_cmd_ = line + GetDisassembleParameters();
306
307 return line;
308 }
309
310 // Create a couple of immediate values up to the number of bytes given.
311 virtual std::vector<int64_t> CreateImmediateValues(size_t imm_bytes) {
312 std::vector<int64_t> res;
313 res.push_back(0);
314 res.push_back(-1);
315 res.push_back(0x12);
316 if (imm_bytes >= 2) {
317 res.push_back(0x1234);
318 res.push_back(-0x1234);
319 if (imm_bytes >= 4) {
320 res.push_back(0x12345678);
321 res.push_back(-0x12345678);
322 if (imm_bytes >= 6) {
323 res.push_back(0x123456789ABC);
324 res.push_back(-0x123456789ABC);
325 if (imm_bytes >= 8) {
326 res.push_back(0x123456789ABCDEF0);
327 res.push_back(-0x123456789ABCDEF0);
328 }
329 }
330 }
331 }
332 return res;
333 }
334
335 // Create an immediate from the specific value.
336 virtual Imm* CreateImmediate(int64_t imm_value) = 0;
337
338 private:
339 // Driver() assembles and compares the results. If the results are not equal and we have a
340 // disassembler, disassemble both and check whether they have the same mnemonics (in which case
341 // we just warn).
342 void Driver(std::string assembly_text, std::string test_name) {
343 EXPECT_NE(assembly_text.length(), 0U) << "Empty assembly";
344
345 NativeAssemblerResult res;
346 Compile(assembly_text, &res, test_name);
347
348 EXPECT_TRUE(res.ok) << res.error_msg;
349 if (!res.ok) {
350 // No way of continuing.
351 return;
352 }
353
354 size_t cs = assembler_->CodeSize();
Ian Rogers700a4022014-05-19 16:49:03 -0700355 std::unique_ptr<std::vector<uint8_t>> data(new std::vector<uint8_t>(cs));
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700356 MemoryRegion code(&(*data)[0], data->size());
357 assembler_->FinalizeInstructions(code);
358
359 if (*data == *res.code) {
360 Clean(&res);
361 } else {
362 if (DisassembleBinaries(*data, *res.code, test_name)) {
363 if (data->size() > res.code->size()) {
364 LOG(WARNING) << "Assembly code is not identical, but disassembly of machine code is "
365 "equal: this implies sub-optimal encoding! Our code size=" << data->size() <<
366 ", gcc size=" << res.code->size();
367 } else {
368 LOG(INFO) << "GCC chose a different encoding than ours, but the overall length is the "
369 "same.";
370 }
371 } else {
372 // This will output the assembly.
373 EXPECT_EQ(*data, *res.code) << "Outputs (and disassembly) not identical.";
374 }
375 }
376 }
377
378 // Structure to store intermediates and results.
379 struct NativeAssemblerResult {
380 bool ok;
381 std::string error_msg;
382 std::string base_name;
Ian Rogers700a4022014-05-19 16:49:03 -0700383 std::unique_ptr<std::vector<uint8_t>> code;
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700384 uintptr_t length;
385 };
386
387 // Compile the assembly file from_file to a binary file to_file. Returns true on success.
388 bool Assemble(const char* from_file, const char* to_file, std::string* error_msg) {
389 bool have_assembler = FileExists(GetAssemblerCommand());
390 EXPECT_TRUE(have_assembler) << "Cannot find assembler:" << GetAssemblerCommand();
391 if (!have_assembler) {
392 return false;
393 }
394
395 std::vector<std::string> args;
396
397 args.push_back(GetAssemblerCommand());
398 args.push_back("-o");
399 args.push_back(to_file);
400 args.push_back(from_file);
401
402 return Exec(args, error_msg);
403 }
404
405 // Runs objdump -h on the binary file and extracts the first line with .text.
406 // Returns "" on failure.
407 std::string Objdump(std::string file) {
408 bool have_objdump = FileExists(GetObjdumpCommand());
409 EXPECT_TRUE(have_objdump) << "Cannot find objdump: " << GetObjdumpCommand();
410 if (!have_objdump) {
411 return "";
412 }
413
414 std::string error_msg;
415 std::vector<std::string> args;
416
417 args.push_back(GetObjdumpCommand());
418 args.push_back(file);
419 args.push_back(">");
420 args.push_back(file+".dump");
421 std::string cmd = Join(args, ' ');
422
423 args.clear();
424 args.push_back("/bin/sh");
425 args.push_back("-c");
426 args.push_back(cmd);
427
428 if (!Exec(args, &error_msg)) {
429 EXPECT_TRUE(false) << error_msg;
430 }
431
432 std::ifstream dump(file+".dump");
433
434 std::string line;
435 bool found = false;
436 while (std::getline(dump, line)) {
437 if (line.find(".text") != line.npos) {
438 found = true;
439 break;
440 }
441 }
442
443 dump.close();
444
445 if (found) {
446 return line;
447 } else {
448 return "";
449 }
450 }
451
452 // Disassemble both binaries and compare the text.
453 bool DisassembleBinaries(std::vector<uint8_t>& data, std::vector<uint8_t>& as,
454 std::string test_name) {
455 std::string disassembler = GetDisassembleCommand();
456 if (disassembler.length() == 0) {
457 LOG(WARNING) << "No dissassembler command.";
458 return false;
459 }
460
461 std::string data_name = WriteToFile(data, test_name + ".ass");
462 std::string error_msg;
463 if (!DisassembleBinary(data_name, &error_msg)) {
464 LOG(INFO) << "Error disassembling: " << error_msg;
465 std::remove(data_name.c_str());
466 return false;
467 }
468
469 std::string as_name = WriteToFile(as, test_name + ".gcc");
470 if (!DisassembleBinary(as_name, &error_msg)) {
471 LOG(INFO) << "Error disassembling: " << error_msg;
472 std::remove(data_name.c_str());
473 std::remove((data_name + ".dis").c_str());
474 std::remove(as_name.c_str());
475 return false;
476 }
477
478 bool result = CompareFiles(data_name + ".dis", as_name + ".dis");
479
480 if (result) {
481 std::remove(data_name.c_str());
482 std::remove(as_name.c_str());
483 std::remove((data_name + ".dis").c_str());
484 std::remove((as_name + ".dis").c_str());
485 }
486
487 return result;
488 }
489
490 bool DisassembleBinary(std::string file, std::string* error_msg) {
491 std::vector<std::string> args;
492
493 args.push_back(GetDisassembleCommand());
494 args.push_back(file);
495 args.push_back("| sed -n \'/<.data>/,$p\' | sed -e \'s/.*://\'");
496 args.push_back(">");
497 args.push_back(file+".dis");
498 std::string cmd = Join(args, ' ');
499
500 args.clear();
501 args.push_back("/bin/sh");
502 args.push_back("-c");
503 args.push_back(cmd);
504
505 return Exec(args, error_msg);
506 }
507
508 std::string WriteToFile(std::vector<uint8_t>& buffer, std::string test_name) {
509 std::string file_name = GetTmpnam() + std::string("---") + test_name;
510 const char* data = reinterpret_cast<char*>(buffer.data());
511 std::ofstream s_out(file_name + ".o");
512 s_out.write(data, buffer.size());
513 s_out.close();
514 return file_name + ".o";
515 }
516
517 bool CompareFiles(std::string f1, std::string f2) {
518 std::ifstream f1_in(f1);
519 std::ifstream f2_in(f2);
520
521 bool result = std::equal(std::istreambuf_iterator<char>(f1_in),
522 std::istreambuf_iterator<char>(),
523 std::istreambuf_iterator<char>(f2_in));
524
525 f1_in.close();
526 f2_in.close();
527
528 return result;
529 }
530
531 // Compile the given assembly code and extract the binary, if possible. Put result into res.
532 bool Compile(std::string assembly_code, NativeAssemblerResult* res, std::string test_name) {
533 res->ok = false;
534 res->code.reset(nullptr);
535
536 res->base_name = GetTmpnam() + std::string("---") + test_name;
537
538 // TODO: Lots of error checking.
539
540 std::ofstream s_out(res->base_name + ".S");
541 s_out << assembly_code;
542 s_out.close();
543
544 if (!Assemble((res->base_name + ".S").c_str(), (res->base_name + ".o").c_str(),
545 &res->error_msg)) {
546 res->error_msg = "Could not compile.";
547 return false;
548 }
549
550 std::string odump = Objdump(res->base_name + ".o");
551 if (odump.length() == 0) {
552 res->error_msg = "Objdump failed.";
553 return false;
554 }
555
556 std::istringstream iss(odump);
557 std::istream_iterator<std::string> start(iss);
558 std::istream_iterator<std::string> end;
559 std::vector<std::string> tokens(start, end);
560
561 if (tokens.size() < OBJDUMP_SECTION_LINE_MIN_TOKENS) {
562 res->error_msg = "Objdump output not recognized: too few tokens.";
563 return false;
564 }
565
566 if (tokens[1] != ".text") {
567 res->error_msg = "Objdump output not recognized: .text not second token.";
568 return false;
569 }
570
571 std::string lengthToken = "0x" + tokens[2];
572 std::istringstream(lengthToken) >> std::hex >> res->length;
573
574 std::string offsetToken = "0x" + tokens[5];
575 uintptr_t offset;
576 std::istringstream(offsetToken) >> std::hex >> offset;
577
578 std::ifstream obj(res->base_name + ".o");
579 obj.seekg(offset);
580 res->code.reset(new std::vector<uint8_t>(res->length));
581 obj.read(reinterpret_cast<char*>(&(*res->code)[0]), res->length);
582 obj.close();
583
584 res->ok = true;
585 return true;
586 }
587
588 // Remove temporary files.
589 void Clean(const NativeAssemblerResult* res) {
590 std::remove((res->base_name + ".S").c_str());
591 std::remove((res->base_name + ".o").c_str());
592 std::remove((res->base_name + ".o.dump").c_str());
593 }
594
595 // Check whether file exists. Is used for commands, so strips off any parameters: anything after
596 // the first space. We skip to the last slash for this, so it should work with directories with
597 // spaces.
598 static bool FileExists(std::string file) {
599 if (file.length() == 0) {
600 return false;
601 }
602
603 // Need to strip any options.
604 size_t last_slash = file.find_last_of('/');
605 if (last_slash == std::string::npos) {
606 // No slash, start looking at the start.
607 last_slash = 0;
608 }
609 size_t space_index = file.find(' ', last_slash);
610
611 if (space_index == std::string::npos) {
612 std::ifstream infile(file.c_str());
613 return infile.good();
614 } else {
615 std::string copy = file.substr(0, space_index - 1);
616
617 struct stat buf;
618 return stat(copy.c_str(), &buf) == 0;
619 }
620 }
621
622 static std::string GetGCCRootPath() {
623 return "prebuilts/gcc/linux-x86";
624 }
625
626 static std::string GetRootPath() {
627 // 1) Check ANDROID_BUILD_TOP
628 char* build_top = getenv("ANDROID_BUILD_TOP");
629 if (build_top != nullptr) {
630 return std::string(build_top) + "/";
631 }
632
633 // 2) Do cwd
634 char temp[1024];
635 return getcwd(temp, 1024) ? std::string(temp) + "/" : std::string("");
636 }
637
638 std::string FindTool(std::string tool_name) {
639 // Find the current tool. Wild-card pattern is "arch-string*tool-name".
640 std::string gcc_path = GetRootPath() + GetGCCRootPath();
641 std::vector<std::string> args;
642 args.push_back("find");
643 args.push_back(gcc_path);
644 args.push_back("-name");
645 args.push_back(GetArchitectureString() + "*" + tool_name);
646 args.push_back("|");
647 args.push_back("sort");
648 args.push_back("|");
649 args.push_back("tail");
650 args.push_back("-n");
651 args.push_back("1");
652 std::string tmp_file = GetTmpnam();
653 args.push_back(">");
654 args.push_back(tmp_file);
655 std::string sh_args = Join(args, ' ');
656
657 args.clear();
658 args.push_back("/bin/sh");
659 args.push_back("-c");
660 args.push_back(sh_args);
661
662 std::string error_msg;
663 if (!Exec(args, &error_msg)) {
664 EXPECT_TRUE(false) << error_msg;
665 return "";
666 }
667
668 std::ifstream in(tmp_file.c_str());
669 std::string line;
670 if (!std::getline(in, line)) {
671 in.close();
672 std::remove(tmp_file.c_str());
673 return "";
674 }
675 in.close();
676 std::remove(tmp_file.c_str());
677 return line;
678 }
679
680 // Use a consistent tmpnam, so store it.
681 std::string GetTmpnam() {
682 if (tmpnam_.length() == 0) {
Andreas Gampeb40c6a72014-05-02 14:25:12 -0700683 ScratchFile tmp;
684 tmpnam_ = tmp.GetFilename() + "asm";
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700685 }
686 return tmpnam_;
687 }
688
Ian Rogers700a4022014-05-19 16:49:03 -0700689 std::unique_ptr<Ass> assembler_;
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700690
691 std::string resolved_assembler_cmd_;
692 std::string resolved_objdump_cmd_;
693 std::string resolved_disassemble_cmd_;
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700694
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700695 std::string android_data_;
696
Andreas Gampe5a4fa822014-03-31 16:50:12 -0700697 static constexpr size_t OBJDUMP_SECTION_LINE_MIN_TOKENS = 6;
698};
699
700} // namespace art
701
702#endif // ART_COMPILER_UTILS_ASSEMBLER_TEST_H_