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            constants = json.load(json_file)
49            return Arch(
50                arch_nr=constants['arch_nr'],
51                arch_name=constants['arch_name'],
52                bits=constants['bits'],
53                syscalls=constants['syscalls'],
54                constants=constants['constants'],
55                syscall_groups=constants.get('syscall_groups', {}),
56            )
57