• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2021 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16import bisect
17import copy
18import os
19import struct
20import tempfile
21from hashlib import sha256
22
23from log_exception import UPDATE_LOGGER
24from blocks_manager import BlocksManager
25from utils import OPTIONS_MANAGER
26from utils import EXTEND_VALUE
27from utils import FILE_MAP_ZERO_KEY
28from utils import FILE_MAP_NONZERO_KEY
29from utils import FILE_MAP_COPY_KEY
30from utils import MAX_BLOCKS_PER_GROUP
31from utils import UPDATE_BIN_FILE_NAME
32from utils import FORBIDEN_UPDATE_IMAGE_SET
33
34
35class FullUpdateImage:
36    """
37    Full image processing class
38    """
39
40    def __init__(self, target_package_images_dir,
41                 full_img_list, full_img_name_list,
42                 verse_script, full_image_path_list,
43                 no_zip=False):
44        self.target_package_images_dir = target_package_images_dir
45        self.full_img_list = full_img_list
46        self.full_img_name_list = full_img_name_list
47        self.verse_script = verse_script
48        self.full_image_path_list = full_image_path_list
49        self.no_zip = no_zip
50
51    def update_full_image(self):
52        """
53        Processing of the full image
54        :return full_image_content_len_list: full image content length list
55        :return full_image_file_obj_list: full image temporary file list
56        """
57        full_image_file_obj_list = []
58        full_image_content_len_list = []
59        for idx, each_name in enumerate(self.full_img_list):
60            full_image_content = self.get_full_image_content(
61                self.full_image_path_list[idx])
62            img_name = self.full_img_name_list[idx][:-4]
63            if full_image_content is False:
64                UPDATE_LOGGER.print_log(
65                    "Get full image content failed!",
66                    log_type=UPDATE_LOGGER.ERROR_LOG)
67                return False, False
68            each_img = tempfile.NamedTemporaryFile(
69                dir=self.target_package_images_dir,
70                prefix="full_image%s" % img_name, mode='wb')
71            each_img.write(full_image_content)
72            each_img.seek(0)
73            full_image_content_len_list.append(len(full_image_content))
74            full_image_file_obj_list.append(each_img)
75            UPDATE_LOGGER.print_log(
76                "Image %s full processing completed" % img_name)
77        update_image_set = set(self.full_img_list) - FORBIDEN_UPDATE_IMAGE_SET
78        if not self.no_zip and len(update_image_set) != 0:
79            # No zip mode (no script command)
80            image_write_cmd = self.verse_script.full_image_update(UPDATE_BIN_FILE_NAME)
81            cmd = '%s_WRITE_FLAG%s' % (UPDATE_BIN_FILE_NAME, image_write_cmd)
82            if each_name not in FORBIDEN_UPDATE_IMAGE_SET:
83                self.verse_script.add_command(cmd=cmd)
84
85        UPDATE_LOGGER.print_log(
86            "All full image processing completed! image count: %d" %
87            len(self.full_img_list))
88        return full_image_content_len_list, full_image_file_obj_list
89
90    @staticmethod
91    def get_full_image_content(each_name):
92        """
93        Obtain the full image content.
94        :param each_name: image name
95        :return content: full image content if available; false otherwise
96        """
97        each_image_path = each_name
98        if not os.path.exists(each_image_path):
99            UPDATE_LOGGER.print_log(
100                "The file is missing "
101                "from the target package, "
102                "the component: %s cannot be full update processed. " %
103                each_image_path)
104            return False
105        with open(each_image_path, 'rb') as f_r:
106            content = f_r.read()
107        return content
108
109
110class IncUpdateImage:
111    """
112    Increment update image class
113    """
114
115    def __init__(self, image_path, map_path):
116        """
117        Initialize the inc image.
118        :param image_path: img file path
119        :param map_path: map file path
120        """
121        self.image_path = image_path
122        self.map_path = map_path
123        self.offset_value_list = []
124        self.care_block_range = None
125        self.extended_range = None
126        self.reserved_blocks = BlocksManager("0")
127        self.file_map = []
128        self.offset_index = []
129        self.block_size = None
130        self.total_blocks = None
131        self.parse_raw_image_file(image_path, map_path)
132
133    def parse_raw_image_file(self, image_path, map_path):
134        """
135        Parse the .img file.
136        :param image_path: img file path
137        :param map_path: map file path
138        """
139        self.block_size = block_size = 4096
140        self.total_blocks = total_blocks = \
141            os.path.getsize(self.image_path) // self.block_size
142        reference = b'\0' * self.block_size
143        with open(image_path, 'rb') as f_r:
144            care_value_list, offset_value_list = [], []
145            nonzero_blocks = []
146            for i in range(self.total_blocks):
147                blocks_data = f_r.read(self.block_size)
148                if blocks_data != reference:
149                    nonzero_blocks.append(i)
150                    nonzero_blocks.append(i + 1)
151            self.care_block_range = BlocksManager(nonzero_blocks)
152            care_value_list = list(self.care_block_range.range_data)
153            for idx, value in enumerate(care_value_list):
154                if idx != 0 and (idx + 1) % 2 == 0:
155                    be_value = int(care_value_list[idx - 1])
156                    af_value = int(care_value_list[idx])
157                    file_tell = be_value * block_size
158                    offset_value_list.append(
159                        (be_value, af_value - be_value,
160                         file_tell, None))
161
162            self.offset_index = [i[0] for i in offset_value_list]
163            self.offset_value_list = offset_value_list
164            extended_range = \
165                self.care_block_range.extend_value_to_blocks(EXTEND_VALUE)
166            all_blocks = BlocksManager(range_data=(0, total_blocks))
167            self.extended_range = \
168                extended_range.get_intersect_with_other(all_blocks). \
169                get_subtract_with_other(self.care_block_range)
170            self.parse_block_map_file(map_path, f_r)
171
172    def parse_block_map_file(self, map_path, image_file_r):
173        """
174        Parses the map file for blocks where files are contained in the image.
175        :param map_path: map file path
176        :param image_file_r: file reading object
177        :return:
178        """
179        remain_range = self.care_block_range
180        temp_file_map = {}
181
182        with open(map_path, 'r') as f_r:
183            # Read the .map file and process each line.
184            for each_line in f_r.readlines():
185                each_map_path, ranges_value = each_line.split(None, 1)
186                each_range = BlocksManager(ranges_value)
187                temp_file_map[each_map_path] = each_range
188                # each_range is contained in the remain range.
189                if each_range.size() != each_range. \
190                        get_intersect_with_other(remain_range).size():
191                    raise RuntimeError
192                # After the processing is complete,
193                # remove each_range from remain_range.
194                remain_range = remain_range.get_subtract_with_other(each_range)
195        reserved_blocks = self.reserved_blocks
196        # Remove reserved blocks from all blocks.
197        remain_range = remain_range.get_subtract_with_other(reserved_blocks)
198
199        # Divide all blocks into zero_blocks
200        # (if there are many) and nonzero_blocks.
201        zero_blocks_list = []
202        nonzero_blocks_list = []
203        nonzero_groups_list = []
204        default_zero_block = ('\0' * self.block_size).encode()
205
206        nonzero_blocks_list, nonzero_groups_list, zero_blocks_list = \
207            self.apply_remain_range(
208                default_zero_block, image_file_r, nonzero_blocks_list,
209                nonzero_groups_list, remain_range, zero_blocks_list)
210
211        temp_file_map = self.get_file_map(
212            nonzero_blocks_list, nonzero_groups_list,
213            reserved_blocks, temp_file_map, zero_blocks_list)
214        self.file_map = temp_file_map
215
216    def apply_remain_range(self, *args):
217        """
218        Implement traversal processing of remain_range.
219        """
220        default_zero_block, image_file_r, \
221            nonzero_blocks_list, nonzero_groups_list, \
222            remain_range, zero_blocks_list = args
223        for start_value, end_value in remain_range:
224            for each_value in range(start_value, end_value):
225                # bisect 二分查找,b在self.offset_index中的位置
226                idx = bisect.bisect_right(self.offset_index, each_value) - 1
227                chunk_start, _, file_pos, fill_data = \
228                    self.offset_value_list[idx]
229                data = self.get_file_data(self.block_size, chunk_start,
230                                          default_zero_block, each_value,
231                                          file_pos, fill_data, image_file_r)
232
233                zero_blocks_list, nonzero_blocks_list, nonzero_groups_list = \
234                    self.get_zero_nonzero_blocks_list(
235                        data, default_zero_block, each_value,
236                        nonzero_blocks_list, nonzero_groups_list,
237                        zero_blocks_list)
238        return nonzero_blocks_list, nonzero_groups_list, zero_blocks_list
239
240    @staticmethod
241    def get_file_map(*args):
242        """
243        Obtain the file map.
244        nonzero_blocks_list nonzero blocks list,
245        nonzero_groups_list nonzero groups list,
246        reserved_blocks reserved blocks ,
247        temp_file_map temporary file map,
248        zero_blocks_list zero block list
249        :return temp_file_map file map
250        """
251        nonzero_blocks_list, nonzero_groups_list, \
252            reserved_blocks, temp_file_map, zero_blocks_list = args
253        if nonzero_blocks_list:
254            nonzero_groups_list.append(nonzero_blocks_list)
255        if zero_blocks_list:
256            temp_file_map[FILE_MAP_ZERO_KEY] = \
257                BlocksManager(range_data=zero_blocks_list)
258        if nonzero_groups_list:
259            for i, blocks in enumerate(nonzero_groups_list):
260                temp_file_map["%s-%d" % (FILE_MAP_NONZERO_KEY, i)] = \
261                    BlocksManager(range_data=blocks)
262        if reserved_blocks:
263            temp_file_map[FILE_MAP_COPY_KEY] = reserved_blocks
264        return temp_file_map
265
266    @staticmethod
267    def get_zero_nonzero_blocks_list(*args):
268        """
269        Get zero_blocks_list, nonzero_blocks_list, and nonzero_groups_list.
270        data: block data,
271        default_zero_block: default to zero block,
272        each_value: each value,
273        nonzero_blocks_list: nonzero_blocks_list,
274        nonzero_groups_list: nonzero_groups_list,
275        zero_blocks_list: zero_blocks_list,
276        :return new_zero_blocks_list: new zero blocks list,
277        :return new_nonzero_blocks_list: new nonzero blocks list,
278        :return new_nonzero_groups_list: new nonzero groups list.
279        """
280        data, default_zero_block, each_value, \
281            nonzero_blocks_list, nonzero_groups_list, \
282            zero_blocks_list = args
283        # Check whether the data block is equal to the default zero_blocks.
284        if data == default_zero_block:
285            zero_blocks_list.append(each_value)
286            zero_blocks_list.append(each_value + 1)
287        else:
288            nonzero_blocks_list.append(each_value)
289            nonzero_blocks_list.append(each_value + 1)
290            # The number of nonzero_blocks is greater than
291            # or equal to the upper limit.
292            if len(nonzero_blocks_list) >= MAX_BLOCKS_PER_GROUP:
293                nonzero_groups_list.append(nonzero_blocks_list)
294                nonzero_blocks_list = []
295        new_zero_blocks_list, new_nonzero_blocks_list, \
296            new_nonzero_groups_list = \
297            copy.copy(zero_blocks_list), \
298            copy.copy(nonzero_blocks_list),\
299            copy.copy(nonzero_groups_list)
300        return new_zero_blocks_list, new_nonzero_blocks_list, \
301            new_nonzero_groups_list
302
303    @staticmethod
304    def get_file_data(*args):
305        """
306        Get the file data.
307        block_size: blocksize,
308        chunk_start: the start position of chunk,
309        default_zero_block: default to zero blocks,
310        each_value: each_value,
311        file_pos: file position,
312        fill_data: data,
313        image_file_r: read file object,
314        :return data: Get the file data.
315        """
316        block_size, chunk_start, default_zero_block, each_value, \
317            file_pos, fill_data, image_file_r = args
318        if file_pos is not None:
319            file_pos += (each_value - chunk_start) * block_size
320            image_file_r.seek(file_pos, os.SEEK_SET)
321            data = image_file_r.read(block_size)
322        else:
323            if fill_data == default_zero_block[:4]:
324                data = default_zero_block
325            else:
326                data = None
327        return data
328
329    def range_sha256(self, ranges):
330        """
331        range sha256 hash content
332        :param ranges: ranges value
333        :return:
334        """
335        hash_obj = sha256()
336        for data in self.__get_blocks_set_data(ranges):
337            hash_obj.update(data)
338        return hash_obj.hexdigest()
339
340    def write_range_data_2_fd(self, ranges, file_obj):
341        """
342        write range data to fd
343        :param ranges: ranges obj
344        :param file_obj: file obj
345        :return:
346        """
347        for data in self.__get_blocks_set_data(ranges):
348            file_obj.write(data)
349
350    def get_ranges(self, ranges):
351        """
352        get ranges value
353        :param ranges: ranges
354        :return: ranges value
355        """
356        return [each_data for each_data in self.__get_blocks_set_data(ranges)]
357
358    def __get_blocks_set_data(self, blocks_set_data):
359        """
360        Get the range data.
361        """
362        with open(self.image_path, 'rb') as f_r:
363            for start, end in blocks_set_data:
364                diff_value = end - start
365                idx = bisect.bisect_right(self.offset_index, start) - 1
366                chunk_start, chunk_len, file_pos, fill_data = \
367                    self.offset_value_list[idx]
368
369                remain = chunk_len - (start - chunk_start)
370                this_read = min(remain, diff_value)
371                if file_pos is not None:
372                    pos = file_pos + ((start - chunk_start) * self.block_size)
373                    f_r.seek(pos, os.SEEK_SET)
374                    yield f_r.read(this_read * self.block_size)
375                else:
376                    yield fill_data * (this_read * (self.block_size >> 2))
377                diff_value -= this_read
378
379                while diff_value > 0:
380                    idx += 1
381                    chunk_start, chunk_len, file_pos, fill_data = \
382                        self.offset_value_list[idx]
383                    this_read = min(chunk_len, diff_value)
384                    if file_pos is not None:
385                        f_r.seek(file_pos, os.SEEK_SET)
386                        yield f_r.read(this_read * self.block_size)
387                    else:
388                        yield fill_data * (this_read * (self.block_size >> 2))
389                    diff_value -= this_read