Skip to content

Instantly share code, notes, and snippets.

View kenballus's full-sized avatar

Ben Kallus kenballus

View GitHub Profile

Meditations on the Entry Point of a Dynamic ELF

Consider the following C program, which we'll call a.c:

#include <stdio.h>

int main(void) {
    puts("Hello world");
}
@kenballus
kenballus / re_generate.py
Created October 18, 2023 17:36
A function for generating examples that match a given Python re for bytes
# This relies on the internal workings of the re module, so don't be surprised if it crashes or doesn't
# work on versions of Python other than 3.11.3.
# I do not want to support Unicode, because it would be way harder. This only works for bytes.
# If you want something that supports Unicode, consider using hypothesis.strategies.from_regex.
# This also does not support \A, \Z, \b, ^, and $.
import re
from re._constants import _NamedIntConstant as RegexConstant # type: ignore
from re._parser import ( # type: ignore
IN,
@kenballus
kenballus / rfc_3986_regex.py
Created January 26, 2023 15:40
A direct translation from RFC3986's collected ABNF to python regexes.
# unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
UNRESERVED_PAT: str = r"([A-Za-z0-9\-\._~])"
# pct-encoded = "%" HEXDIG HEXDIG
PCT_ENCODED_PAT: str = r"(%[A-F0-9][A-F0-9])"
# sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
SUB_DELIMS_PAT: str = r"([!\$&'\(\)\*\+,;=])"
# pchar = unreserved / pct-encoded / sub-delims / ":" / "@"

I recently challenged myself to write a function in Python with the type signature make_tuple_type(T: type, n: int) -> type that returns the type of tuples consisting of n elements of type T. For example, make_tuple_type(str, 4) should return typing.Tuple[str, str, str, str]. My first thought was to use a starred expression:

>>> from typing import Tuple
>>> def make_tuple_type(T: type, n: int) -> type:
...     return Tuple[*[int] * n]
  File "<stdin>", line 2
    return Tuple[*[int] * n]
                 ^
SyntaxError: invalid syntax
&gt;&gt;&gt; # Note that that wasn't a TypeError saying I can't multiply a type by an int,

Pointers

This is a primer on pointers for students learning C, and thus sacrifices some accuracy for clarity. Please do not treat it as absolute truth.

Before a program runs, its code and data are copied into memory. Thus, all code and data is associated with a memory address during program execution. A pointer is just a variable that contains one such memory address. We will now address a few of the most common use cases for pointers in C.

In-out arguments

Consider the following C program:

#include "mt7620a.dtsi"
#include <dt-bindings/gpio/gpio.h>
#include <dt-bindings/input/input.h>
/ {
compatible = "linksys,ea6100", "ralink,mt7620a-soc";
model = "Linksys EA6100";
nand {