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