uppercut-pcsx2-pine 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- uppercut_pcsx2_pine-0.1.0/.gitignore +16 -0
- uppercut_pcsx2_pine-0.1.0/LICENSE +21 -0
- uppercut_pcsx2_pine-0.1.0/PKG-INFO +131 -0
- uppercut_pcsx2_pine-0.1.0/README.md +109 -0
- uppercut_pcsx2_pine-0.1.0/pyproject.toml +35 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/__init__.py +36 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/client.py +318 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/errors.py +34 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/fake_server.py +227 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/protocol.py +146 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/py.typed +0 -0
- uppercut_pcsx2_pine-0.1.0/src/uppercut_pcsx2_pine/transport.py +161 -0
- uppercut_pcsx2_pine-0.1.0/tests/conftest.py +39 -0
- uppercut_pcsx2_pine-0.1.0/tests/servers.py +16 -0
- uppercut_pcsx2_pine-0.1.0/tests/test_client.py +270 -0
- uppercut_pcsx2_pine-0.1.0/tests/test_protocol.py +122 -0
- uppercut_pcsx2_pine-0.1.0/tests/test_transport.py +214 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Uppercut Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-pcsx2-pine
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A client for PCSX2's PINE socket: read and write PS2 memory, batch reads, title, status, game id, save states, with an optional write allowlist.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-pcsx2-pine
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: emulator,ipc,memory,pcsx2,pine,playstation-2,ps2
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Games/Entertainment
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# uppercut-pcsx2-pine
|
|
24
|
+
|
|
25
|
+
A client for [PCSX2](https://pcsx2.net)'s PINE socket. It reads and writes PlayStation 2 memory (8, 16, 32 and 64 bits, single or batched), asks for the title, status, game id, disc CRC and versions, saves and loads states, and can refuse every write outside a list of allowed ranges. It speaks over a Unix socket (Linux and macOS) or a TCP port on the local machine (Windows). Standard library only.
|
|
26
|
+
|
|
27
|
+
The wire format was checked against PCSX2's own server source (`pcsx2/PINE.cpp`): opcodes 0 to 15, the length framing, the 650,000-byte request and 449,999-byte reply limits, the 0xFF failure byte, and the socket name PCSX2 gives each slot. The client contains no game addresses; those stay in your code.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install uppercut-pcsx2-pine
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
PINE is off in a stock PCSX2: turn on *Enable PINE* in its settings (or `EnablePINE = true` in the ini) and start a game.
|
|
34
|
+
|
|
35
|
+
## Python
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from uppercut_pcsx2_pine import PineClient, PineCommandFailed, PineConnectionError, signed
|
|
39
|
+
|
|
40
|
+
# Linux and macOS: the Unix socket PCSX2 made. Windows: PineClient.tcp(port=28011).
|
|
41
|
+
with PineClient.unix(slot=28011) as pine:
|
|
42
|
+
print(pine.identity()) # version, title, game id, uuid, game version, status
|
|
43
|
+
hp = signed(pine.read16(0x00345678), 16)
|
|
44
|
+
x, y = pine.read_many([(0x00345680, 32), (0x00345684, 32)])
|
|
45
|
+
blob = pine.read_bytes(0x00345700, 0x240)
|
|
46
|
+
pine.save_state(1)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Reads return unsigned integers. `signed(value, bits)` turns one into a two's-complement number.
|
|
50
|
+
|
|
51
|
+
### Batches
|
|
52
|
+
|
|
53
|
+
A batch is one PINE message: every command in it runs before the next message is handled. Reads answer in order.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
x, y = (
|
|
57
|
+
pine.batch()
|
|
58
|
+
.write32(0x00345800, 1) # writes are allowed in a batch; they answer nothing
|
|
59
|
+
.read32(0x00345680)
|
|
60
|
+
.read32(0x00345684)
|
|
61
|
+
.execute()
|
|
62
|
+
)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`read_many` and `read_bytes` build batches for you. A request is limited to 650,000 bytes and a reply to 449,999, so a long list becomes several messages (`read_bytes` moves 32 KiB at a time) and is not one atomic snapshot; a hand-built batch that cannot fit one message raises `ValueError` as you add to it. `read_bytes` uses 64-bit reads for the bulk and 32, 16 and 8-bit reads for the tail, so any length and alignment works.
|
|
66
|
+
|
|
67
|
+
### Write allowlist
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from uppercut_pcsx2_pine import PineClient, PineWriteDenied
|
|
71
|
+
|
|
72
|
+
read_only = PineClient.unix(write_allowlist=[]) # no writes at all
|
|
73
|
+
guarded = PineClient.unix(write_allowlist=[(0x00400000, 0x00400100)]) # start inclusive, end exclusive
|
|
74
|
+
try:
|
|
75
|
+
guarded.write8(0x00500000, 1)
|
|
76
|
+
except PineWriteDenied:
|
|
77
|
+
... # nothing was sent
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
With no `write_allowlist` argument every write is allowed. A write must lie inside one range. `PineWriteDenied` is also a `PermissionError`. A `WriteAllowlist` object can be passed instead of a list and extended later with `add(start, end)`.
|
|
81
|
+
|
|
82
|
+
### Save states
|
|
83
|
+
|
|
84
|
+
`save_state(slot)` and `load_state(slot)` take a slot from 0 to 255. PCSX2 answers at once and does the work later on its emulation thread, so a caller that needs the file must wait for it to appear (or for `status()` to read running again).
|
|
85
|
+
|
|
86
|
+
### Errors
|
|
87
|
+
|
|
88
|
+
| Error | When |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `PineConnectionError` | the socket is missing or refused the connection, or closed before a whole reply. Also a `ConnectionError` and so an `OSError` |
|
|
91
|
+
| `PineTimeoutError` | no answer within `timeout` (default 2 s). A `PineConnectionError` and a `TimeoutError` |
|
|
92
|
+
| `PineCommandFailed` | PCSX2 answered 0xFF. It does this for memory, string and state commands while no game is running. `status()` and `version()` still answer |
|
|
93
|
+
| `PineProtocolError` | a reply the protocol does not allow: bad length, unknown result byte, wrong payload size, unknown status |
|
|
94
|
+
| `PineWriteDenied` | a write outside the allowlist. A `PermissionError` too |
|
|
95
|
+
| `ValueError`, `TypeError` | an address outside 32 bits, a value too wide for its width, a width other than 8, 16, 32 or 64 |
|
|
96
|
+
|
|
97
|
+
All of them except the last two are `PineError`. After any error but `PineCommandFailed` and `PineWriteDenied` the connection is dropped and the next call opens a new one.
|
|
98
|
+
|
|
99
|
+
### Sockets
|
|
100
|
+
|
|
101
|
+
| | |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `PineClient.unix(path=None, slot=28011)` | Unix socket. With no path, `default_socket_path(slot)`: `$TMPDIR` on macOS, `$XDG_RUNTIME_DIR` elsewhere, then `/tmp`; the file is `pcsx2.sock`, plus `.<slot>` when the slot is not 28011 |
|
|
104
|
+
| `PineClient.tcp(host="127.0.0.1", port=28011)` | TCP, what PCSX2 on Windows listens on |
|
|
105
|
+
| `PineClient()` | the Unix socket, or TCP on Windows |
|
|
106
|
+
|
|
107
|
+
Connections are kept open between calls by default; pass `persistent=False` to open one per request. One client can be shared by threads: requests are serialised.
|
|
108
|
+
|
|
109
|
+
## Testing your own code
|
|
110
|
+
|
|
111
|
+
`uppercut_pcsx2_pine.fake_server.FakePineServer` is a stand-in server for tests. It runs in your process on TCP or a Unix socket, follows PCSX2's rules (a bad command fails the whole message, memory commands fail without a game, the size limits are the real ones), keeps memory in a `bytearray` and records the requests it received. No emulator, BIOS or game is needed.
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from uppercut_pcsx2_pine import PineClient
|
|
115
|
+
from uppercut_pcsx2_pine.fake_server import FakePineServer
|
|
116
|
+
|
|
117
|
+
with FakePineServer(bytearray(0x1000), base=0x100000) as server:
|
|
118
|
+
with PineClient.tcp(port=server.start_tcp()) as pine:
|
|
119
|
+
pine.write32(0x100000, 0xDEADBEEF)
|
|
120
|
+
assert pine.read8(0x100003) == 0xDE
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Notes
|
|
124
|
+
|
|
125
|
+
- The PINE protocol belongs to PCSX2 (GPL-3.0-or-later). This package is an independent client written from the wire format and shares no PCSX2 code.
|
|
126
|
+
- Memory reads and writes go through PCSX2's own memory mapping, so addresses are the guest's virtual addresses.
|
|
127
|
+
- PCSX2 does not report a failed save or load over PINE; check the file.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# uppercut-pcsx2-pine
|
|
2
|
+
|
|
3
|
+
A client for [PCSX2](https://pcsx2.net)'s PINE socket. It reads and writes PlayStation 2 memory (8, 16, 32 and 64 bits, single or batched), asks for the title, status, game id, disc CRC and versions, saves and loads states, and can refuse every write outside a list of allowed ranges. It speaks over a Unix socket (Linux and macOS) or a TCP port on the local machine (Windows). Standard library only.
|
|
4
|
+
|
|
5
|
+
The wire format was checked against PCSX2's own server source (`pcsx2/PINE.cpp`): opcodes 0 to 15, the length framing, the 650,000-byte request and 449,999-byte reply limits, the 0xFF failure byte, and the socket name PCSX2 gives each slot. The client contains no game addresses; those stay in your code.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install uppercut-pcsx2-pine
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
PINE is off in a stock PCSX2: turn on *Enable PINE* in its settings (or `EnablePINE = true` in the ini) and start a game.
|
|
12
|
+
|
|
13
|
+
## Python
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from uppercut_pcsx2_pine import PineClient, PineCommandFailed, PineConnectionError, signed
|
|
17
|
+
|
|
18
|
+
# Linux and macOS: the Unix socket PCSX2 made. Windows: PineClient.tcp(port=28011).
|
|
19
|
+
with PineClient.unix(slot=28011) as pine:
|
|
20
|
+
print(pine.identity()) # version, title, game id, uuid, game version, status
|
|
21
|
+
hp = signed(pine.read16(0x00345678), 16)
|
|
22
|
+
x, y = pine.read_many([(0x00345680, 32), (0x00345684, 32)])
|
|
23
|
+
blob = pine.read_bytes(0x00345700, 0x240)
|
|
24
|
+
pine.save_state(1)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Reads return unsigned integers. `signed(value, bits)` turns one into a two's-complement number.
|
|
28
|
+
|
|
29
|
+
### Batches
|
|
30
|
+
|
|
31
|
+
A batch is one PINE message: every command in it runs before the next message is handled. Reads answer in order.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
x, y = (
|
|
35
|
+
pine.batch()
|
|
36
|
+
.write32(0x00345800, 1) # writes are allowed in a batch; they answer nothing
|
|
37
|
+
.read32(0x00345680)
|
|
38
|
+
.read32(0x00345684)
|
|
39
|
+
.execute()
|
|
40
|
+
)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`read_many` and `read_bytes` build batches for you. A request is limited to 650,000 bytes and a reply to 449,999, so a long list becomes several messages (`read_bytes` moves 32 KiB at a time) and is not one atomic snapshot; a hand-built batch that cannot fit one message raises `ValueError` as you add to it. `read_bytes` uses 64-bit reads for the bulk and 32, 16 and 8-bit reads for the tail, so any length and alignment works.
|
|
44
|
+
|
|
45
|
+
### Write allowlist
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from uppercut_pcsx2_pine import PineClient, PineWriteDenied
|
|
49
|
+
|
|
50
|
+
read_only = PineClient.unix(write_allowlist=[]) # no writes at all
|
|
51
|
+
guarded = PineClient.unix(write_allowlist=[(0x00400000, 0x00400100)]) # start inclusive, end exclusive
|
|
52
|
+
try:
|
|
53
|
+
guarded.write8(0x00500000, 1)
|
|
54
|
+
except PineWriteDenied:
|
|
55
|
+
... # nothing was sent
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
With no `write_allowlist` argument every write is allowed. A write must lie inside one range. `PineWriteDenied` is also a `PermissionError`. A `WriteAllowlist` object can be passed instead of a list and extended later with `add(start, end)`.
|
|
59
|
+
|
|
60
|
+
### Save states
|
|
61
|
+
|
|
62
|
+
`save_state(slot)` and `load_state(slot)` take a slot from 0 to 255. PCSX2 answers at once and does the work later on its emulation thread, so a caller that needs the file must wait for it to appear (or for `status()` to read running again).
|
|
63
|
+
|
|
64
|
+
### Errors
|
|
65
|
+
|
|
66
|
+
| Error | When |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `PineConnectionError` | the socket is missing or refused the connection, or closed before a whole reply. Also a `ConnectionError` and so an `OSError` |
|
|
69
|
+
| `PineTimeoutError` | no answer within `timeout` (default 2 s). A `PineConnectionError` and a `TimeoutError` |
|
|
70
|
+
| `PineCommandFailed` | PCSX2 answered 0xFF. It does this for memory, string and state commands while no game is running. `status()` and `version()` still answer |
|
|
71
|
+
| `PineProtocolError` | a reply the protocol does not allow: bad length, unknown result byte, wrong payload size, unknown status |
|
|
72
|
+
| `PineWriteDenied` | a write outside the allowlist. A `PermissionError` too |
|
|
73
|
+
| `ValueError`, `TypeError` | an address outside 32 bits, a value too wide for its width, a width other than 8, 16, 32 or 64 |
|
|
74
|
+
|
|
75
|
+
All of them except the last two are `PineError`. After any error but `PineCommandFailed` and `PineWriteDenied` the connection is dropped and the next call opens a new one.
|
|
76
|
+
|
|
77
|
+
### Sockets
|
|
78
|
+
|
|
79
|
+
| | |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| `PineClient.unix(path=None, slot=28011)` | Unix socket. With no path, `default_socket_path(slot)`: `$TMPDIR` on macOS, `$XDG_RUNTIME_DIR` elsewhere, then `/tmp`; the file is `pcsx2.sock`, plus `.<slot>` when the slot is not 28011 |
|
|
82
|
+
| `PineClient.tcp(host="127.0.0.1", port=28011)` | TCP, what PCSX2 on Windows listens on |
|
|
83
|
+
| `PineClient()` | the Unix socket, or TCP on Windows |
|
|
84
|
+
|
|
85
|
+
Connections are kept open between calls by default; pass `persistent=False` to open one per request. One client can be shared by threads: requests are serialised.
|
|
86
|
+
|
|
87
|
+
## Testing your own code
|
|
88
|
+
|
|
89
|
+
`uppercut_pcsx2_pine.fake_server.FakePineServer` is a stand-in server for tests. It runs in your process on TCP or a Unix socket, follows PCSX2's rules (a bad command fails the whole message, memory commands fail without a game, the size limits are the real ones), keeps memory in a `bytearray` and records the requests it received. No emulator, BIOS or game is needed.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from uppercut_pcsx2_pine import PineClient
|
|
93
|
+
from uppercut_pcsx2_pine.fake_server import FakePineServer
|
|
94
|
+
|
|
95
|
+
with FakePineServer(bytearray(0x1000), base=0x100000) as server:
|
|
96
|
+
with PineClient.tcp(port=server.start_tcp()) as pine:
|
|
97
|
+
pine.write32(0x100000, 0xDEADBEEF)
|
|
98
|
+
assert pine.read8(0x100003) == 0xDE
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Notes
|
|
102
|
+
|
|
103
|
+
- The PINE protocol belongs to PCSX2 (GPL-3.0-or-later). This package is an independent client written from the wire format and shares no PCSX2 code.
|
|
104
|
+
- Memory reads and writes go through PCSX2's own memory mapping, so addresses are the guest's virtual addresses.
|
|
105
|
+
- PCSX2 does not report a failed save or load over PINE; check the file.
|
|
106
|
+
|
|
107
|
+
## License
|
|
108
|
+
|
|
109
|
+
MIT
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-pcsx2-pine"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A client for PCSX2's PINE socket: read and write PS2 memory, batch reads, title, status, game id, save states, with an optional write allowlist."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
keywords = ["pcsx2", "pine", "ps2", "playstation-2", "emulator", "ipc", "memory"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Games/Entertainment",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Source = "https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-pcsx2-pine"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/uppercut_pcsx2_pine"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.sdist]
|
|
35
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""A client for PCSX2's PINE socket: read and write PlayStation 2 memory, batch reads, ask for the title, status,
|
|
2
|
+
game id and version, and save and load states. Standard library only."""
|
|
3
|
+
|
|
4
|
+
from .client import RANGE_LIMIT, PineBatch, PineClient, WriteAllowlist
|
|
5
|
+
from .errors import (
|
|
6
|
+
PineCommandFailed,
|
|
7
|
+
PineConnectionError,
|
|
8
|
+
PineError,
|
|
9
|
+
PineProtocolError,
|
|
10
|
+
PineTimeoutError,
|
|
11
|
+
PineWriteDenied,
|
|
12
|
+
)
|
|
13
|
+
from .protocol import DEFAULT_SLOT, MAX_REPLY_SIZE, MAX_REQUEST_SIZE, PineStatus, signed
|
|
14
|
+
from .transport import TcpTransport, Transport, UnixTransport, default_socket_path
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DEFAULT_SLOT",
|
|
18
|
+
"MAX_REPLY_SIZE",
|
|
19
|
+
"MAX_REQUEST_SIZE",
|
|
20
|
+
"RANGE_LIMIT",
|
|
21
|
+
"PineBatch",
|
|
22
|
+
"PineClient",
|
|
23
|
+
"PineCommandFailed",
|
|
24
|
+
"PineConnectionError",
|
|
25
|
+
"PineError",
|
|
26
|
+
"PineProtocolError",
|
|
27
|
+
"PineStatus",
|
|
28
|
+
"PineTimeoutError",
|
|
29
|
+
"PineWriteDenied",
|
|
30
|
+
"TcpTransport",
|
|
31
|
+
"Transport",
|
|
32
|
+
"UnixTransport",
|
|
33
|
+
"WriteAllowlist",
|
|
34
|
+
"default_socket_path",
|
|
35
|
+
"signed",
|
|
36
|
+
]
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""The PINE client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Iterable, Optional, Sequence, Tuple, Union
|
|
7
|
+
|
|
8
|
+
from . import protocol as p
|
|
9
|
+
from .errors import PineProtocolError, PineWriteDenied
|
|
10
|
+
from .transport import TcpTransport, Transport, UnixTransport
|
|
11
|
+
|
|
12
|
+
Range = Tuple[int, int]
|
|
13
|
+
RANGE_LIMIT = 32_768
|
|
14
|
+
"""How many bytes of memory ``read_bytes`` and ``write_bytes`` move per message."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WriteAllowlist:
|
|
18
|
+
"""Guest address ranges a client may write to. Each range is ``(start, end)``, ``end`` exclusive."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, ranges: Iterable[Range] = ()) -> None:
|
|
21
|
+
self._ranges: list[Range] = []
|
|
22
|
+
for start, end in ranges:
|
|
23
|
+
self.add(start, end)
|
|
24
|
+
|
|
25
|
+
def add(self, start: int, end: int) -> None:
|
|
26
|
+
p.check_address(start)
|
|
27
|
+
if not start < end <= 0x1_0000_0000:
|
|
28
|
+
raise ValueError(f"allowlist range {start:#x} to {end:#x} is empty or outside the 32-bit address space")
|
|
29
|
+
self._ranges.append((start, end))
|
|
30
|
+
|
|
31
|
+
def allows(self, address: int, size: int = 1) -> bool:
|
|
32
|
+
"""True when ``size`` bytes starting at ``address`` lie inside one range."""
|
|
33
|
+
return any(start <= address and address + size <= end for start, end in self._ranges)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def ranges(self) -> list[Range]:
|
|
37
|
+
return list(self._ranges)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PineBatch:
|
|
41
|
+
"""Commands sent as one PINE message. Reads answer in order; ``execute()`` returns their values.
|
|
42
|
+
|
|
43
|
+
A batch is one message, so the emulator sees it between two frames of its own choosing but not necessarily
|
|
44
|
+
between two game frames. It raises ``ValueError`` if it cannot fit in one request or reply.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(self, client: "PineClient") -> None:
|
|
48
|
+
self._client = client
|
|
49
|
+
self._commands: list[bytes] = []
|
|
50
|
+
self._read_bits: list[int] = []
|
|
51
|
+
self._size = 4
|
|
52
|
+
self._reply_size = 5
|
|
53
|
+
|
|
54
|
+
def _add(self, command: bytes, reply_bits: Optional[int]) -> "PineBatch":
|
|
55
|
+
if self._size + len(command) > p.MAX_REQUEST_SIZE:
|
|
56
|
+
raise ValueError("this batch no longer fits in one PINE request")
|
|
57
|
+
if reply_bits is not None and self._reply_size + reply_bits // 8 > p.MAX_REPLY_SIZE:
|
|
58
|
+
raise ValueError("this batch's reply no longer fits in one PINE reply")
|
|
59
|
+
self._commands.append(command)
|
|
60
|
+
self._size += len(command)
|
|
61
|
+
if reply_bits is not None:
|
|
62
|
+
self._read_bits.append(reply_bits)
|
|
63
|
+
self._reply_size += reply_bits // 8
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
def read(self, address: int, bits: int) -> "PineBatch":
|
|
67
|
+
return self._add(p.read_command(address, bits), bits)
|
|
68
|
+
|
|
69
|
+
def read8(self, address: int) -> "PineBatch":
|
|
70
|
+
return self.read(address, 8)
|
|
71
|
+
|
|
72
|
+
def read16(self, address: int) -> "PineBatch":
|
|
73
|
+
return self.read(address, 16)
|
|
74
|
+
|
|
75
|
+
def read32(self, address: int) -> "PineBatch":
|
|
76
|
+
return self.read(address, 32)
|
|
77
|
+
|
|
78
|
+
def read64(self, address: int) -> "PineBatch":
|
|
79
|
+
return self.read(address, 64)
|
|
80
|
+
|
|
81
|
+
def write(self, address: int, value: int, bits: int) -> "PineBatch":
|
|
82
|
+
command = p.write_command(address, value, bits)
|
|
83
|
+
self._client._check_write(address, bits // 8)
|
|
84
|
+
return self._add(command, None)
|
|
85
|
+
|
|
86
|
+
def write8(self, address: int, value: int) -> "PineBatch":
|
|
87
|
+
return self.write(address, value, 8)
|
|
88
|
+
|
|
89
|
+
def write16(self, address: int, value: int) -> "PineBatch":
|
|
90
|
+
return self.write(address, value, 16)
|
|
91
|
+
|
|
92
|
+
def write32(self, address: int, value: int) -> "PineBatch":
|
|
93
|
+
return self.write(address, value, 32)
|
|
94
|
+
|
|
95
|
+
def write64(self, address: int, value: int) -> "PineBatch":
|
|
96
|
+
return self.write(address, value, 64)
|
|
97
|
+
|
|
98
|
+
def __len__(self) -> int:
|
|
99
|
+
return len(self._commands)
|
|
100
|
+
|
|
101
|
+
def execute(self) -> list[int]:
|
|
102
|
+
"""Send the batch and return the values of its reads, in order. An empty batch sends nothing."""
|
|
103
|
+
if not self._commands:
|
|
104
|
+
return []
|
|
105
|
+
answer = self._client._send(b"".join(self._commands))
|
|
106
|
+
return p.split_values(answer, self._read_bits)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class PineClient:
|
|
110
|
+
"""Talks to a running PCSX2 over PINE.
|
|
111
|
+
|
|
112
|
+
``write_allowlist`` is ``None`` (the default) for unrestricted writes, or a ``WriteAllowlist`` or a list of
|
|
113
|
+
``(start, end)`` ranges (``end`` exclusive). An empty list makes the client read-only. A write outside the
|
|
114
|
+
allowlist raises ``PineWriteDenied`` before anything is sent.
|
|
115
|
+
|
|
116
|
+
Reads return unsigned integers; use ``signed(value, bits)`` for signed fields.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
transport: Optional[Transport] = None,
|
|
122
|
+
*,
|
|
123
|
+
write_allowlist: Union[WriteAllowlist, Iterable[Range], None] = None,
|
|
124
|
+
) -> None:
|
|
125
|
+
self.transport: Transport = transport if transport is not None else _default_transport()
|
|
126
|
+
if write_allowlist is None or isinstance(write_allowlist, WriteAllowlist):
|
|
127
|
+
self.write_allowlist: Optional[WriteAllowlist] = write_allowlist
|
|
128
|
+
else:
|
|
129
|
+
self.write_allowlist = WriteAllowlist(write_allowlist)
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def unix(
|
|
133
|
+
cls,
|
|
134
|
+
path: Union[str, "os.PathLike[str]", None] = None,
|
|
135
|
+
*,
|
|
136
|
+
slot: int = p.DEFAULT_SLOT,
|
|
137
|
+
timeout: float = 2.0,
|
|
138
|
+
persistent: bool = True,
|
|
139
|
+
write_allowlist: Union[WriteAllowlist, Iterable[Range], None] = None,
|
|
140
|
+
) -> "PineClient":
|
|
141
|
+
return cls(UnixTransport(path, slot=slot, timeout=timeout, persistent=persistent), write_allowlist=write_allowlist)
|
|
142
|
+
|
|
143
|
+
@classmethod
|
|
144
|
+
def tcp(
|
|
145
|
+
cls,
|
|
146
|
+
host: str = "127.0.0.1",
|
|
147
|
+
port: int = p.DEFAULT_SLOT,
|
|
148
|
+
*,
|
|
149
|
+
timeout: float = 2.0,
|
|
150
|
+
persistent: bool = True,
|
|
151
|
+
write_allowlist: Union[WriteAllowlist, Iterable[Range], None] = None,
|
|
152
|
+
) -> "PineClient":
|
|
153
|
+
return cls(TcpTransport(host, port, timeout=timeout, persistent=persistent), write_allowlist=write_allowlist)
|
|
154
|
+
|
|
155
|
+
def close(self) -> None:
|
|
156
|
+
self.transport.close()
|
|
157
|
+
|
|
158
|
+
def __enter__(self) -> "PineClient":
|
|
159
|
+
return self
|
|
160
|
+
|
|
161
|
+
def __exit__(self, *_exc: object) -> None:
|
|
162
|
+
self.close()
|
|
163
|
+
|
|
164
|
+
def _send(self, commands: bytes) -> bytes:
|
|
165
|
+
return p.parse_reply(self.transport.request(p.frame_request(commands)))
|
|
166
|
+
|
|
167
|
+
def _check_write(self, address: int, size: int) -> None:
|
|
168
|
+
if self.write_allowlist is not None and not self.write_allowlist.allows(address, size):
|
|
169
|
+
raise PineWriteDenied(f"write of {size} byte(s) at {address:#x} is outside the write allowlist")
|
|
170
|
+
|
|
171
|
+
# Memory.
|
|
172
|
+
|
|
173
|
+
def batch(self) -> PineBatch:
|
|
174
|
+
return PineBatch(self)
|
|
175
|
+
|
|
176
|
+
def read(self, address: int, bits: int) -> int:
|
|
177
|
+
return self.batch().read(address, bits).execute()[0]
|
|
178
|
+
|
|
179
|
+
def read8(self, address: int) -> int:
|
|
180
|
+
return self.read(address, 8)
|
|
181
|
+
|
|
182
|
+
def read16(self, address: int) -> int:
|
|
183
|
+
return self.read(address, 16)
|
|
184
|
+
|
|
185
|
+
def read32(self, address: int) -> int:
|
|
186
|
+
return self.read(address, 32)
|
|
187
|
+
|
|
188
|
+
def read64(self, address: int) -> int:
|
|
189
|
+
return self.read(address, 64)
|
|
190
|
+
|
|
191
|
+
def read_many(self, requests: Sequence[Tuple[int, int]], *, max_per_message: int = 4096) -> list[int]:
|
|
192
|
+
"""Read several ``(address, bits)`` pairs. Each message holds at most ``max_per_message`` reads, so a long
|
|
193
|
+
list becomes several messages and is not one atomic snapshot."""
|
|
194
|
+
values: list[int] = []
|
|
195
|
+
for start in range(0, len(requests), max_per_message):
|
|
196
|
+
batch = self.batch()
|
|
197
|
+
for address, bits in requests[start : start + max_per_message]:
|
|
198
|
+
batch.read(address, bits)
|
|
199
|
+
values.extend(batch.execute())
|
|
200
|
+
return values
|
|
201
|
+
|
|
202
|
+
def write(self, address: int, value: int, bits: int) -> None:
|
|
203
|
+
self.batch().write(address, value, bits).execute()
|
|
204
|
+
|
|
205
|
+
def write8(self, address: int, value: int) -> None:
|
|
206
|
+
self.write(address, value, 8)
|
|
207
|
+
|
|
208
|
+
def write16(self, address: int, value: int) -> None:
|
|
209
|
+
self.write(address, value, 16)
|
|
210
|
+
|
|
211
|
+
def write32(self, address: int, value: int) -> None:
|
|
212
|
+
self.write(address, value, 32)
|
|
213
|
+
|
|
214
|
+
def write64(self, address: int, value: int) -> None:
|
|
215
|
+
self.write(address, value, 64)
|
|
216
|
+
|
|
217
|
+
def read_bytes(self, address: int, length: int, *, chunk: int = RANGE_LIMIT) -> bytes:
|
|
218
|
+
"""Read ``length`` bytes: 64-bit reads for the bulk, then 32, 16 and 8-bit reads for the tail, batched into
|
|
219
|
+
messages of at most ``chunk`` bytes. Several messages are not one atomic snapshot."""
|
|
220
|
+
if length < 0:
|
|
221
|
+
raise ValueError("length cannot be negative")
|
|
222
|
+
p.check_address(address, max(length, 1))
|
|
223
|
+
out = bytearray()
|
|
224
|
+
offset = 0
|
|
225
|
+
while offset < length:
|
|
226
|
+
batch, widths, size = self.batch(), [], 0
|
|
227
|
+
while offset + size < length and size < chunk:
|
|
228
|
+
bits = _widest(length - offset - size)
|
|
229
|
+
batch.read(address + offset + size, bits)
|
|
230
|
+
widths.append(bits)
|
|
231
|
+
size += bits // 8
|
|
232
|
+
values = batch.execute()
|
|
233
|
+
for bits, value in zip(widths, values):
|
|
234
|
+
out += value.to_bytes(bits // 8, "little")
|
|
235
|
+
offset += size
|
|
236
|
+
return bytes(out)
|
|
237
|
+
|
|
238
|
+
def write_bytes(self, address: int, data: bytes, *, chunk: int = RANGE_LIMIT) -> None:
|
|
239
|
+
"""Write ``data`` with the widest writes that fit, in messages of at most ``chunk`` bytes. The whole range is
|
|
240
|
+
checked against the allowlist before the first message is sent."""
|
|
241
|
+
data = bytes(data)
|
|
242
|
+
p.check_address(address, max(len(data), 1))
|
|
243
|
+
if data:
|
|
244
|
+
self._check_write(address, len(data))
|
|
245
|
+
offset = 0
|
|
246
|
+
while offset < len(data):
|
|
247
|
+
batch, size = self.batch(), 0
|
|
248
|
+
while offset + size < len(data) and size < chunk:
|
|
249
|
+
bits = _widest(len(data) - offset - size)
|
|
250
|
+
value = int.from_bytes(data[offset + size : offset + size + bits // 8], "little")
|
|
251
|
+
batch.write(address + offset + size, value, bits)
|
|
252
|
+
size += bits // 8
|
|
253
|
+
batch.execute()
|
|
254
|
+
offset += size
|
|
255
|
+
|
|
256
|
+
# Emulator and game.
|
|
257
|
+
|
|
258
|
+
def _string(self, opcode: int) -> str:
|
|
259
|
+
return p.parse_string(self._send(bytes((opcode,))))
|
|
260
|
+
|
|
261
|
+
def version(self) -> str:
|
|
262
|
+
"""The emulator's version, for example ``"PCSX2 v2.x.y"``. Works with no game running."""
|
|
263
|
+
return self._string(p.VERSION)
|
|
264
|
+
|
|
265
|
+
def title(self) -> str:
|
|
266
|
+
return self._string(p.TITLE)
|
|
267
|
+
|
|
268
|
+
def game_id(self) -> str:
|
|
269
|
+
"""The disc serial, for example ``"SLUS-00000"``."""
|
|
270
|
+
return self._string(p.GAME_ID)
|
|
271
|
+
|
|
272
|
+
def uuid(self) -> str:
|
|
273
|
+
"""The disc CRC as eight hex digits (PCSX2 calls this the UUID)."""
|
|
274
|
+
return self._string(p.UUID)
|
|
275
|
+
|
|
276
|
+
def game_version(self) -> str:
|
|
277
|
+
return self._string(p.GAME_VERSION)
|
|
278
|
+
|
|
279
|
+
def status(self) -> p.PineStatus:
|
|
280
|
+
"""Running, paused or shut down. Works with no game running (it then says shut down)."""
|
|
281
|
+
answer = self._send(bytes((p.STATUS,)))
|
|
282
|
+
(value,) = p.split_values(answer, [32])
|
|
283
|
+
try:
|
|
284
|
+
return p.PineStatus(value)
|
|
285
|
+
except ValueError:
|
|
286
|
+
raise PineProtocolError(f"unknown PINE status {value}") from None
|
|
287
|
+
|
|
288
|
+
def identity(self) -> dict[str, str]:
|
|
289
|
+
"""Version, title, game id, uuid, game version and status in one dictionary."""
|
|
290
|
+
return {
|
|
291
|
+
"pcsx2_version": self.version(),
|
|
292
|
+
"title": self.title(),
|
|
293
|
+
"game_id": self.game_id(),
|
|
294
|
+
"uuid": self.uuid(),
|
|
295
|
+
"game_version": self.game_version(),
|
|
296
|
+
"status": self.status().label,
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
def save_state(self, slot: int) -> None:
|
|
300
|
+
"""Ask PCSX2 to save the state to ``slot`` (0 to 255). The reply comes at once; the file is written a moment
|
|
301
|
+
later on the emulation thread, so wait for it to appear."""
|
|
302
|
+
self._send(p.state_command(p.SAVE_STATE, slot))
|
|
303
|
+
|
|
304
|
+
def load_state(self, slot: int) -> None:
|
|
305
|
+
"""Ask PCSX2 to load the state in ``slot``. Like ``save_state``, the load happens after the reply."""
|
|
306
|
+
self._send(p.state_command(p.LOAD_STATE, slot))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _widest(remaining: int) -> int:
|
|
310
|
+
for bits in (64, 32, 16, 8):
|
|
311
|
+
if remaining >= bits // 8:
|
|
312
|
+
return bits
|
|
313
|
+
raise ValueError("nothing left to move")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _default_transport() -> Transport:
|
|
317
|
+
"""The Unix socket where the platform has one, else the TCP port: how PCSX2 itself picks."""
|
|
318
|
+
return TcpTransport() if os.name == "nt" else UnixTransport()
|