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_img_rel_ro_size,
95                              size_t data_img_rel_ro_app_image_offset,
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* StartDataImgRelRo() override;
106   void EndDataImgRelRo(OutputStream* data_img_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_img_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_img_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_img_rel_ro_size,size_t data_img_rel_ro_app_image_offset,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_img_rel_ro_size,
177                                                      size_t data_img_rel_ro_app_image_offset,
178                                                      size_t bss_size,
179                                                      size_t bss_methods_offset,
180                                                      size_t bss_roots_offset,
181                                                      size_t dex_section_size) {
182   DCHECK_EQ(rodata_size_, 0u);
183   rodata_size_ = rodata_size;
184   DCHECK_EQ(text_size_, 0u);
185   text_size_ = text_size;
186   DCHECK_EQ(data_img_rel_ro_size_, 0u);
187   data_img_rel_ro_size_ = data_img_rel_ro_size;
188   DCHECK_EQ(bss_size_, 0u);
189   bss_size_ = bss_size;
190   DCHECK_EQ(dex_section_size_, 0u);
191   dex_section_size_ = dex_section_size;
192   builder_->PrepareDynamicSection(elf_file_->GetPath(),
193                                   rodata_size_,
194                                   text_size_,
195                                   data_img_rel_ro_size_,
196                                   data_img_rel_ro_app_image_offset,
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>
StartDataImgRelRo()230 OutputStream* ElfWriterQuick<ElfTypes>::StartDataImgRelRo() {
231   auto* data_img_rel_ro = builder_->GetDataImgRelRo();
232   data_img_rel_ro->Start();
233   return data_img_rel_ro;
234 }
235 
236 template <typename ElfTypes>
EndDataImgRelRo(OutputStream * data_img_rel_ro)237 void ElfWriterQuick<ElfTypes>::EndDataImgRelRo(OutputStream* data_img_rel_ro) {
238   CHECK_EQ(builder_->GetDataImgRelRo(), data_img_rel_ro);
239   builder_->GetDataImgRelRo()->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_.reset(ThreadPool::Create("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     // If mini-debug-info wasn't explicitly created so far, create it now (happens in tests).
270     if (debug_info_task_ == nullptr) {
271       PrepareDebugInfo(debug_info);
272     }
273     // Wait for the mini-debug-info generation to finish and write it to disk.
274     Thread* self = Thread::Current();
275     DCHECK(debug_info_thread_pool_ != nullptr);
276     debug_info_thread_pool_->Wait(self, true, false);
277     builder_->WriteSection(".gnu_debugdata", debug_info_task_->GetResult());
278   }
279   // The Strip method expects debug info to be last (mini-debug-info is not stripped).
280   if (!debug_info.Empty() && compiler_options_.GetGenerateDebugInfo()) {
281     // Generate all the debug information we can.
282     debug::WriteDebugInfo(builder_.get(), debug_info);
283   }
284 }
285 
286 template <typename ElfTypes>
StripDebugInfo()287 bool ElfWriterQuick<ElfTypes>::StripDebugInfo() {
288   off_t file_size = builder_->Strip();
289   return elf_file_->SetLength(file_size) == 0;
290 }
291 
292 template <typename ElfTypes>
End()293 bool ElfWriterQuick<ElfTypes>::End() {
294   builder_->End();
295   if (compiler_options_.GetGenerateBuildId()) {
296     uint8_t build_id[ElfBuilder<ElfTypes>::kBuildIdLen];
297     ComputeFileBuildId(&build_id);
298     builder_->WriteBuildId(build_id);
299   }
300   return builder_->Good();
301 }
302 
303 template <typename ElfTypes>
ComputeFileBuildId(uint8_t (* build_id)[ElfBuilder<ElfTypes>::kBuildIdLen])304 void ElfWriterQuick<ElfTypes>::ComputeFileBuildId(
305     uint8_t (*build_id)[ElfBuilder<ElfTypes>::kBuildIdLen]) {
306   constexpr int kBufSize = 8192;
307   std::vector<char> buffer(kBufSize);
308   int64_t offset = 0;
309   SHA_CTX ctx;
310   SHA1_Init(&ctx);
311   while (true) {
312     int64_t bytes_read = elf_file_->Read(buffer.data(), kBufSize, offset);
313     CHECK_GE(bytes_read, 0);
314     if (bytes_read == 0) {
315       // End of file.
316       break;
317     }
318     SHA1_Update(&ctx, buffer.data(), bytes_read);
319     offset += bytes_read;
320   }
321   SHA1_Final(*build_id, &ctx);
322 }
323 
324 template <typename ElfTypes>
GetStream()325 OutputStream* ElfWriterQuick<ElfTypes>::GetStream() {
326   return builder_->GetStream();
327 }
328 
329 template <typename ElfTypes>
GetLoadedSize()330 size_t ElfWriterQuick<ElfTypes>::GetLoadedSize() {
331   return builder_->GetLoadedSize();
332 }
333 
334 // Explicit instantiations
335 template class ElfWriterQuick<ElfTypes32>;
336 template class ElfWriterQuick<ElfTypes64>;
337 
338 }  // namespace linker
339 }  // namespace art
340