Как вызвать эквивалентную команду для трассировки на Mac — в идеале из Python?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как вызвать эквивалентную команду для трассировки на Mac — в идеале из Python?

Сообщение Anonymous »

Автономный воспроизводимый пример
Мне нужно отследить вывод любой команды через Python. Но мне нужно всего лишь перевести следующую команду amd linux в команды mac m1/arm (поэтому Python, скорее всего, не имеет значения):

Код: Выделить всё

strace -e trace=execve -v -s 100000000 -xx -ttt -ff -o output.txt sh -c 'echo hi'
Как мне это сделать?
У меня это не получается:

Код: Выделить всё

 ❯ sudo dtruss -t execve -f sh -c 'echo hi'
dtrace: system integrity protection is on, some features will not be available

dtrace: failed to execute sh: Operation not permitted
Примечание.
  • Я полностью контролирую ввод, поэтому могу выполнять sudo и связанные с ним команды на своем Mac ( в основном это отладка моего кода, поэтому он работает на pycharm)
Сбой Strace из Brew
Не могу установить strace из Brew:

Код: Выделить всё

 ❯ brew install strace
Running `brew update --auto-update`...
strace: Linux is required for this software.
[email protected]: Linux is required for this software.
Error: strace: Unsatisfied requirements failed this build.
Execsnoop также не удалось

Код: Выделить всё

❯ sudo execsnoop sh -c 'echo hi'

dtrace: system integrity protection is on, some features will not be available

dtrace: invalid probe specifier
/*
* Command line arguments
*/
inline int OPT_dump    = 0;
inline int OPT_cmd     = 0;
inline int OPT_time    = 0;
inline int OPT_timestr = 0;
inline int OPT_zone    = 0;
inline int OPT_safe    = 0;
inline int OPT_proj    = 0;
inline int FILTER      = 0;
inline string COMMAND  = ".";

#pragma D option quiet
#pragma D option switchrate=10hz

/*
* Print header
*/
dtrace:::BEGIN
{
/* print optional headers */
OPT_time    ? printf("%-14s ", "TIME") : 1;
OPT_timestr ? printf("%-20s ", "STRTIME") : 1;
OPT_zone    ? printf("%-10s ", "ZONE") : 1;
OPT_proj    ? printf("%5s ", "PROJ") : 1;

/* print main headers */
/* APPLE: Removed "ZONE" header, it has no meaning in darwin */
OPT_dump    ? printf("%s %s %s %s %s %s %s\n",
"TIME", "PROJ", "UID", "PID", "PPID", "COMM", "ARGS") :
printf("%5s %6s %6s %s\n", "UID", "PID", "PPID", "ARGS");
}

/*
* Print exec event
*/
/* SOLARIS: syscall::exec:return, syscall::exece:return */
proc:::exec-success
/(FILTER == 0) || (OPT_cmd == 1 && COMMAND == strstr(COMMAND, execname)) || (OPT_cmd == 1 && execname == strstr(execname, COMMAND))/
{
/* print optional fields */
OPT_time ? printf("%-14d ", timestamp/1000) : 1;
OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
OPT_zone ? printf("%-10s ", zonename) : 1;
OPT_proj ? printf("%5d ", curpsinfo->pr_projid) : 1;

/* print main data */
/* APPLE: Removed the zonename output, it has no meaning in darwin */
OPT_dump ? printf("%d %d %d %d %d %s ", timestamp/1000,
curpsinfo->pr_projid, uid, pid, ppid, execname) :
printf("%5d %6d %6d ", uid, pid, ppid);
OPT_safe ? printf("%S\n", curpsinfo->pr_psargs) :
printf("%s\n", curpsinfo->pr_psargs);
}
: probe description proc:::exec-success does not match any probes. System Integrity Protection is on
Я унаследовал этот код и в нем вызывает strace из Python. В частности, он вызывает:

Код: Выделить всё

def strace_build(executable: str,
regex: str,
workdir: Optional[str],
command: List[str],
strace_logdir=None) -> List[str]:
''' trace calls of executable during access to files that match regex
in workdir while executing the command and  returns the list of pycoq_context
file names

In the simplest case strace runs the specified command until it
exits.  It intercepts and records the system calls which are
called by a process and the signals which are received by a
process.   The name of each system call, its arguments and its
return value are printed on standard error or to the file
specified with the -o option.

https://stackoverflow.com/questions/73724074/how-to-call-an-equivalent-command-to-strace-on-mac-ideally-from-python
'''
print('---- Calling strace_build ----')

def _strace_build(executable, regex, workdir, command, logdir):
logfname = os.path.join(logdir, 'strace.log')
logging.info(f"pycoq: tracing {executable} accesing {regex} while "
f"executing {command} from {workdir} with "
f"curdir {os.getcwd()}")
print(f"pycoq: tracing {executable} accesing {regex} while "
f"executing {command} from {workdir} with "
f"curdir {os.getcwd()}")
with subprocess.Popen(['strace', '-e', 'trace=execve',
'-v', '-ff', '-s', '100000000',
'-xx', '-ttt',
'-o', logfname] + command,
cwd=workdir,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
for line in iter(proc.stdout.readline, ''):
logging.debug(f"strace stdout: {line}")
print(f"strace stdout: {line=}")
logging.info(f"strace stderr: {proc.stderr.read()}"
"waiting strace to finish...")
proc.wait()
logging.info('strace finished')
res: list[str] = parse_strace_logdir(logdir, executable, regex)
print('---- Done with strace_build ----')
return res

if strace_logdir is None:
with tempfile.TemporaryDirectory() as _logdir:
return _strace_build(executable, regex, workdir, command, _logdir)
else:
os.makedirs(strace_logdir, exist_ok=True)
strace_logdir_cur = tempfile.mkdtemp(dir=strace_logdir)
return _strace_build(executable, regex, workdir, command, strace_logdir_cur)
но поскольку он вызывает strace, он работает только в Linux. Я хочу, чтобы он работал на моем Mac — в идеале, если это возможно, максимально питоническим способом. Я считаю, что он отслеживает команду терминала, вызываемую из Python.
Что было бы эквивалентным способом вызова этой команды на Mac, используя те же флаги, чтобы она работала (в идеале точно) то же самое?
Не уверен, имеет ли это значение, но я использую Mac m1.

некоторые результаты когда используется вышеуказанная функция:

Код: Выделить всё

--done with make attempt--
---- Calling strace_build ----
pycoq: tracing /home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc accesing .*\.v$ while executing ['opam', 'reinstall', '--yes', '--switch', 'ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1', '--keep-build-dir', 'debug_proj'] from None with curdir /home/bot
strace stdout: line='\n'
strace stdout: line=' Synchronising pinned packages >\n'
strace stdout: line='[debug_proj.~dev] no changes from file:///home/bot/iit-term-synthesis/coq_projects/debug_proj\n'
strace stdout: line='\n'
strace stdout: line='debug_proj is not installed.  Install it? [Y/n] y\n'
strace stdout: line='Sorry, no solution found: there seems to be a problem with your request.\n'
strace stdout: line='\n'
strace stdout: line='No solution found, exiting\n'
---- Done with strace_build ----
...
---- Calling strace_build ----
pycoq: tracing /home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc accesing .*\.v$ while executing ['make', '-C', '/home/bot/iit-term-synthesis/coq_projects/debug_proj'] from None with curdir /home/bot
strace stdout: line="make: Entering directory '/home/bot/iit-term-synthesis/coq_projects/debug_proj'\n"
strace stdout: line='coq_makefile -f _CoqProject -o CoqMakefile\n'
strace stdout: line='make --no-print-directory -f CoqMakefile \n'
strace stdout: line='COQDEP VFILES\n'
strace stdout: line='COQC debug_0_plus_n_eq_n.v\n'
strace stdout: line='COQC debug1_n_plus_1_greater_than_n.v\n'
strace stdout: line='COQC debug2_n_plus_0_eq_n.v\n'
strace stdout: line="make: Leaving directory '/home/bot/iit-term-synthesis/coq_projects/debug_proj'\n"
---- Done with strace_build ----

Код: Выделить всё

def strace_build_mac_m1(executable: str,
regex: str,
workdir: Optional[str],
command: List[str],
strace_logdir=None) -> List[str]:
''' trace calls of executable during access to files that match regex
in workdir while executing the command and  returns the list of pycoq_context
file names

In the simplest case strace runs the specified command until it
exits.  It intercepts and records the system calls which are
called by a process and the signals which are received by a
process.  The name of each system call, its arguments and its
return value are printed on standard error or to the file
specified with the -o option.

https://stackoverflow.com/questions/73724074/how-to-call-an-equivalent-command-to-strace-on-mac-ideally-from-python

plan:
- get the command we are running
- pip push my pycoq with no name changes so code doesn't break
- pull the rest of the repos needed, I don't think anything else since lf is here
- harcode test
- actually, look at commands...we need to provide for reproducibility a way to install opam and all this stuff
without docker but in the mac since we are trying to do a mac install.  Argh...

COMMANDS:
pycoq: tracing /home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc accesing .*\.v$ while executing ['opam', 'reinstall', '--yes', '--switch', 'ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1', '--keep-build-dir', 'lf'] from None with curdir /home/bot
executable='/home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc'
regex='.*\\.v$'
workdir=None
command=['opam', 'reinstall', '--yes', '--switch', 'ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1', '--keep-build-dir', 'lf']
curdir: os.getcwd()='/home/bot'
'''
print('---- Calling strace_build_mac_m1 ----')

def _strace_build(executable, regex, workdir, command, logdir):
logfname = os.path.join(logdir, 'strace.log')
logging.info(f"pycoq: tracing {executable} accesing {regex} while "
f"executing {command} from {workdir} with "
f"curdir {os.getcwd()}")
print(f"pycoq: tracing {executable} accesing {regex} while "
f"executing {command} from {workdir} with "
f"curdir {os.getcwd()}")
print(f'{executable=}')
print(f'{regex=}')
print(f'{workdir=}')
print(f'{command=}')
print(f'curdir: {os.getcwd()=}')
with subprocess.Popen(['dtruss', '-e', 'trace=execve',
'-v', '-ff', '-s', '100000000',
'-xx', '-ttt',
'-o', logfname] + command,
cwd=workdir,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) as proc:
for line in iter(proc.stdout.readline, ''):
logging.debug(f"strace stdout: {line}")
print(f"strace stdout: {line=}")
logging.info(f"strace stderr: {proc.stderr.read()}"
"waiting strace to finish...")
proc.wait()
logging.info('strace finished')
res: list[str] = parse_strace_logdir(logdir, executable, regex)
print('---- Done with strace_build_mac_m1 ----')
return res

if strace_logdir is None:
with tempfile.TemporaryDirectory() as _logdir:
return _strace_build(executable, regex, workdir, command, _logdir)
else:
os.makedirs(strace_logdir, exist_ok=True)
strace_logdir_cur = tempfile.mkdtemp(dir=strace_logdir)
return _strace_build(executable, regex, workdir, command, strace_logdir_cur)

# -

def code_for_mac_m1():
coq_package = 'lf'
coq_package_pin = '~/pycoq/pycoq/test/lf'
coq_package_pin = os.path.expanduser(coq_package_pin)

print(f'coq_package: {coq_package=}')
print(f'coq_package_pin: {coq_package_pin=}')

### pycoq: tracing /home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc accesing .*\.v$ while executing ['opam', 'reinstall', '--yes', '--switch', 'ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1', '--keep-build-dir', 'lf'] from None with curdir /home/bot
# executable='/home/bot/.opam/ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1/bin/coqc'
# regex='.*\\.v$'
# workdir=None
# command=['opam', 'reinstall', '--yes', '--switch', 'ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1', '--keep-build-dir', 'lf']
# curdir: os.getcwd()='/home/bot'

# - get the filename in split
# path2filenames: list[str] = pycoq.opam.opam_strace_build(coq_proj, coq_proj_pin)
path2filenames_raw: list[str] = strace_build_mac_m1()
path2filenames_raw.sort()
print(f'\n====----> Populate coq pkg/proj data with files: {path2filenames_raw=}')

if __name__ == '__main__':
code_for_mac_m1()
print('Done!\n\a')
почему это не соответствует рекомендациям SO? Я не прошу ясно запрос на программное обеспечение. Судя по обсуждению, работать на Python гораздо сложнее + иметь необходимую настройку Mac + инструмент с эквивалентными флагами для трассировки для Mac.


Google для замены (аналога) функциональности strace для Mac OS и изменения парсера, который анализирует выходные данные strace для этого «mac-strace».
Функциональность strace используется для проверки системы сборки Coq на предмет запишите все параметры, аргументы и среду для coqc, в которой каждый отдельный файл .v обрабатывается coqc в процессе сборки. Система сборки Coq сложна, и я не анализировал, а решил просто наблюдать с помощью strace того, что делает настоящий Coq, а strace просто записывает все параметры и аргументы (например, -R и т. д.) того, что делает настоящий Coq, чтобы pycoq мог вызов coqc с точно такими же параметрами и аргументами


Использование модифицированного файла dtruss.sh
Ответ Филиппа не сработал:

Код: Выделить всё

(meta_learning) brandomiranda~ ❯ cat dtruss.sh
#!/bin/bash

file=$(type -P $1); shift
c=/tmp/$(basename "$file")
cp "$file" "$c"
codesign --remove-signature "$c"
sudo dtruss "$c" "$@"
(meta_learning) brandomiranda~ ❯ chmod +x dtruss.sh
(meta_learning) brandomiranda~ ❯ ./dtruss.sh echo hi

dtrace: system integrity protection is on, some features will not be available

dtrace: failed to execute /tmp/echo: Could not create symbolicator for task
Чтобы исправить ситуацию, когда sudo не запрашивает пароль, см.:

Код: Выделить всё

# root and users in group wheel can run anything on any machine as any user
root        ALL = (ALL) ALL
%admin      ALL = (ALL) NOPASSWD: ALL
#%admin     ALL = (ALL) ALL
Связано:
  • Можно ли запустить dtruss, не делая лишних действий предложено здесь?
  • Кросс, unix reddit.
  • Кросс, разработчики Apple Reddit.


Подробнее здесь: https://stackoverflow.com/questions/737 ... rom-python
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»