This repository was archived by the owner on Jul 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathutils.py
More file actions
327 lines (272 loc) · 10.9 KB
/
Copy pathutils.py
File metadata and controls
327 lines (272 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# The MIT License
#
# Copyright (c) OpenAI (https://openai.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import contextlib
import faulthandler
import io
import os
import platform
import signal
import tempfile
import subprocess
import multiprocessing
import time
from typing import Optional
TIMEOUT_LIMIT=240.0
@contextlib.contextmanager
def swallow_subprocess_output():
"""Context manager to swallow stdout and stderr for subprocesses."""
original_popen = subprocess.Popen
original_run = subprocess.run
def _popen_patch(*args, **kwargs):
if 'capture_output' in kwargs and kwargs['capture_output']:
# Avoid setting stdout or stderr if capture_output is True
kwargs.pop('stdout', None)
kwargs.pop('stderr', None)
else:
kwargs.setdefault('stdout', subprocess.PIPE)
kwargs.setdefault('stderr', subprocess.PIPE)
return original_popen(*args, **kwargs)
def _run_patch(*args, **kwargs):
if 'capture_output' in kwargs and kwargs['capture_output']:
# Avoid setting stdout or stderr if capture_output is True
kwargs.pop('stdout', None)
kwargs.pop('stderr', None)
else:
kwargs.setdefault('stdout', subprocess.PIPE)
kwargs.setdefault('stderr', subprocess.PIPE)
return original_run(*args, **kwargs)
subprocess.Popen = _popen_patch
subprocess.run = _run_patch
try:
yield
finally:
subprocess.Popen = original_popen
subprocess.run = original_run
@contextlib.contextmanager
def swallow_io():
stream = WriteOnlyStringIO()
with contextlib.redirect_stdout(stream):
with contextlib.redirect_stderr(stream):
with redirect_stdin(stream):
with swallow_subprocess_output():
yield
@contextlib.contextmanager
def time_limit(seconds: float):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.setitimer(signal.ITIMER_REAL, seconds)
signal.signal(signal.SIGALRM, signal_handler)
try:
yield
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
@contextlib.contextmanager
def create_tempdir():
with tempfile.TemporaryDirectory() as dirname:
with chdir(dirname):
yield dirname
@contextlib.contextmanager
def chdir(root):
if root == ".":
yield
return
cwd = os.getcwd()
os.chdir(root)
try:
yield
except BaseException as exc:
raise exc
finally:
os.chdir(cwd)
@contextlib.contextmanager
def safe_environment():
# Save original functions
original_kill = os.kill
original_killpg = os.killpg
original_system = os.system
original_subprocess_call = subprocess.call
original_subprocess_check_output = subprocess.check_output
original_subprocess_run = subprocess.run
original_subprocess_popen = subprocess.Popen
original_os_popen = os.popen
original_os_execv = os.execv
original_os_execvp = os.execvp
original_os_execvpe = os.execvpe
current_pid = os.getpid()
current_pgid = os.getpgid(current_pid)
manager = multiprocessing.Manager()
child_pids = manager.list()
def safe_kill(pid, sig):
try:
pgid = os.getpgid(pid)
if pid == current_pid or pid in child_pids:
original_kill(pid, sig)
else:
print(f"Prevented attempt to kill PID {pid} with signal {sig}")
except ProcessLookupError:
pass
def safe_killpg(pgid, sig):
if pgid == current_pgid or pgid in {os.getpgid(pid) for pid in child_pids}:
original_killpg(pgid, sig)
else:
print(f"Prevented attempt to kill PGID {pgid} with signal {sig}")
def safe_system(command):
print(f"Intercepted system command: {command}")
if 'kill' in command or 'killall' in command:
return 0 # Simulate successful execution without doing anything
return original_system(command)
def safe_subprocess_call(command, *args, **kwargs):
print(f"Intercepted subprocess call: {command}")
if 'kill' in command or 'killall' in command:
return 0 # Simulate successful execution without doing anything
return original_subprocess_call(command, *args, **kwargs)
def safe_subprocess_check_output(command, *args, **kwargs):
print(f"Intercepted command: {command}")
if 'ps' in command:
return b"" # Simulate no processes found
return original_subprocess_check_output(command, *args, **kwargs)
def safe_subprocess_run(*args, **kwargs):
print(f"Intercepted subprocess run command: {args}")
if 'kill' in args[0] or 'killall' in args[0]:
return subprocess.CompletedProcess(args, 0, b'', b'') # Simulate successful execution
return original_subprocess_run(*args, **kwargs)
class SafePopen(subprocess.Popen):
def __init__(self, *args, **kwargs):
print(f"Intercepted Popen command: {args}")
kwargs['preexec_fn'] = os.setsid # Start the process in a new session
super().__init__(*args, **kwargs)
child_pids.append(self.pid)
def communicate(self, *args, **kwargs):
try:
return super().communicate(*args, **kwargs)
except subprocess.TimeoutExpired:
print("Timeout expired, intercepted and returning None")
return None, None
def kill(self):
print(f"Intercepted kill call for PID {self.pid}")
safe_kill(self.pid, signal.SIGTERM)
def terminate(self):
print(f"Intercepted terminate call for PID {self.pid}")
safe_kill(self.pid, signal.SIGTERM)
def safe_os_popen(command):
print(f"Intercepted os.popen command: {command}")
if 'kill' in command or 'killall' in command:
return os.popen('echo Intercepted')
return original_os_popen(command)
def safe_exec(*args, **kwargs):
print(f"Intercepted exec command: {args}")
# Override the risky functions with the safe versions
os.kill = safe_kill
os.killpg = safe_killpg
os.system = safe_system
subprocess.call = safe_subprocess_call
subprocess.check_output = safe_subprocess_check_output
subprocess.run = safe_subprocess_run
subprocess.Popen = SafePopen
os.popen = safe_os_popen
os.execv = safe_exec
os.execvp = safe_exec
os.execvpe = safe_exec
try:
yield
finally:
for pid in child_pids:
try:
os.kill(pid, signal.SIGTERM)
for _ in range(10):
time.sleep(0.1)
try:
os.kill(pid, 0)
except ProcessLookupError:
break
else:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
except Exception as e:
print(f"Error handling process {pid}: {e}")
os.kill = original_kill
os.killpg = original_killpg
os.system = original_system
subprocess.call = original_subprocess_call
subprocess.check_output = original_subprocess_check_output
subprocess.run = original_subprocess_run
subprocess.Popen = original_subprocess_popen
os.popen = original_os_popen
os.execv = original_os_execv
os.execvp = original_os_execvp
os.execvpe = original_os_execvpe
class TimeoutException(Exception):
pass
class WriteOnlyStringIO(io.StringIO):
"""StringIO that throws an exception when it's read from"""
def read(self, *args, **kwargs):
raise IOError
def readline(self, *args, **kwargs):
raise IOError
def readlines(self, *args, **kwargs):
raise IOError
def readable(self, *args, **kwargs):
"""Returns True if the IO object can be read."""
return False
class redirect_stdin(contextlib._RedirectStream): # type: ignore
_stream = "stdin"
def reliability_guard(max_as_limit, max_data_limit, max_stack_limit):
"""
This disables various destructive functions and prevents the generated code
from interfering with the test (e.g. fork bomb, killing other processes,
removing filesystem files, etc.)
WARNING
This function is NOT a security sandbox. Untrusted code, including, model-
generated code, should not be blindly executed outside of one. See the
Codex paper for more information about OpenAI's code sandbox, and proceed
with caution.
"""
import os
import time
from datetime import datetime
os.environ['TZ'] = 'UTC'
time.tzset()
os.environ["OMP_NUM_THREADS"] = "1"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3"
os.environ['TF_ENABLE_ONEDNN_OPTS'] = "0"
if max_as_limit and max_data_limit and max_stack_limit:
import resource
max_as_limit = max_as_limit * 1024 * 1024
max_data_limit = max_data_limit * 1024 * 1024
max_stack_limit = max_stack_limit * 1024 * 1024
resource.setrlimit(
resource.RLIMIT_AS, (max_as_limit, max_as_limit)
)
resource.setrlimit(
resource.RLIMIT_DATA, (max_data_limit, max_data_limit)
)
if not platform.uname().system == "Darwin":
resource.setrlimit(
resource.RLIMIT_STACK, (max_stack_limit, max_stack_limit)
)
faulthandler.disable()
import builtins
builtins.exit = None
builtins.quit = None
import matplotlib.pyplot as plt
plt.close('all')