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