blob: 568a7ae5d671c56eeab8a84424741947b43c29d7 [file] [log] [blame]
Vladimir Marko5096e662015-12-08 19:25:49 +00001/*
2 * Copyright (C) 2015 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 "file_magic.h"
18
19#include <fcntl.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include "android-base/stringprintf.h"
24
Vladimir Marko5096e662015-12-08 19:25:49 +000025#include "base/logging.h"
Andreas Gampe43e10b02016-07-15 17:17:34 -070026#include "base/unix_file/fd_file.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000027#include "dex_file.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000028
29namespace art {
30
Andreas Gampe46ee31b2016-12-14 10:11:49 -080031using android::base::StringPrintf;
32
Andreas Gampe43e10b02016-07-15 17:17:34 -070033File OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Vladimir Marko5096e662015-12-08 19:25:49 +000034 CHECK(magic != nullptr);
Andreas Gampe43e10b02016-07-15 17:17:34 -070035 File fd(filename, O_RDONLY, /* check_usage */ false);
36 if (fd.Fd() == -1) {
Vladimir Marko5096e662015-12-08 19:25:49 +000037 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Andreas Gampe43e10b02016-07-15 17:17:34 -070038 return File();
Vladimir Marko5096e662015-12-08 19:25:49 +000039 }
Andreas Gampe43e10b02016-07-15 17:17:34 -070040 int n = TEMP_FAILURE_RETRY(read(fd.Fd(), magic, sizeof(*magic)));
Vladimir Marko5096e662015-12-08 19:25:49 +000041 if (n != sizeof(*magic)) {
42 *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
Andreas Gampe43e10b02016-07-15 17:17:34 -070043 return File();
Vladimir Marko5096e662015-12-08 19:25:49 +000044 }
Andreas Gampe43e10b02016-07-15 17:17:34 -070045 if (lseek(fd.Fd(), 0, SEEK_SET) != 0) {
Vladimir Marko5096e662015-12-08 19:25:49 +000046 *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
47 strerror(errno));
Andreas Gampe43e10b02016-07-15 17:17:34 -070048 return File();
Vladimir Marko5096e662015-12-08 19:25:49 +000049 }
50 return fd;
51}
52
53bool IsZipMagic(uint32_t magic) {
54 return (('P' == ((magic >> 0) & 0xff)) &&
55 ('K' == ((magic >> 8) & 0xff)));
56}
57
58bool IsDexMagic(uint32_t magic) {
59 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
60}
61
62} // namespace art