Initialize parser from shared memory (by name or address) Usage: init_parser(shm_name, size) or init_parser(shm_capsule, size)
| 230 | // Initialize parser from shared memory (by name or address) |
| 231 | // Usage: init_parser(shm_name, size) or init_parser(shm_capsule, size) |
| 232 | static PyObject* InitParser(PyObject *self, PyObject *args) { |
| 233 | PyObject *shm_arg = NULL; |
| 234 | unsigned long long shm_size = 0; |
| 235 | |
| 236 | if (!PyArg_ParseTuple(args, "OK", &shm_arg, &shm_size)) { |
| 237 | return NULL; |
| 238 | } |
| 239 | |
| 240 | // Clean up any previous parser |
| 241 | if (__z3_parser != nullptr) { |
| 242 | delete __z3_parser; |
| 243 | __z3_parser = nullptr; |
| 244 | } |
| 245 | if (__attached_shm != nullptr) { |
| 246 | munmap(__attached_shm, __attached_shm_size); |
| 247 | __attached_shm = nullptr; |
| 248 | __attached_shm_size = 0; |
| 249 | } |
| 250 | |
| 251 | void *shm_base = nullptr; |
| 252 | |
| 253 | if (PyUnicode_Check(shm_arg)) { |
| 254 | // shm_arg is a string (shared memory name) |
| 255 | const char *shm_name = PyUnicode_AsUTF8(shm_arg); |
| 256 | if (shm_name == NULL) { |
| 257 | return NULL; |
| 258 | } |
| 259 | |
| 260 | int shm_fd = shm_open(shm_name, O_RDWR, S_IRUSR | S_IWUSR); |
| 261 | if (shm_fd == -1) { |
| 262 | fprintf(stderr, "Failed to open shm '%s': %s\n", shm_name, strerror(errno)); |
| 263 | return PyErr_SetFromErrno(PyExc_OSError); |
| 264 | } |
| 265 | |
| 266 | shm_base = mmap(0, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); |
| 267 | close(shm_fd); |
| 268 | |
| 269 | if (shm_base == MAP_FAILED) { |
| 270 | fprintf(stderr, "Failed to mmap shm: %s\n", strerror(errno)); |
| 271 | return PyErr_SetFromErrno(PyExc_OSError); |
| 272 | } |
| 273 | |
| 274 | __attached_shm = shm_base; |
| 275 | __attached_shm_size = shm_size; |
| 276 | } else if (PyCapsule_CheckExact(shm_arg)) { |
| 277 | // shm_arg is a capsule (already mapped address) |
| 278 | shm_base = PyCapsule_GetPointer(shm_arg, "dfsan_label_info"); |
| 279 | if (shm_base == NULL) { |
| 280 | return NULL; |
| 281 | } |
| 282 | // Don't track for munmap - caller owns this memory |
| 283 | } else if (PyLong_Check(shm_arg)) { |
| 284 | // shm_arg is an integer address |
| 285 | shm_base = (void *)PyLong_AsUnsignedLongLong(shm_arg); |
| 286 | if (PyErr_Occurred()) { |
| 287 | return NULL; |
| 288 | } |
| 289 | // Don't track for munmap - caller owns this memory |