xref: /aosp_15_r20/external/minijail/tools/arch.py (revision 4b9c6d91573e8b3a96609339b46361b5476dd0f9)
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2018 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17"""Architecture-specific information."""
18
19import collections
20import json
21
22
23class Arch(
24        collections.namedtuple('Arch', [
25            'arch_nr', 'arch_name', 'bits', 'syscalls', 'constants',
26            'syscall_groups'
27        ])):
28    """Holds architecture-specific information."""
29
30    def truncate_word(self, value):
31        """Return the value truncated to fit in a word."""
32        return value & self.max_unsigned
33
34    @property
35    def min_signed(self):
36        """The smallest signed value that can be represented in a word."""
37        return -(1 << (self.bits - 1))
38
39    @property
40    def max_unsigned(self):
41        """The largest unsigned value that can be represented in a word."""
42        return (1 << self.bits) - 1
43
44    @staticmethod
45    def load_from_json(json_path):
46        """Return an Arch from a .json file."""
47        with open(json_path, 'r') as json_file:
48            return Arch.load_from_json_bytes(json_file.read())
49
50    @staticmethod
51    def load_from_json_bytes(json_bytes):
52        """Return an Arch from a json string."""
53        constants = json.loads(json_bytes)
54        return Arch(
55            arch_nr=constants["arch_nr"],
56            arch_name=constants["arch_name"],
57            bits=constants["bits"],
58            syscalls=constants["syscalls"],
59            constants=constants["constants"],
60            syscall_groups=constants.get("syscall_groups", {}),
61        )
62