• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
23 #include "base/logging.h"
24 #include "dex_file.h"
25 #include "stringprintf.h"
26 
27 namespace art {
28 
OpenAndReadMagic(const char * filename,uint32_t * magic,std::string * error_msg)29 ScopedFd OpenAndReadMagic(const char* filename, uint32_t* magic, std::string* error_msg) {
30   CHECK(magic != nullptr);
31   ScopedFd fd(open(filename, O_RDONLY, 0));
32   if (fd.get() == -1) {
33     *error_msg = StringPrintf("Unable to open '%s' : %s", filename, strerror(errno));
34     return ScopedFd();
35   }
36   int n = TEMP_FAILURE_RETRY(read(fd.get(), magic, sizeof(*magic)));
37   if (n != sizeof(*magic)) {
38     *error_msg = StringPrintf("Failed to find magic in '%s'", filename);
39     return ScopedFd();
40   }
41   if (lseek(fd.get(), 0, SEEK_SET) != 0) {
42     *error_msg = StringPrintf("Failed to seek to beginning of file '%s' : %s", filename,
43                               strerror(errno));
44     return ScopedFd();
45   }
46   return fd;
47 }
48 
IsZipMagic(uint32_t magic)49 bool IsZipMagic(uint32_t magic) {
50   return (('P' == ((magic >> 0) & 0xff)) &&
51           ('K' == ((magic >> 8) & 0xff)));
52 }
53 
IsDexMagic(uint32_t magic)54 bool IsDexMagic(uint32_t magic) {
55   return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
56 }
57 
58 }  // namespace art
59