blob: 1471c59b730e77c1d2ce4d94970861fdd8a64b74 [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 Gampe57943812017-12-06 21:39:13 -080023#include <android-base/logging.h>
24#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080025
David Sehr1979c642018-04-26 14:41:18 -070026#include "unix_file/fd_file.h"
Vladimir Marko5096e662015-12-08 19:25:49 +000027
28namespace art {
29
Andreas Gampe46ee31b2016-12-14 10:11:49 -080030using android::base::StringPrintf;
31
Andreas Gampe43e10b02016-07-15 17:17:34 -070032File OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
Vladimir Marko5096e662015-12-08 19:25:49 +000033 CHECK(magic != nullptr);
Andreas Gampe0de385f2018-10-11 11:11:13 -070034 File fd(filename, O_RDONLY, /* check_usage= */ false);
Andreas Gampe43e10b02016-07-15 17:17:34 -070035 if (fd.Fd() == -1) {
Vladimir Marko5096e662015-12-08 19:25:49 +000036 *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
Andreas Gampe43e10b02016-07-15 17:17:34 -070037 return File();
Vladimir Marko5096e662015-12-08 19:25:49 +000038 }
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -070039 if (!ReadMagicAndReset(fd.Fd(), magic, error_msg)) {
40 StringPrintf("Error in reading magic from file %s: %s", filename, error_msg->c_str());
Andreas Gampe43e10b02016-07-15 17:17:34 -070041 return File();
Vladimir Marko5096e662015-12-08 19:25:49 +000042 }
43 return fd;
44}
45
Shubham Ajmerac12bf4c2017-10-24 16:59:42 -070046bool ReadMagicAndReset(int fd, uint32_t* magic, std::string* error_msg) {
47 int n = TEMP_FAILURE_RETRY(read(fd, magic, sizeof(*magic)));
48 if (n != sizeof(*magic)) {
49 *error_msg = StringPrintf("Failed to find magic");
50 return false;
51 }
52 if (lseek(fd, 0, SEEK_SET) != 0) {
53 *error_msg = StringPrintf("Failed to seek to beginning of file : %s", strerror(errno));
54 return false;
55 }
56 return true;
57}
58
Vladimir Marko5096e662015-12-08 19:25:49 +000059bool IsZipMagic(uint32_t magic) {
60 return (('P' == ((magic >> 0) & 0xff)) &&
61 ('K' == ((magic >> 8) & 0xff)));
62}
63
Vladimir Marko5096e662015-12-08 19:25:49 +000064} // namespace art