1 /*
2  * Copyright (C) 2012 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 #include "elf_writer_quick.h"
18 
19 #include <memory>
20 #include <openssl/sha.h>
21 #include <unordered_map>
22 #include <unordered_set>
23 
24 #include <android-base/logging.h>
25 
26 #include "base/casts.h"
27 #include "base/globals.h"
28 #include "base/leb128.h"
29 #include "base/utils.h"
30 #include "compiled_method.h"
31 #include "debug/elf_debug_writer.h"
32 #include "debug/method_debug_info.h"
33 #include "driver/compiler_options.h"
34 #include "elf/elf_builder.h"
35 #include "elf/elf_utils.h"
36 #include "stream/buffered_output_stream.h"
37 #include "stream/file_output_stream.h"
38 #include "thread-current-inl.h"
39 #include "thread_pool.h"
40 
41 namespace art {
42 namespace linker {
43 
44 class DebugInfoTask : public Task {
45  public:
DebugInfoTask(InstructionSet isa,const InstructionSetFeatures * features,uint64_t text_section_address,size_t text_section_size,uint64_t dex_section_address,size_t dex_section_size,const debug::DebugInfo & debug_info)46   DebugInfoTask(InstructionSet isa,
47                 const InstructionSetFeatures* features,
48                 uint64_t text_section_address,
49                 size_t text_section_size,
50                 uint64_t dex_section_address,
51                 size_t dex_section_size,
52                 const debug::DebugInfo& debug_info)
53       : isa_(isa),
54         instruction_set_features_(features),
55         text_section_address_(text_section_address),
56         text_section_size_(text_section_size),
57         dex_section_address_(dex_section_address),
58         dex_section_size_(dex_section_size),
59         debug_info_(debug_info) {
60   }
61 
Run(Thread *)62   void Run(Thread*) override {
63     result_ = debug::MakeMiniDebugInfo(isa_,
64                                        instruction_set_features_,
65                                        text_section_address_,
66                                        text_section_size_,
67                                        dex_section_address_,
68                                        dex_section_size_,
69                                        debug_info_);
70   }
71 
GetResult()72   std::vector<uint8_t>* GetResult() {
73     return &result_;
74   }
75 
76  private:
77   InstructionSet isa_;
78   const InstructionSetFeatures* instruction_set_features_;
79   uint64_t text_section_address_;
80   size_t text_section_size_;
81   uint64_t dex_section_address_;
82   size_t dex_section_size_;
83   const debug::DebugInfo& debug_info_;
84   std::vector<uint8_t> result_;
85 };
86 
87 template <typename ElfTypes>
88 class ElfWriterQuick final : public ElfWriter {
89  public:
90   ElfWriterQuick(const CompilerOptions& compiler_options,
91                  File* elf_file);
92   ~ElfWriterQuick();
93 
94   void Start() override;
95   void PrepareDynamicSection(size_t rodata_size,
96                              size_t text_size,
97                              size_t data_bimg_rel_ro_size,
98                              size_t bss_size,
99                              size_t bss_methods_offset,
100                              size_t bss_roots_offset,
101                              size_t dex_section_size) override;
102   void PrepareDebugInfo(const debug::DebugInfo& debug_info) override;
103   OutputStream* StartRoData() override;
104   void EndRoData(OutputStream* rodata) override;
105   OutputStream* StartText() override;
106   void EndText(OutputStream* text) override;
107   OutputStream* StartDataBimgRelRo() override;
108   void EndDataBimgRelRo(OutputStream* data_bimg_rel_ro) override;
109   void WriteDynamicSection() override;
110   void WriteDebugInfo(const debug::DebugInfo& debug_info) override;
111   bool StripDebugInfo() override;
112   bool End() override;
113 
114   OutputStream* GetStream() override;
115 
116   size_t GetLoadedSize() override;
117 
118   static void EncodeOatPatches(const std::vector<uintptr_t>& locations,
119                                std::vector<uint8_t>* buffer);
120 
121  private:
122   const CompilerOptions& compiler_options_;
123   File* const elf_file_;
124   size_t rodata_size_;
125   size_t text_size_;
126   size_t data_bimg_rel_ro_size_;
127   size_t bss_size_;
128   size_t dex_section_size_;
129   std::unique_ptr<BufferedOutputStream> output_stream_;
130   std::unique_ptr<ElfBuilder<ElfTypes>> builder_;
131   std::unique_ptr<DebugInfoTask> debug_info_task_;
132   std::unique_ptr<ThreadPool> debug_info_thread_pool_;
133 
134   void ComputeFileBuildId(uint8_t (*build_id)[ElfBuilder<ElfTypes>::kBuildIdLen]);
135 
136   DISALLOW_IMPLICIT_CONSTRUCTORS(ElfWriterQuick);
137 };
138 
CreateElfWriterQuick(const CompilerOptions & compiler_options,File * elf_file)139 std::unique_ptr<ElfWriter> CreateElfWriterQuick(const CompilerOptions& compiler_options,
140                                                 File* elf_file) {
141   if (Is64BitInstructionSet(compiler_options.GetInstructionSet())) {
142     return std::make_unique<ElfWriterQuick<ElfTypes64>>(compiler_options, elf_file);
143   } else {
144     return std::make_unique<ElfWriterQuick<ElfTypes32>>(compiler_options, elf_file);
145   }
146 }
147 
148 template <typename ElfTypes>
ElfWriterQuick(const CompilerOptions & compiler_options,File * elf_file)149 ElfWriterQuick<ElfTypes>::ElfWriterQuick(const CompilerOptions& compiler_options, File* elf_file)
150     : ElfWriter(),
151       compiler_options_(compiler_options),
152       elf_file_(elf_file),
153       rodata_size_(0u),
154       text_size_(0u),
155       data_bimg_rel_ro_size_(0u),
156       bss_size_(0u),
157       dex_section_size_(0u),
158       output_stream_(
159           std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(elf_file))),
160       builder_(new ElfBuilder<ElfTypes>(compiler_options_.GetInstructionSet(),
161                                         output_stream_.get())) {}
162 
163 template <typename ElfTypes>
~ElfWriterQuick()164 ElfWriterQuick<ElfTypes>::~ElfWriterQuick() {}
165 
166 template <typename ElfTypes>
Start()167 void ElfWriterQuick<ElfTypes>::Start() {
168   builder_->Start();
169   if (compiler_options_.GetGenerateBuildId()) {
170     builder_->GetBuildId()->AllocateVirtualMemory(builder_->GetBuildId()->GetSize());
171     builder_->WriteBuildIdSection();
172   }
173 }
174 
175 template <typename ElfTypes>
PrepareDynamicSection(size_t rodata_size,size_t text_size,size_t data_bimg_rel_ro_size,size_t bss_size,size_t bss_methods_offset,size_t bss_roots_offset,size_t dex_section_size)176 void ElfWriterQuick<ElfTypes>::PrepareDynamicSection(size_t rodata_size,
177                                                      size_t text_size,
178                                                      size_t data_bimg_rel_ro_size,
179                                                      size_t bss_size,
180                                                      size_t bss_methods_offset,
181                                                      size_t bss_roots_offset,
182                                                      size_t dex_section_size) {
183   DCHECK_EQ(rodata_size_, 0u);
184   rodata_size_ = rodata_size;
185   DCHECK_EQ(text_size_, 0u);
186   text_size_ = text_size;
187   DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
188   data_bimg_rel_ro_size_ = data_bimg_rel_ro_size;
189   DCHECK_EQ(bss_size_, 0u);
190   bss_size_ = bss_size;
191   DCHECK_EQ(dex_section_size_, 0u);
192   dex_section_size_ = dex_section_size;
193   builder_->PrepareDynamicSection(elf_file_->GetPath(),
194                                   rodata_size_,
195                                   text_size_,
196                                   data_bimg_rel_ro_size_,
197                                   bss_size_,
198                                   bss_methods_offset,
199                                   bss_roots_offset,
200                                   dex_section_size);
201 }
202 
203 template <typename ElfTypes>
StartRoData()204 OutputStream* ElfWriterQuick<ElfTypes>::StartRoData() {
205   auto* rodata = builder_->GetRoData();
206   rodata->Start();
207   return rodata;
208 }
209 
210 template <typename ElfTypes>
EndRoData(OutputStream * rodata)211 void ElfWriterQuick<ElfTypes>::EndRoData(OutputStream* rodata) {
212   CHECK_EQ(builder_->GetRoData(), rodata);
213   builder_->GetRoData()->End();
214 }
215 
216 template <typename ElfTypes>
StartText()217 OutputStream* ElfWriterQuick<ElfTypes>::StartText() {
218   auto* text = builder_->GetText();
219   text->Start();
220   return text;
221 }
222 
223 template <typename ElfTypes>
EndText(OutputStream * text)224 void ElfWriterQuick<ElfTypes>::EndText(OutputStream* text) {
225   CHECK_EQ(builder_->GetText(), text);
226   builder_->GetText()->End();
227 }
228 
229 template <typename ElfTypes>
StartDataBimgRelRo()230 OutputStream* ElfWriterQuick<ElfTypes>::StartDataBimgRelRo() {
231   auto* data_bimg_rel_ro = builder_->GetDataBimgRelRo();
232   data_bimg_rel_ro->Start();
233   return data_bimg_rel_ro;
234 }
235 
236 template <typename ElfTypes>
EndDataBimgRelRo(OutputStream * data_bimg_rel_ro)237 void ElfWriterQuick<ElfTypes>::EndDataBimgRelRo(OutputStream* data_bimg_rel_ro) {
238   CHECK_EQ(builder_->GetDataBimgRelRo(), data_bimg_rel_ro);
239   builder_->GetDataBimgRelRo()->End();
240 }
241 
242 template <typename ElfTypes>
WriteDynamicSection()243 void ElfWriterQuick<ElfTypes>::WriteDynamicSection() {
244   builder_->WriteDynamicSection();
245 }
246 
247 template <typename ElfTypes>
PrepareDebugInfo(const debug::DebugInfo & debug_info)248 void ElfWriterQuick<ElfTypes>::PrepareDebugInfo(const debug::DebugInfo& debug_info) {
249   if (compiler_options_.GetGenerateMiniDebugInfo()) {
250     // Prepare the mini-debug-info in background while we do other I/O.
251     Thread* self = Thread::Current();
252     debug_info_task_ = std::make_unique<DebugInfoTask>(
253         builder_->GetIsa(),
254         compiler_options_.GetInstructionSetFeatures(),
255         builder_->GetText()->GetAddress(),
256         text_size_,
257         builder_->GetDex()->Exists() ? builder_->GetDex()->GetAddress() : 0,
258         dex_section_size_,
259         debug_info);
260     debug_info_thread_pool_ = std::make_unique<ThreadPool>("Mini-debug-info writer", 1);
261     debug_info_thread_pool_->AddTask(self, debug_info_task_.get());
262     debug_info_thread_pool_->StartWorkers(self);
263   }
264 }
265 
266 template <typename ElfTypes>
WriteDebugInfo(const debug::DebugInfo & debug_info)267 void ElfWriterQuick<ElfTypes>::WriteDebugInfo(const debug::DebugInfo& debug_info) {
268   if (compiler_options_.GetGenerateMiniDebugInfo()) {
269     // Wait for the mini-debug-info generation to finish and write it to disk.
270     Thread* self = Thread::Current();
271     DCHECK(debug_info_thread_pool_ != nullptr);
272     debug_info_thread_pool_->Wait(self, true, false);
273     builder_->WriteSection(".gnu_debugdata", debug_info_task_->GetResult());
274   }
275   // The Strip method expects debug info to be last (mini-debug-info is not stripped).
276   if (!debug_info.Empty() && compiler_options_.GetGenerateDebugInfo()) {
277     // Generate all the debug information we can.
278     debug::WriteDebugInfo(builder_.get(), debug_info);
279   }
280 }
281 
282 template <typename ElfTypes>
StripDebugInfo()283 bool ElfWriterQuick<ElfTypes>::StripDebugInfo() {
284   off_t file_size = builder_->Strip();
285   return elf_file_->SetLength(file_size) == 0;
286 }
287 
288 template <typename ElfTypes>
End()289 bool ElfWriterQuick<ElfTypes>::End() {
290   builder_->End();
291   if (compiler_options_.GetGenerateBuildId()) {
292     uint8_t build_id[ElfBuilder<ElfTypes>::kBuildIdLen];
293     ComputeFileBuildId(&build_id);
294     builder_->WriteBuildId(build_id);
295   }
296   return builder_->Good();
297 }
298 
299 template <typename ElfTypes>
ComputeFileBuildId(uint8_t (* build_id)[ElfBuilder<ElfTypes>::kBuildIdLen])300 void ElfWriterQuick<ElfTypes>::ComputeFileBuildId(
301     uint8_t (*build_id)[ElfBuilder<ElfTypes>::kBuildIdLen]) {
302   constexpr int kBufSize = 8192;
303   std::vector<char> buffer(kBufSize);
304   int64_t offset = 0;
305   SHA_CTX ctx;
306   SHA1_Init(&ctx);
307   while (true) {
308     int64_t bytes_read = elf_file_->Read(buffer.data(), kBufSize, offset);
309     CHECK_GE(bytes_read, 0);
310     if (bytes_read == 0) {
311       // End of file.
312       break;
313     }
314     SHA1_Update(&ctx, buffer.data(), bytes_read);
315     offset += bytes_read;
316   }
317   SHA1_Final(*build_id, &ctx);
318 }
319 
320 template <typename ElfTypes>
GetStream()321 OutputStream* ElfWriterQuick<ElfTypes>::GetStream() {
322   return builder_->GetStream();
323 }
324 
325 template <typename ElfTypes>
GetLoadedSize()326 size_t ElfWriterQuick<ElfTypes>::GetLoadedSize() {
327   return builder_->GetLoadedSize();
328 }
329 
330 // Explicit instantiations
331 template class ElfWriterQuick<ElfTypes32>;
332 template class ElfWriterQuick<ElfTypes64>;
333 
334 }  // namespace linker
335 }  // namespace art
336