blob: 12bc45108e94c1375aca7da73835b6d3a55be5a3 [file] [log] [blame]
David Brazdil7b49e6c2016-09-01 11:06:18 +01001/*
2 * Copyright (C) 2016 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 "vdex_file.h"
18
19#include <memory>
20
21#include "base/logging.h"
22
23namespace art {
24
25constexpr uint8_t VdexFile::Header::kVdexMagic[4];
26constexpr uint8_t VdexFile::Header::kVdexVersion[4];
27
28bool VdexFile::Header::IsMagicValid() const {
29 return (memcmp(magic_, kVdexMagic, sizeof(kVdexMagic)) == 0);
30}
31
32bool VdexFile::Header::IsVersionValid() const {
33 return (memcmp(version_, kVdexVersion, sizeof(kVdexVersion)) == 0);
34}
35
36VdexFile::Header::Header() {
37 memcpy(magic_, kVdexMagic, sizeof(kVdexMagic));
38 memcpy(version_, kVdexVersion, sizeof(kVdexVersion));
39 DCHECK(IsMagicValid());
40 DCHECK(IsVersionValid());
41}
42
43VdexFile* VdexFile::Open(const std::string& vdex_filename,
44 bool writable,
45 bool low_4gb,
46 std::string* error_msg) {
47 if (!OS::FileExists(vdex_filename.c_str())) {
48 *error_msg = "File " + vdex_filename + " does not exist.";
49 return nullptr;
50 }
51
52 std::unique_ptr<File> vdex_file;
53 if (writable) {
54 vdex_file.reset(OS::OpenFileReadWrite(vdex_filename.c_str()));
55 } else {
56 vdex_file.reset(OS::OpenFileForReading(vdex_filename.c_str()));
57 }
58 if (vdex_file == nullptr) {
59 *error_msg = "Could not open file " + vdex_filename +
60 (writable ? " for read/write" : "for reading");
61 return nullptr;
62 }
63
64 int64_t vdex_length = vdex_file->GetLength();
65 if (vdex_length == -1) {
66 *error_msg = "Could not read the length of file " + vdex_filename;
67 return nullptr;
68 }
69
70 std::unique_ptr<MemMap> mmap(MemMap::MapFile(vdex_length,
71 writable ? PROT_READ | PROT_WRITE : PROT_READ,
72 MAP_SHARED,
73 vdex_file->Fd(),
74 0 /* start offset */,
75 low_4gb,
76 vdex_filename.c_str(),
77 error_msg));
78 if (mmap == nullptr) {
79 *error_msg = "Failed to mmap file " + vdex_filename + " : " + *error_msg;
80 return nullptr;
81 }
82
83 *error_msg = "Success";
84 return new VdexFile(vdex_file.release(), mmap.release());
85}
86
87} // namespace art