bitcode_wrapperer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * Copyright 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. #include "bcinfo/Wrap/bitcode_wrapperer.h"
  17. #define LOG_TAG "bcinfo"
  18. #include <stdio.h>
  19. #include <sys/stat.h>
  20. #include <log/log.h>
  21. using std::vector;
  22. // The number of bytes in a 32 bit integer.
  23. static const uint32_t kWordSize = 4;
  24. // Number of LLVM-defined fixed fields in the header.
  25. static const uint32_t kLLVMFields = 4;
  26. // Total number of fixed fields in the header.
  27. static const uint32_t kFixedFields = 7;
  28. // The magic number that must exist for bitcode wrappers.
  29. static const uint32_t kWrapperMagicNumber = 0x0B17C0DE;
  30. // The version number associated with a wrapper file.
  31. // Note: llvm currently only allows the value 0. When this changes,
  32. // we should consider making this a command line option.
  33. static const uint32_t kLLVMVersionNumber = 0;
  34. // Fields defined by Android bitcode header.
  35. static const uint32_t kAndroidHeaderVersion = 0;
  36. static const uint32_t kAndroidTargetAPI = 0;
  37. static const uint32_t kAndroidDefaultCompilerVersion = 0;
  38. static const uint32_t kAndroidDefaultOptimizationLevel = 3;
  39. // PNaCl bitcode version number.
  40. static const uint32_t kPnaclBitcodeVersion = 0;
  41. // Max size for variable fields. Currently only used for writing them
  42. // out to files (the parsing works for arbitrary sizes).
  43. static const size_t kMaxVariableFieldSize = 256;
  44. BitcodeWrapperer::BitcodeWrapperer(WrapperInput* infile, WrapperOutput* outfile)
  45. : infile_(infile),
  46. outfile_(outfile),
  47. buffer_size_(0),
  48. cursor_(0),
  49. infile_at_eof_(false),
  50. infile_bc_offset_(0),
  51. wrapper_bc_offset_(0),
  52. wrapper_bc_size_(0),
  53. android_header_version_(kAndroidHeaderVersion),
  54. android_target_api_(kAndroidTargetAPI),
  55. android_compiler_version_(kAndroidDefaultCompilerVersion),
  56. android_optimization_level_(kAndroidDefaultOptimizationLevel),
  57. pnacl_bc_version_(0),
  58. error_(false) {
  59. buffer_.resize(kBitcodeWrappererBufferSize);
  60. if (IsInputBitcodeWrapper()) {
  61. ParseWrapperHeader();
  62. } else if (IsInputBitcodeFile()) {
  63. wrapper_bc_offset_ = kWordSize * kFixedFields;
  64. wrapper_bc_size_ = GetInFileSize();
  65. } else {
  66. ALOGE("Error: input file is not a bitcode file.\n");
  67. error_ = true;
  68. }
  69. }
  70. BitcodeWrapperer::~BitcodeWrapperer() {
  71. for(size_t i = 0; i < variable_field_data_.size(); i++) {
  72. delete [] variable_field_data_[i];
  73. }
  74. }
  75. void BitcodeWrapperer::ClearBuffer() {
  76. buffer_size_ = 0;
  77. cursor_ = 0;
  78. infile_at_eof_ = false;
  79. }
  80. bool BitcodeWrapperer::Seek(uint32_t pos) {
  81. if (infile_ != nullptr && infile_->Seek(pos)) {
  82. ClearBuffer();
  83. return true;
  84. }
  85. return false;
  86. }
  87. bool BitcodeWrapperer::CanReadWord() {
  88. if (GetBufferUnreadBytes() < kWordSize) {
  89. FillBuffer();
  90. return GetBufferUnreadBytes() >= kWordSize;
  91. } else {
  92. return true;
  93. }
  94. }
  95. void BitcodeWrapperer::FillBuffer() {
  96. if (cursor_ > 0) {
  97. // Before filling, move any remaining bytes to the
  98. // front of the buffer. This allows us to assume
  99. // that after the call to FillBuffer, readable
  100. // text is contiguous.
  101. if (cursor_ < buffer_size_) {
  102. size_t i = 0;
  103. while (cursor_ < buffer_size_) {
  104. buffer_[i++] = buffer_[cursor_++];
  105. }
  106. cursor_ = 0;
  107. buffer_size_ = i;
  108. }
  109. } else {
  110. // Assume the buffer contents have been used,
  111. // and we want to completely refill it.
  112. buffer_size_ = 0;
  113. }
  114. // If we don't have an input, we can't refill the buffer at all.
  115. if (infile_ == nullptr) {
  116. return;
  117. }
  118. // Now fill in remaining space.
  119. size_t needed = buffer_.size() - buffer_size_;
  120. while (buffer_.size() > buffer_size_) {
  121. int actually_read = infile_->Read(&buffer_[buffer_size_], needed);
  122. if (infile_->AtEof()) {
  123. infile_at_eof_ = true;
  124. }
  125. if (actually_read) {
  126. buffer_size_ += actually_read;
  127. needed -= actually_read;
  128. } else if (infile_at_eof_) {
  129. break;
  130. }
  131. }
  132. }
  133. bool BitcodeWrapperer::ReadWord(uint32_t& word) {
  134. if (!CanReadWord()) return false;
  135. word = (((uint32_t) BufferLookahead(0)) << 0)
  136. | (((uint32_t) BufferLookahead(1)) << 8)
  137. | (((uint32_t) BufferLookahead(2)) << 16)
  138. | (((uint32_t) BufferLookahead(3)) << 24);
  139. cursor_ += kWordSize;
  140. return true;
  141. }
  142. bool BitcodeWrapperer::WriteWord(uint32_t value) {
  143. uint8_t buffer[kWordSize];
  144. buffer[3] = (value >> 24) & 0xFF;
  145. buffer[2] = (value >> 16) & 0xFF;
  146. buffer[1] = (value >> 8) & 0xFF;
  147. buffer[0] = (value >> 0) & 0xFF;
  148. return outfile_->Write(buffer, kWordSize);
  149. }
  150. bool BitcodeWrapperer::WriteVariableFields() {
  151. // This buffer may have to be bigger if we start using the fields
  152. // for larger things.
  153. uint8_t buffer[kMaxVariableFieldSize];
  154. for (vector<BCHeaderField>::iterator it = header_fields_.begin();
  155. it != header_fields_.end(); ++it) {
  156. if (!it->Write(buffer, kMaxVariableFieldSize) ||
  157. !outfile_->Write(buffer, it->GetTotalSize())) {
  158. return false;
  159. }
  160. }
  161. return true;
  162. }
  163. bool BitcodeWrapperer::ParseWrapperHeader() {
  164. // Make sure LLVM-defined fields have been parsed
  165. if (!IsInputBitcodeWrapper()) return false;
  166. // Check the android/pnacl fields
  167. if (!ReadWord(android_header_version_) ||
  168. !ReadWord(android_target_api_) || !ReadWord(pnacl_bc_version_)) {
  169. ALOGW("Error: file not long enough to contain header\n");
  170. return false;
  171. }
  172. if (pnacl_bc_version_ != kPnaclBitcodeVersion) {
  173. ALOGW("Error: bad PNaCl Bitcode version\n");
  174. return false;
  175. }
  176. int field_data_total = wrapper_bc_offset_ - kWordSize * kFixedFields;
  177. if (field_data_total > 0) {
  178. // Read in the variable fields. We need to allocate space for the data.
  179. int field_data_read = 0;
  180. while (field_data_read < field_data_total) {
  181. FillBuffer();
  182. size_t buffer_needed = BCHeaderField::GetDataSizeFromSerialized(
  183. &buffer_[cursor_]);
  184. if (buffer_needed > buffer_.size()) {
  185. buffer_.resize(buffer_needed +
  186. sizeof(BCHeaderField::FixedSubfield) * 2);
  187. FillBuffer();
  188. }
  189. variable_field_data_.push_back(new uint8_t[buffer_needed]);
  190. BCHeaderField field(BCHeaderField::kInvalid, 0,
  191. variable_field_data_.back());
  192. field.Read(&buffer_[cursor_], buffer_size_);
  193. header_fields_.push_back(field);
  194. size_t field_size = field.GetTotalSize();
  195. cursor_ += field_size;
  196. field_data_read += field_size;
  197. if (field_data_read > field_data_total) {
  198. // We read too much data, the header is corrupted
  199. ALOGE("Error: raw bitcode offset inconsistent with "
  200. "variable field data\n");
  201. return false;
  202. }
  203. struct IntFieldHelper {
  204. BCHeaderField::FixedSubfield tag;
  205. uint16_t len;
  206. uint32_t val;
  207. };
  208. IntFieldHelper tempIntField;
  209. switch (field.getID()) {
  210. case BCHeaderField::kAndroidCompilerVersion:
  211. if (field.Write((uint8_t*)&tempIntField,
  212. sizeof(tempIntField))) {
  213. android_compiler_version_ = tempIntField.val;
  214. }
  215. break;
  216. case BCHeaderField::kAndroidOptimizationLevel:
  217. if (field.Write((uint8_t*)&tempIntField,
  218. sizeof(tempIntField))) {
  219. android_optimization_level_ = tempIntField.val;
  220. }
  221. break;
  222. default:
  223. // Ignore other field types for now
  224. break;
  225. }
  226. }
  227. Seek(0);
  228. }
  229. return true;
  230. }
  231. bool BitcodeWrapperer::IsInputBitcodeWrapper() {
  232. ResetCursor();
  233. // First make sure that there are enough words (LLVM header)
  234. // to peek at.
  235. if (GetBufferUnreadBytes() < kLLVMFields * kWordSize) {
  236. FillBuffer();
  237. if (GetBufferUnreadBytes() < kLLVMFields * kWordSize) return false;
  238. }
  239. // Now make sure the magic number is right.
  240. uint32_t first_word;
  241. if ((!ReadWord(first_word)) ||
  242. (kWrapperMagicNumber != first_word)) return false;
  243. // Make sure the version is right.
  244. uint32_t second_word;
  245. if ((!ReadWord(second_word)) ||
  246. (kLLVMVersionNumber != second_word)) return false;
  247. // Make sure that the offset and size (for llvm) is defined.
  248. uint32_t bc_offset;
  249. uint32_t bc_size;
  250. if (ReadWord(bc_offset) &&
  251. ReadWord(bc_size)) {
  252. // Before returning, save the extracted values.
  253. wrapper_bc_offset_ = bc_offset;
  254. infile_bc_offset_ = bc_offset;
  255. wrapper_bc_size_ = bc_size;
  256. return true;
  257. }
  258. // If reached, unable to read wrapped header.
  259. return false;
  260. }
  261. bool BitcodeWrapperer::IsInputBitcodeFile() {
  262. ResetCursor();
  263. // First make sure that there are four bytes to peek at.
  264. if (GetBufferUnreadBytes() < kWordSize) {
  265. FillBuffer();
  266. if (GetBufferUnreadBytes() < kWordSize) return false;
  267. }
  268. // If reached, Check if first 4 bytes match bitcode
  269. // file magic number.
  270. return (BufferLookahead(0) == 'B') &&
  271. (BufferLookahead(1) == 'C') &&
  272. (BufferLookahead(2) == 0xc0) &&
  273. (BufferLookahead(3) == 0xde);
  274. }
  275. bool BitcodeWrapperer::BufferCopyInToOut(uint32_t size) {
  276. while (size > 0) {
  277. // Be sure buffer is non-empty before writing.
  278. if (0 == buffer_size_) {
  279. FillBuffer();
  280. if (0 == buffer_size_) {
  281. return false;
  282. }
  283. }
  284. // copy the buffer to the output file.
  285. size_t block = (buffer_size_ < size) ? buffer_size_ : size;
  286. if (!outfile_->Write(&buffer_[cursor_], block)) return false;
  287. size -= block;
  288. buffer_size_ = 0;
  289. }
  290. // Be sure that there isn't more bytes on the input stream.
  291. FillBuffer();
  292. return buffer_size_ == 0;
  293. }
  294. void BitcodeWrapperer::AddHeaderField(BCHeaderField* field) {
  295. header_fields_.push_back(*field);
  296. wrapper_bc_offset_ += field->GetTotalSize();
  297. }
  298. bool BitcodeWrapperer::WriteBitcodeWrapperHeader() {
  299. return
  300. // Note: This writes out the 4 word header required by llvm wrapped
  301. // bitcode.
  302. WriteWord(kWrapperMagicNumber) &&
  303. WriteWord(kLLVMVersionNumber) &&
  304. WriteWord(wrapper_bc_offset_) &&
  305. WriteWord(wrapper_bc_size_) &&
  306. // 2 fixed fields defined by Android
  307. WriteWord(android_header_version_) &&
  308. WriteWord(android_target_api_) &&
  309. // PNaClBitcode version
  310. WriteWord(kPnaclBitcodeVersion) &&
  311. // Common variable-length fields
  312. WriteVariableFields();
  313. }
  314. void BitcodeWrapperer::PrintWrapperHeader() {
  315. if (error_) {
  316. fprintf(stderr, "Error condition exists: the following"
  317. "data may not be reliable\n");
  318. }
  319. fprintf(stderr, "Wrapper magic:\t\t%x\n", kWrapperMagicNumber);
  320. fprintf(stderr, "LLVM Bitcode version:\t%d\n", kLLVMVersionNumber);
  321. fprintf(stderr, "Raw bitcode offset:\t%d\n", wrapper_bc_offset_);
  322. fprintf(stderr, "Raw bitcode size:\t%d\n", wrapper_bc_size_);
  323. fprintf(stderr, "Android header version:\t%d\n", android_header_version_);
  324. fprintf(stderr, "Android target API:\t%d\n", android_target_api_);
  325. fprintf(stderr, "PNaCl bitcode version:\t%d\n", kPnaclBitcodeVersion);
  326. for (size_t i = 0; i < header_fields_.size(); i++) header_fields_[i].Print();
  327. }
  328. bool BitcodeWrapperer::GenerateWrappedBitcodeFile() {
  329. if (!error_ &&
  330. WriteBitcodeWrapperHeader() &&
  331. Seek(infile_bc_offset_) &&
  332. BufferCopyInToOut(wrapper_bc_size_)) {
  333. off_t dangling = wrapper_bc_size_ & 3;
  334. if (dangling) {
  335. return outfile_->Write((const uint8_t*) "\0\0\0\0", 4 - dangling);
  336. }
  337. return true;
  338. }
  339. return false;
  340. }
  341. bool BitcodeWrapperer::GenerateRawBitcodeFile() {
  342. return !error_ && Seek(infile_bc_offset_) &&
  343. BufferCopyInToOut(wrapper_bc_size_);
  344. }