1# 2# Copyright (C) 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# 16"""This file contains ELF utility functions.""" 17 18 19def DecodeSLEB128(data, begin_offset=0): 20 """Decode one int64 from SLEB128 encoded bytes. 21 22 Args: 23 data: A str, bytes to decode. 24 begin_offset: An integer, offset in data to start decode from. 25 26 Returns: 27 A tuple (value, num), the decoded value and number of consumed bytes. 28 29 Raises: 30 IndexError: String index out of range. 31 """ 32 cur = begin_offset 33 value = 0 34 shift = 0 35 while True: 36 try: 37 byte, cur = ord(data[cur]), cur + 1 38 except IndexError: 39 raise 40 value |= (byte & 0x7F) << shift 41 shift += 7 42 if byte & 0x80 == 0: 43 break 44 if byte & 0x40: 45 value |= (-1) << shift 46 return value, cur - begin_offset 47