HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Valid memory address in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonaddressvalidmemory

Problem

I am looking for suggestions of improving this function to check whether a memory address is appropriate or not.

def isweird(addr, cpu_name):
    """Check if a memory address is weird
    Args:
        addr (str): a memory address
        cpu_name (str): cpu name
    Returns:
        bool: True if the address is weird
    """
    if not isinstance(addr, six.string_types):
        raise Exception('The memory address must be a string.')

    if addr == '0x0':
        return True

    addr = addr.lower()

    # Strip leading zeroes
    addr = addr[2:].lstrip('0')

    if utils.is64(cpu_name):
        if len(addr) = ((1 = 0xffffffffffff0000 (ie: last 64k)
                return True
    else:
        val = int(addr, 16)
        if val = ((1 = 0xffff0000 (ie: last 64k)
            return True
    return False

Solution

In this code:

if len(addr) = ((1 = 0xffffffffffff0000 (ie: last 64k)
        return True


You can replace the inner if statements with return statements:

if len(addr) = ((1 = 0xffffffffffff0000 (ie: last 64k)


This is possible because if these conditions are false,
the execution will reach the return False at the end of the function.
The reason to rewrite this way is so that the reader doesn't have to follow the execution path until the end of the function,
he can know on these lines that no further statements will be executed,
the return value is already decided at these points.

Some of the comments are incorrect and misleading:

if val = ((1 = 0xffffffffffff0000 (ie: last 64k)


1 << 16 is 0x10000, not 0xffff.

(1 << 32) - (1 << 16) is 0xffff0000, not 0xffffffffffff0000.

Following the naming conventions of Python,
the function isweird should be named is_weird instead.

Code Snippets

if len(addr) <= 8:
    val = int(addr, 16)
    if val <= (1 << 16):  # val <= 0xffff (ie: first 64k)
        return True
elif addr.startswith('ffffffff'):
    addr = addr[8:]  # 8 == len('ffffffff')
    val = int(addr, 16)
    if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffffffffffff0000 (ie: last 64k)
        return True
if len(addr) <= 8:
    val = int(addr, 16)
    return val <= (1 << 16)  # val <= 0xffff (ie: first 64k)
elif addr.startswith('ffffffff'):
    addr = addr[8:]  # 8 == len('ffffffff')
    val = int(addr, 16)
    return val >= ((1 << 32) - (1 << 16))  # val >= 0xffffffffffff0000 (ie: last 64k)
if val <= (1 << 16):  # val <= 0xffff (ie: first 64k)

if val >= ((1 << 32) - (1 << 16)):  # val >= 0xffffffffffff0000 (ie: last 64k)

Context

StackExchange Code Review Q#140147, answer score: 6

Revisions (0)

No revisions yet.