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