Sub topic 3
How pickle works: a small virtual machine
Assume you know basic Python classes, special methods, byte streams, and the difference between a model and its weights. You should also understand that serialization turns an in-memory object into bytes, while deserialization reconstructs the object from those bytes.
Pickle is an instruction stream
pickle is Python's object serialization format. It does not store an object as a simple picture of its fields. Instead, it writes a sequence of instructions called opcodes. A pickle interpreter reads those instructions and builds the original object.
The interpreter behaves like a small stack-based virtual machine:
- The stack holds values currently being assembled.
- The memo stores objects that may be reused later.
- The opcode stream tells the interpreter what to push, combine, save, or return.
STOPends the stream and returns the value at the top of the stack.
For example, a list containing two integers can be represented by instructions that push an empty list, push each integer, append them, and stop.
import pickle
import pickletools
value = [10, 20]
data = pickle.dumps(value, protocol=4)
print("Serialized bytes:", data)
print("\nOpcodes:")
pickletools.dis(data)The exact bytes depend on the pickle protocol. A protocol is a numbered version of the pickle instruction set. Newer protocols can be more compact or support more Python features, but they do not make untrusted pickle data safe.
The stack and memo
Suppose the stream needs to construct a dictionary. It can push an empty dictionary onto the stack, then push a key and a value, and finally use an instruction that adds the pair to the dictionary.
Some instructions use a temporary marker called MARK. The marker separates items that belong to one operation from values already on the stack. A tuple or list can therefore be assembled from everything above the marker.
The memo is different from the stack. It gives objects numeric references. This allows pickle to preserve:
- Shared references, where two fields point to the same object.
- Cycles, where an object eventually refers back to itself.
- Repeated values without writing the same object repeatedly.
A memo reference is an instruction, not a copy of the object. During loading, the interpreter looks up the referenced object and places it on the stack.
Instructions can name callables
Some opcodes identify a Python object by its module and name. Other instructions combine a callable with arguments and invoke it to reconstruct a value. This mechanism supports custom classes and special methods such as __reduce__.
That flexibility is the source of pickle's security risk. The interpreter is designed to rebuild Python objects, not merely copy numeric data. If a pickle controls which callable is named and which arguments it receives, loading the pickle may perform an unexpected function call.
Inspecting instructions without loading
pickletools.dis decodes the opcode stream without running the unpickler. It is useful for reviewing a suspicious file, although inspection alone does not prove that a file is safe. The next chapter examines how callable reconstruction can become code execution.
Exercise
What are the two main temporary storage areas used by the pickle virtual machine, and what does each one do?
Show answer
The stack holds values while an object is being assembled. The memo stores references to objects so pickle can reuse them and preserve shared references or cycles.