#!/usr/bin/python3
# ELF support functionality for Python.
# Copyright (C) 2022-2025 Free Software Foundation, Inc.
# This file is part of the GNU C Library.
#
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <https://www.gnu.org/licenses/>.
"""Basic ELF parser.
Use Image.readfile(path) to read an ELF file into memory and begin
parsing it.
"""
import collections
import functools
import os
import struct
import glibcpp
class _MetaNamedValue(type):
"""Used to set up _NamedValue subclasses."""
@classmethod
def __prepare__(metacls, cls, bases, **kwds):
# Indicates an int-based class. Needed for types like Shn.
int_based = False
for base in bases:
if issubclass(base, int):
int_based = int
break
return dict(by_value={},
by_name={},
prefix=None,
_int_based=int_based)
def __contains__(self, other):
return other in self.by_value
class _NamedValue(metaclass=_MetaNamedValue):
"""Typed, named integer constants.
Constants have the following instance attributes:
name: The full name of the constant (e.g., "PT_NULL").
short_name: The name with of the constant without the prefix ("NULL").
value: The integer value of the constant.
The following class attributes are available:
by_value: A dict mapping integers to constants.
by_name: A dict mapping strings to constants.
prefix: A string that is removed from the start of short names, or None.
"""
def __new__(cls, arg0, arg1=None):
"""Instance creation.
For the one-argument form, the argument must be a string, an
int, or an instance of this class. Strings are looked up via
by_name. Values are looked up via by_value; if value lookup
fails, a new unnamed instance is returned. Instances of this
class a re returned as-is.
The two-argument form expects the name (a string) and the
value (an integer). A new instance is created in this case.
The instance is not registered in the by_value/by_name
dictionaries (but the caller can do that).
"""
typ0 = type(arg0)
if arg1 is N