1#
2#   Copyright 2018 - 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
16import logging
17import struct
18
19OS_VERSOIN_OFFSET_BOOTIMG = 44
20SPL_YEAR_BASE_BOOTIMG = 2000
21SPL_YEAR_MASK_BOOTIMG = 127 << 4
22SPL_MONTH_MASK_BOOTIMG = 15
23
24
25def GetSPLVersionFromBootImg(img_file_path):
26    """Gets SPL version from given boot.img file path.
27
28    Args:
29        img_file_path : string, path to the boot.img file.
30    Returns:
31        A dict contains SPL version's year and date value.
32    """
33    try:
34        fo = open(img_file_path, "rb")
35        fo.seek(OS_VERSOIN_OFFSET_BOOTIMG, 0)
36
37        os_version = fo.read(4)
38    except IOError as e:
39        logging.error(e.strerror)
40        return {}
41
42    os_version_int = struct.unpack("i", os_version)[0]
43
44    year = (os_version_int & SPL_YEAR_MASK_BOOTIMG) >> 4
45    month = os_version_int & SPL_MONTH_MASK_BOOTIMG
46
47    version_date = {}
48    version_date["year"] = SPL_YEAR_BASE_BOOTIMG + year
49    version_date["month"] = month
50
51    return version_date