client: build the tab completion vocabulary at runtime from the command tree

Tab completion used a generated table (pm3line_vocabulary.h, refreshed by
hand via `make commands`) that drifted from the real command tables: new
commands were missing (e.g. `hw bwm*`), removed ones lingered, and the
"offline" flag depended on the platform of whoever regenerated it
(IfPm5() returns true offline on PM5 builds).

Build the vocabulary at startup instead:

- cmdparser: add walkCommandsRecursive(), a tree walk using a fourth
  internal sentinel (XX_internal_command_walk_XX) next to the dump ones.
  It hands each leaf to a visitor as its command_t chain (ancestors +
  leaf). A dispatch counter detects entries shown like a category but
  with their own parser (reveng) and reports them as leaves.
- pm3line_vocabulary: dynamic vocabulary holding the IsAvailable()
  predicates of every command and its ancestor categories, so completion
  applies exactly the rule CmdsHelp() uses, live, for both offline and
  connected devices. Script entries ("script run <relpath>") come from
  the same directories `script list` scans, sorted, including
  subdirectories with the path `script run` needs.
- pm3line: readline and linenoise completers consume the live vocabulary.
  The walk runs with output disabled so category handlers stay silent.
- Drop pm3_help2list.py and the header regeneration from `make commands`.

Behaviour change: entries whose category is hidden by `help` (e.g. `mem`,
`usart` offline) are no longer offered, matching `help`; when connected,
commands the device does not support are no longer offered either.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
MsprgandClaude Fable 5 authored and Philippe Teuwen committed 2026-08-28 14:29:04 +02:00
1 parent b6e9d48a35
commit d852118de5
13 files changed
+386 -1387

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased]
- Changed client tab completion - vocabulary is now built at runtime from the live command tree and uses the same availability rules as `help`, removing the generated `pm3line_vocabulary.h` and `pm3_help2list.py` (@Msprg)
- Fixed standalone modes - the one second button hold trigger was a no-op on all non-PM5 platforms, leaving `hw standalone` over USB as the only entry point (@ShawInnes)
- Added `sim022.bin` - enabled burst mode transfers, which allows us to do TA1=96 in speeds (@iceman1001)
- Fixed `hf felica liteauth` - empty long option names for `-c` and `-k` made argtable read past the string (found by ASAN on `--fulltext`) (@Msprg)
+1 -3
View File
@@ -228,7 +228,7 @@ help:
@echo "+ fpga_compress - Make tools/fpga_compress"
@echo
@echo "+ style - Apply some automated source code formatting rules"
@echo "+ commands - Regenerate commands documentation files and autocompletion data"
@echo "+ commands - Regenerate commands documentation files (doc/commands.md, doc/commands.json)"
@echo "+ check - Run offline tests. Set CHECKARGS to pass arguments to the test script"
@echo "+ .../check - Run offline tests against specific target. See above."
@echo "+ miscchecks - Detect various encoding issues in source code"
@@ -361,8 +361,6 @@ commands: client
@command -v python3 >/dev/null || ( echo "Please install 'python3' package first" ; exit 1 )
# Update commands.json, patch port in case it was run under Windows
[ -x client/proxmark3 ] && client/proxmark3 --fulltext | sed 's#com[0-9]#/dev/ttyACM0#'|python3 client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json
# Update the readline autocomplete autogenerated code
[ -x client/proxmark3 ] && client/proxmark3 --fulltext | python3 client/pyscripts/pm3_help2list.py - - | tr -d '\r' > client/src/pm3line_vocabulary.h
# Detecting weird codepages and tabs.
+1
View File
@@ -516,6 +516,7 @@ set (TARGET_SOURCES
${PM3_ROOT}/client/src/pm3_fit.c
${PM3_ROOT}/client/src/pm3line.c
${PM3_ROOT}/client/src/pm3line_vocabulary.c
${PM3_ROOT}/client/src/scandir.c
${PM3_ROOT}/client/src/scripting.c
${PM3_ROOT}/client/src/ui.c
+1
View File
@@ -912,6 +912,7 @@ SRCS = mifare/aiddesfire.c \
pm3_fit.c \
preferences.c \
pm3line.c \
pm3line_vocabulary.c \
proxmark3.c \
scandir.c \
relay/relay_posix.c \
+1
View File
@@ -435,6 +435,7 @@ set (TARGET_SOURCES
${PM3_ROOT}/client/src/pm3_dsp.c
${PM3_ROOT}/client/src/pm3_fit.c
${PM3_ROOT}/client/src/pm3line.c
${PM3_ROOT}/client/src/pm3line_vocabulary.c
${PM3_ROOT}/client/src/scandir.c
${PM3_ROOT}/client/src/scripting.c
${PM3_ROOT}/client/src/ui.c
-231
View File
@@ -1,231 +0,0 @@
#!/usr/bin/env python3
"""
PM3 Help 2 List
This script takes the full text help output from the PM3 client and converts it to a list to be used for readline autocomplete.
It is based on pm3_help2JSON.py by
Original Authors / Maintainers:
- Samuel Windall
This version
- Iceman
Note:
This script is used as a helper script to generate the pm3line_vocabulary.h file.
It need a working proxmark3 client to extract the help text.
Ie: this script can't be used inside the normal build sequence.
"""
import re
import datetime
import argparse
import logging
from pathlib import Path
import subprocess
##############################################################################
# Script version data: (Please increment when making updates)
APP_NAME = 'PM3Help2List'
VERSION_MAJOR = 1
VERSION_MINOR = 0
##############################################################################
# Main Application Code:
def main():
"""The main function for the script"""
args = build_arg_parser().parse_args()
logging_format = '%(message)s'
if args.debug:
logging.basicConfig(level=logging.DEBUG, format=logging_format)
else:
logging.basicConfig(level=logging.WARN, format=logging_format)
logging.info(f'{get_version()} starting...')
help_text = args.input_file.read()
command_data = parse_all_command_data(help_text)
# Collect all git-tracked scripts
paths = [('*.py', Path(__file__).parent),
('*.lua', Path(__file__).parent.parent / 'luascripts'),
('*.cmd', Path(__file__).parent.parent / 'cmdscripts')]
try:
for pattern, scripts_dir in paths:
result = subprocess.run(['git', 'ls-files', pattern],
cwd=scripts_dir,
capture_output=True,
text=True,
check=True)
for file_path in result.stdout.strip().split('\n'):
if file_path:
file = Path(file_path)
command_data[file.name] = {'command': f'script run {file.name}', 'offline': False}
except subprocess.CalledProcessError:
print("Error, need git")
args.output_file.write("""//-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// readline auto complete utilities
//-----------------------------------------------------------------------------
#ifndef PM3LINE_VOCABULARY_H__
#define PM3LINE_VOCABULARY_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
typedef struct vocabulary_s {
bool offline;
const char *name;
} vocabulary_t;
const static vocabulary_t vocabulary[] = {\n""")
for key, values in command_data.items():
offline = 0
if (values['offline'] == True):
offline = 1
cmd = values['command']
args.output_file.write(' {{ {}, "{}" }},\n'.format(offline, cmd))
args.output_file.write(""" {0, NULL}\n};
#ifdef __cplusplus
}
#endif
#endif
""")
logging.info(f'{get_version()} completed!')
def build_arg_parser():
"""Build the argument parser for reading the program arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('input_file', type=argparse.FileType('r'), help='Source of full text help from the PM3 client.')
parser.add_argument('output_file', type=argparse.FileType('w'), help='Destination for list output.')
parser.add_argument('--version', '-v', action='version', version=get_version(), help='Version data about this app.')
parser.add_argument('--debug', '-d', action='store_true', help='Log debug messages.')
return parser
def build_help_regex():
"""The regex uses to parse the full text output of help data from the pm3 client."""
# Reads the divider followed by the command itself
re_command = r'-{87}\n(?P<command>.+)\n'
# Reads if the command is available offline
re_offline = r'available offline: (?P<offline>yes|no)\n+'
return re.compile(re_command+re_offline, re.MULTILINE);
def parse_all_command_data(help_text):
"""Turns the full text output of help data from the pm3 client into a list of dictionaries"""
command_dicts = {}
# Strip out ANSI escape sequences
help_text = remove_ansi_escape_codes(help_text)
# Find all commands in the full text help output
matches = build_help_regex().finditer(help_text)
for match in matches:
# Turn a match into a dictionary with keys for the extracted fields
command_object = parse_command_data(match)
# Store this command against its name for easy lookup
command_dicts[command_object['command']] = command_object
return command_dicts
def parse_command_data(match):
"""Turns a regex match of a command in the help text and converts it into a dictionary"""
logging.info('Parsing new command...')
# Get and clean the command string
command = remove_extra_whitespace(match.group('command'))
logging.info(f' Command: {command}')
# Get the online status as a boolean. Note: the regex only picks up 'yes' or 'no' so this check is safe.
offline = (match.group('offline') == 'yes')
logging.debug(f' Offline: {offline}')
# Construct the command dictionary
command_data = {
'command': command,
'offline': offline,
}
logging.info('Completed parsing command!')
return command_data
##############################################################################
# Helper Functions:
def get_version():
"""Get the version string for this script"""
return f'{APP_NAME} v{VERSION_MAJOR}.{VERSION_MINOR:02}'
def remove_ansi_escape_codes(text):
"""Remove ANSI escape sequences that may be left in the text."""
re_ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
return re_ansi_escape.sub('', str(text)).lower()
def remove_extra_whitespace(text):
"""Removes extra whitespace that may be in the text."""
# Ensure input is a string
text = str(text)
# Remove whitespace from the start and end of the text
text = text.strip()
# Deduplicate spaces in the string
text = re.sub(r' +', ' ', text)
return text
def text_to_oneliner(text):
"""Converts a multi line string into a single line string and removes extra whitespace"""
# Ensure input is a string
text = str(text)
# Replace newlines with spaces
text = re.sub(r'\n+', ' ', text)
# Remove the extra whitespace
text = remove_extra_whitespace(text)
return text
def text_to_list(text):
"""Converts a multi line string into a list of lines and removes extra whitespace"""
# Ensure input is a string
text = str(text)
# Get all the lines
lines = text.strip().split('\n')
# For each line clean up any extra whitespace
return [remove_extra_whitespace(line) for line in lines]
##############################################################################
# Application entrypoint:
if __name__ == '__main__':
main()
+62 -2
View File
@@ -48,8 +48,6 @@ typedef pthread_mutex_t pthread_spinlock_t;
pthread_mutex_destroy(lock)
#endif
#define MAX_PM3_INPUT_ARGS_LENGTH 4096
bool AlwaysAvailable(void) {
return true;
}
@@ -309,8 +307,24 @@ static int execute_system_command(const char *command) {
}
// Command tree walk state, see walkCommandsRecursive()
static command_visitor_t s_walk_visitor = NULL;
static void *s_walk_ctx = NULL;
static const command_t *s_walk_path[CMD_WALK_MAX_DEPTH];
static size_t s_walk_depth = 0;
static size_t s_walk_dispatches = 0;
int CmdsParse(const command_t Commands[], const char *Cmd) {
// Command tree walk children, see walkCommandsRecursive().
// Handled before the client_exe_delay: the walk enters here once per
// category and must not pay the delay every time.
if (strcmp(Cmd, "XX_internal_command_walk_XX") == 0) {
s_walk_dispatches++;
walkCommandsRecursive(Commands, s_walk_visitor, s_walk_ctx);
return PM3_SUCCESS;
}
if (g_session.client_exe_delay != 0) {
msleep(g_session.client_exe_delay);
}
@@ -512,3 +526,49 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown, bool full_help)
++i;
}
}
void walkCommandsRecursive(const command_t cmds[], command_visitor_t visitor, void *ctx) {
if (cmds == NULL || cmds[0].Name == NULL || visitor == NULL) return;
// Leaf commands first, then categories: same order as dumpCommandsRecursive()
for (int i = 0; cmds[i].Name; i++) {
if (cmds[i].Name[0] == '-' || strlen(cmds[i].Name) == 0) continue;
if (cmds[i].Help[0] == '{') continue;
s_walk_path[s_walk_depth] = &cmds[i];
visitor(s_walk_path, s_walk_depth + 1, ctx);
}
for (int i = 0; cmds[i].Name; i++) {
if (cmds[i].Name[0] == '-' || strlen(cmds[i].Name) == 0) continue;
if (cmds[i].Help[0] != '{') continue;
if (s_walk_depth + 1 >= CMD_WALK_MAX_DEPTH) {
PrintAndLogEx(DEBUG, "command tree too deep, skipping category %s", cmds[i].Name);
continue;
}
command_visitor_t old_visitor = s_walk_visitor;
void *old_ctx = s_walk_ctx;
size_t dispatches = s_walk_dispatches;
s_walk_visitor = visitor;
s_walk_ctx = ctx;
s_walk_path[s_walk_depth++] = &cmds[i];
// This is what causes the recursion, since the category Parse-implementation
// in turn calls CmdsParse() on its own table.
cmds[i].Parse("XX_internal_command_walk_XX");
s_walk_depth--;
s_walk_visitor = old_visitor;
s_walk_ctx = old_ctx;
// A few commands (e.g. "reveng") are shown like a category but are
// plain commands with their own parser. They never reach CmdsParse(),
// so report them as leaves.
if (s_walk_dispatches == dispatches) {
s_walk_path[s_walk_depth] = &cmds[i];
visitor(s_walk_path, s_walk_depth + 1, ctx);
}
}
}
+12
View File
@@ -21,6 +21,8 @@
#include "common.h"
#define MAX_PM3_INPUT_ARGS_LENGTH 4096
typedef struct command_s {
const char *Name;
int (*Parse)(const char *Cmd);
@@ -29,6 +31,14 @@ typedef struct command_s {
} command_t;
// command_t array are expected to be NULL terminated
// Maximum nesting depth of the command tree supported by walkCommandsRecursive()
#define CMD_WALK_MAX_DEPTH 8
// Called by walkCommandsRecursive() for each leaf command.
// path[0..depth-1] are the command_t entries from the top level category
// down to the leaf command itself (path[depth-1]).
typedef void (*command_visitor_t)(const command_t *const path[], size_t depth, void *ctx);
// helpers for command_t IsAvailable
bool AlwaysAvailable(void);
bool IfClientDebugEnabled(void);
@@ -70,5 +80,7 @@ void CmdsLS(const command_t Commands[]);
// Parse a command line
int CmdsParse(const command_t Commands[], const char *Cmd);
void dumpCommandsRecursive(const command_t cmds[], int markdown, bool full_help);
// Walk the command tree, calling visitor for every leaf command
void walkCommandsRecursive(const command_t cmds[], command_visitor_t visitor, void *ctx);
#endif
+29 -18
View File
@@ -35,27 +35,29 @@
#if defined(HAVE_READLINE)
static char *rl_command_generator(const char *text, int state) {
static int index;
static size_t index;
static size_t len;
static size_t count;
static const vocabulary_t *vocabulary;
size_t rlen = strlen(rl_line_buffer);
const char *command;
if (!state) {
index = 0;
len = strlen(text);
vocabulary = pm3line_vocabulary_get(&count);
}
while ((command = vocabulary[index].name)) {
while (index < count) {
// When no pm3 device present
// and the command is not available offline,
// we skip it.
if ((g_session.pm3_present == false) && (vocabulary[index].offline == false)) {
index++;
const vocabulary_t *entry = &vocabulary[index++];
// Skip commands which are not available right now,
// using the same rules as "help"
if (pm3line_vocabulary_is_available(entry) == false) {
continue;
}
index++;
const char *command = entry->name;
if (strncmp(command, rl_line_buffer, rlen) == 0) {
const char *next = command + (rlen - len);
@@ -77,22 +79,23 @@ static char **rl_command_completion(const char *text, int start, int end) {
#elif defined(HAVE_LINENOISE)
static void ln_command_completion(const char *text, linenoiseCompletions *lc) {
int index = 0;
const char *prev_match = "";
size_t prev_match_len = 0;
size_t len = strlen(text);
const char *command;
while ((command = vocabulary[index].name)) {
size_t count = 0;
const vocabulary_t *vocabulary = pm3line_vocabulary_get(&count);
// When no pm3 device present
// and the command is not available offline,
// we skip it.
if ((g_session.pm3_present == false) && (vocabulary[index].offline == false)) {
index++;
for (size_t index = 0; index < count; index++) {
const vocabulary_t *entry = &vocabulary[index];
// Skip commands which are not available right now,
// using the same rules as "help"
if (pm3line_vocabulary_is_available(entry) == false) {
continue;
}
index++;
const char *command = entry->name;
if (strncmp(command, text, len) == 0) {
const char *space = strstr(command + len, " ");
@@ -156,6 +159,10 @@ void pm3line_install_signals(void) {
}
void pm3line_init(void) {
#if defined(HAVE_READLINE) || defined(HAVE_LINENOISE)
// Build the completion vocabulary from the live command tree
pm3line_vocabulary_build();
#endif
#if defined(HAVE_READLINE)
/* initialize history */
using_history();
@@ -203,6 +210,10 @@ void pm3line_free(void *ref) {
free(ref);
}
void pm3line_cleanup(void) {
pm3line_vocabulary_free();
}
void pm3line_update_prompt(const char *prompt) {
#if defined(HAVE_READLINE)
rl_set_prompt(prompt);
+1
View File
@@ -23,6 +23,7 @@ void pm3line_init(void);
void pm3line_install_signals(void);
char *pm3line_read(const char *s);
void pm3line_free(void *ref);
void pm3line_cleanup(void);
void pm3line_update_prompt(const char *prompt);
int pm3line_load_history(const char *path);
void pm3line_add_history(const char *line);
+250
View File
@@ -0,0 +1,250 @@
//-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// Line editor auto complete vocabulary, built at runtime from the live
// command tree so it can never drift from what "help" shows.
//-----------------------------------------------------------------------------
// this define is needed for scandir/alphasort to work
#define _GNU_SOURCE
#include "pm3line_vocabulary.h"
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include "scandir.h"
#include "cmdmain.h" // getTopLevelCommandTable
#include "fileutils.h" // path_is_directory
#include "proxmark3.h" // get_my_executable_directory, get_my_user_directory
#include "ui.h" // PrintAndLogEx
#include "util.h" // str_dup, str_endswith, g_printAndLog
#define VOCAB_INITIAL_CAPACITY 1024
#define VOCAB_MAX_PATH 1024
static vocabulary_t *s_vocab = NULL;
static size_t s_count = 0;
static size_t s_capacity = 0;
static bool s_built = false;
// Append an entry with the given name. Returns NULL if the name is already
// present or on allocation failure.
static vocabulary_t *vocab_add(const char *name) {
for (size_t i = 0; i < s_count; i++) {
if (strcmp(s_vocab[i].name, name) == 0) {
return NULL;
}
}
if (s_count == s_capacity) {
size_t new_capacity = s_capacity ? s_capacity * 2 : VOCAB_INITIAL_CAPACITY;
vocabulary_t *tmp = realloc(s_vocab, new_capacity * sizeof(vocabulary_t));
if (tmp == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory for completion vocabulary");
return NULL;
}
s_vocab = tmp;
s_capacity = new_capacity;
}
vocabulary_t *entry = &s_vocab[s_count];
memset(entry, 0, sizeof(*entry));
entry->name = str_dup(name);
if (entry->name == NULL) {
return NULL;
}
s_count++;
return entry;
}
// Visitor for walkCommandsRecursive(): one call per leaf command.
static void vocab_visit_command(const command_t *const path[], size_t depth, void *ctx) {
(void) ctx;
char name[MAX_PM3_INPUT_ARGS_LENGTH] = {0};
size_t pos = 0;
for (size_t i = 0; i < depth; i++) {
int n = snprintf(name + pos, sizeof(name) - pos, "%s%s", i ? " " : "", path[i]->Name);
if (n < 0 || (size_t)n >= sizeof(name) - pos) {
return;
}
pos += (size_t)n;
}
vocabulary_t *entry = vocab_add(name);
if (entry == NULL) {
return;
}
entry->depth = (uint8_t)depth;
for (size_t i = 0; i < depth; i++) {
entry->is_available[i] = path[i]->IsAvailable;
}
}
// Add "script run <file>" entries for every script with extension ext found
// under dir (recursively), inheriting the availability of "script run" itself.
// rel is the path of dir relative to the script directory ("" or e.g. "examples/"),
// which is what "script run" needs to find a script in a subdirectory.
static void vocab_add_scripts_dir(const char *dir, const char *rel, const char *ext, const vocabulary_t *script_run) {
struct dirent **namelist;
int n = scandir(dir, &namelist, NULL, alphasort);
if (n < 0) {
return;
}
for (int i = 0; i < n; i++) {
const char *fname = namelist[i]->d_name;
if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
free(namelist[i]);
continue;
}
char fullpath[VOCAB_MAX_PATH] = {0};
int len = snprintf(fullpath, sizeof(fullpath), "%s%s", dir, fname);
if (len < 0 || (size_t)len >= sizeof(fullpath) - 1) {
free(namelist[i]);
continue;
}
if (path_is_directory(fullpath)) {
fullpath[len] = PATHSEP[0];
fullpath[len + 1] = '\0';
char subrel[VOCAB_MAX_PATH] = {0};
len = snprintf(subrel, sizeof(subrel), "%s%s%s", rel, fname, PATHSEP);
if (len > 0 && (size_t)len < sizeof(subrel)) {
vocab_add_scripts_dir(fullpath, subrel, ext, script_run);
}
free(namelist[i]);
continue;
}
if (str_endswith(fname, ext)) {
char name[MAX_PM3_INPUT_ARGS_LENGTH] = {0};
len = snprintf(name, sizeof(name), "%s %s%s", script_run->name, rel, fname);
if (len > 0 && (size_t)len < sizeof(name)) {
vocabulary_t *entry = vocab_add(name);
if (entry != NULL) {
entry->depth = script_run->depth;
memcpy(entry->is_available, script_run->is_available, sizeof(entry->is_available));
}
}
}
free(namelist[i]);
}
free(namelist);
}
// Same search order as searchAndList() / "script list":
// dev tree next to the executable, user directory, installed share directory.
static void vocab_add_scripts(const char *pm3dir, const char *ext, const vocabulary_t *script_run) {
const char *exec_path = get_my_executable_directory();
const char *user_path = get_my_user_directory();
if (exec_path != NULL) {
char path[VOCAB_MAX_PATH] = {0};
int n = snprintf(path, sizeof(path), "%s%s", exec_path, pm3dir);
if (n > 0 && (size_t)n < sizeof(path)) {
vocab_add_scripts_dir(path, "", ext, script_run);
}
}
if (user_path != NULL) {
char path[VOCAB_MAX_PATH] = {0};
int n = snprintf(path, sizeof(path), "%s%s%s", user_path, PM3_USER_DIRECTORY, pm3dir);
if (n > 0 && (size_t)n < sizeof(path)) {
vocab_add_scripts_dir(path, "", ext, script_run);
}
}
if (exec_path != NULL) {
char path[VOCAB_MAX_PATH] = {0};
int n = snprintf(path, sizeof(path), "%s%s%s", exec_path, PM3_SHARE_RELPATH, pm3dir);
if (n > 0 && (size_t)n < sizeof(path)) {
vocab_add_scripts_dir(path, "", ext, script_run);
}
}
}
void pm3line_vocabulary_build(void) {
pm3line_vocabulary_free();
// The walk goes through the Parse() of every category. Keep it silent:
// a few commands shown like categories (e.g. "reveng") run their own
// parser on the walk token and would complain about it.
uint8_t old_printAndLog = g_printAndLog;
g_printAndLog = 0;
walkCommandsRecursive(getTopLevelCommandTable(), vocab_visit_command, NULL);
g_printAndLog = old_printAndLog;
// Script files complete as "script run <file>", with the availability of "script run".
// Take a copy: vocab_add() may realloc the array while scripts are being added.
vocabulary_t script_run = {0};
for (size_t i = 0; i < s_count; i++) {
if (strcmp(s_vocab[i].name, "script run") == 0) {
script_run = s_vocab[i];
break;
}
}
if (script_run.name != NULL) {
vocab_add_scripts(LUA_SCRIPTS_SUBDIR, ".lua", &script_run);
vocab_add_scripts(CMD_SCRIPTS_SUBDIR, ".cmd", &script_run);
#ifdef HAVE_PYTHON
vocab_add_scripts(PYTHON_SCRIPTS_SUBDIR, ".py", &script_run);
#endif
}
s_built = true;
}
void pm3line_vocabulary_free(void) {
for (size_t i = 0; i < s_count; i++) {
free(s_vocab[i].name);
}
free(s_vocab);
s_vocab = NULL;
s_count = 0;
s_capacity = 0;
s_built = false;
}
const vocabulary_t *pm3line_vocabulary_get(size_t *count) {
if (s_built == false) {
pm3line_vocabulary_build();
}
if (count != NULL) {
*count = s_count;
}
return s_vocab;
}
bool pm3line_vocabulary_is_available(const vocabulary_t *entry) {
if (entry == NULL) {
return false;
}
for (uint8_t i = 0; i < entry->depth; i++) {
if (entry->is_available[i] != NULL && entry->is_available[i]() == false) {
return false;
}
}
return true;
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -702,6 +702,7 @@ check_script:
}
CmdScriptCleanup();
pm3line_cleanup();
}
#ifndef LIBPM3