Skip to content

Commit

Permalink
Give an actual name to MemoryIO on FreeBSD
Browse files Browse the repository at this point in the history
  • Loading branch information
quantum5 committed Jan 30, 2022
1 parent 41c88f3 commit e30f7b1
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion dmoj/cptbox/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,24 @@
import io
import mmap
import os
from tempfile import NamedTemporaryFile
from typing import Optional

from dmoj.cptbox._cptbox import memory_fd_create, memory_fd_seal
from dmoj.cptbox.tracer import FREEBSD


class MemoryIO(io.FileIO):
_name: Optional[str]

def __init__(self, prefill: Optional[bytes] = None, seal=False) -> None:
super().__init__(memory_fd_create(), 'r+')
if FREEBSD:
with NamedTemporaryFile(delete=False) as f:
self._name = f.name
super().__init__(os.dup(f.fileno()), 'r+')
else:
super().__init__(memory_fd_create(), 'r+')

if prefill:
self.write(prefill)
if seal:
Expand All @@ -32,7 +42,14 @@ def seal(self) -> None:
finally:
os.close(new_fd)

def close(self) -> None:
super().close()
if self._name:
os.unlink(self._name)

def to_path(self) -> str:
if self._name:
return self._name
return f'/proc/{os.getpid()}/fd/{self.fileno()}'

def to_bytes(self) -> bytes:
Expand Down

0 comments on commit e30f7b1

Please sign in to comment.