GP-4847: Unify Debugger param dialogs. Prefixed integers allowed.

This commit is contained in:
Dan 2024-09-05 12:35:28 -04:00
parent e0bf7b4c53
commit 16ff4c4d08
36 changed files with 2842 additions and 1509 deletions

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,397 +15,128 @@
*/
package ghidra.app.plugin.core.debug.gui.tracermi;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.beans.*;
import java.util.*;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.jdom.Element;
import docking.DialogComponentProvider;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.app.plugin.core.debug.service.tracermi.TraceRmiTarget;
import ghidra.app.plugin.core.debug.utils.MiscellaneousUtils;
import ghidra.app.plugin.core.debug.gui.AbstractDebuggerParameterDialog;
import ghidra.app.plugin.core.debug.service.tracermi.TraceRmiTarget.Missing;
import ghidra.dbg.target.TargetObject;
import ghidra.dbg.target.schema.SchemaContext;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.RemoteParameter;
import ghidra.framework.options.SaveState;
import ghidra.framework.plugintool.AutoConfigState.ConfigStateField;
import ghidra.framework.plugintool.PluginTool;
import ghidra.util.Msg;
import ghidra.util.layout.PairLayout;
import ghidra.trace.model.target.TraceObject;
public class RemoteMethodInvocationDialog extends DialogComponentProvider
implements PropertyChangeListener {
private static final String KEY_MEMORIZED_ARGUMENTS = "memorizedArguments";
public class RemoteMethodInvocationDialog extends AbstractDebuggerParameterDialog<RemoteParameter> {
static class ChoicesPropertyEditor implements PropertyEditor {
private final List<?> choices;
private final String[] tags;
private final List<PropertyChangeListener> listeners = new ArrayList<>();
private Object value;
public ChoicesPropertyEditor(Set<?> choices) {
this.choices = List.copyOf(choices);
this.tags = choices.stream().map(Objects::toString).toArray(String[]::new);
}
/**
* TODO: Make this a proper editor which can browse and select objects of a required schema.
*/
public static class TraceObjectEditor extends PropertyEditorSupport {
private final JLabel unmodifiableField = new JLabel();
@Override
public void setValue(Object value) {
if (Objects.equals(value, this.value)) {
super.setValue(value);
if (value == null) {
unmodifiableField.setText("");
return;
}
if (!choices.contains(value)) {
throw new IllegalArgumentException("Unsupported value: " + value);
if (!(value instanceof TraceObject obj)) {
throw new IllegalArgumentException();
}
Object oldValue;
List<PropertyChangeListener> listeners;
synchronized (this.listeners) {
oldValue = this.value;
this.value = value;
if (this.listeners.isEmpty()) {
return;
}
listeners = List.copyOf(this.listeners);
}
PropertyChangeEvent evt = new PropertyChangeEvent(this, null, oldValue, value);
for (PropertyChangeListener l : listeners) {
l.propertyChange(evt);
}
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean isPaintable() {
return false;
}
@Override
public void paintValue(Graphics gfx, Rectangle box) {
// Not paintable
}
@Override
public String getJavaInitializationString() {
if (value == null) {
return "null";
}
if (value instanceof String str) {
return "\"" + StringEscapeUtils.escapeJava(str) + "\"";
}
return Objects.toString(value);
}
@Override
public String getAsText() {
return Objects.toString(value);
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
int index = ArrayUtils.indexOf(tags, text);
if (index < 0) {
throw new IllegalArgumentException("Unsupported value: " + text);
}
setValue(choices.get(index));
}
@Override
public String[] getTags() {
return tags.clone();
}
@Override
public Component getCustomEditor() {
return null;
unmodifiableField.setText(obj.getCanonicalPath().toString());
}
@Override
public boolean supportsCustomEditor() {
return false;
return true;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
public Component getCustomEditor() {
return unmodifiableField;
}
}
record NameTypePair(String name, Class<?> type) {
public static NameTypePair fromParameter(SchemaContext ctx, RemoteParameter parameter) {
return new NameTypePair(parameter.name(), ctx.getSchema(parameter.type()).getType());
}
public static NameTypePair fromString(String name) throws ClassNotFoundException {
String[] parts = name.split(",", 2);
if (parts.length != 2) {
// This appears to be a bad assumption - empty fields results in solitary labels
return new NameTypePair(parts[0], String.class);
//throw new IllegalArgumentException("Could not parse name,type");
}
return new NameTypePair(parts[0], Class.forName(parts[1]));
}
static {
PropertyEditorManager.registerEditor(TraceObject.class, TraceObjectEditor.class);
}
private final BidiMap<RemoteParameter, PropertyEditor> paramEditors =
new DualLinkedHashBidiMap<>();
private final SchemaContext ctx;
private JPanel panel;
private JLabel descriptionLabel;
private JPanel pairPanel;
private PairLayout layout;
protected JButton invokeButton;
protected JButton resetButton;
private final PluginTool tool;
private SchemaContext ctx;
private Map<String, RemoteParameter> parameters;
private Map<String, Object> defaults;
// TODO: Not sure this is the best keying, but I think it works.
private Map<NameTypePair, Object> memorized = new HashMap<>();
private Map<String, Object> arguments;
public RemoteMethodInvocationDialog(PluginTool tool, String title, String buttonText,
Icon buttonIcon) {
super(title, true, true, true, false);
this.tool = tool;
populateComponents(buttonText, buttonIcon);
setRememberSize(false);
}
protected Object computeMemorizedValue(RemoteParameter parameter) {
return memorized.computeIfAbsent(NameTypePair.fromParameter(ctx, parameter),
ntp -> parameter.getDefaultValue());
}
public Map<String, Object> promptArguments(SchemaContext ctx,
Map<String, RemoteParameter> parameterMap, Map<String, Object> defaults) {
setParameters(ctx, parameterMap);
setDefaults(defaults);
tool.showDialog(this);
return getArguments();
}
public void setParameters(SchemaContext ctx, Map<String, RemoteParameter> parameterMap) {
public RemoteMethodInvocationDialog(PluginTool tool, SchemaContext ctx, String title,
String buttonText, Icon buttonIcon) {
super(tool, title, buttonText, buttonIcon);
this.ctx = ctx;
this.parameters = parameterMap;
populateOptions();
}
public void setDefaults(Map<String, Object> defaults) {
this.defaults = defaults;
}
private void populateComponents(String buttonText, Icon buttonIcon) {
panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
layout = new PairLayout(5, 5);
pairPanel = new JPanel(layout);
JPanel centering = new JPanel(new FlowLayout(FlowLayout.CENTER));
JScrollPane scrolling = new JScrollPane(centering, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//scrolling.setPreferredSize(new Dimension(100, 130));
panel.add(scrolling, BorderLayout.CENTER);
centering.add(pairPanel);
descriptionLabel = new JLabel();
descriptionLabel.setMaximumSize(new Dimension(300, 100));
panel.add(descriptionLabel, BorderLayout.NORTH);
addWorkPanel(panel);
invokeButton = new JButton(buttonText, buttonIcon);
addButton(invokeButton);
resetButton = new JButton("Reset", DebuggerResources.ICON_REFRESH);
addButton(resetButton);
addCancelButton();
invokeButton.addActionListener(this::invoke);
resetButton.addActionListener(this::reset);
}
@Override
protected void cancelCallback() {
this.arguments = null;
close();
protected String parameterName(RemoteParameter parameter) {
return parameter.name();
}
protected void invoke(ActionEvent evt) {
this.arguments = collectArguments();
close();
}
private void reset(ActionEvent evt) {
this.arguments = new HashMap<>();
for (RemoteParameter param : parameters.values()) {
if (defaults.containsKey(param.name())) {
arguments.put(param.name(), defaults.get(param.name()));
}
else {
arguments.put(param.name(), param.getDefaultValue());
}
@Override
protected Class<?> parameterType(RemoteParameter parameter) {
Class<?> type = ctx.getSchema(parameter.type()).getType();
if (TargetObject.class.isAssignableFrom(type)) {
return TraceObject.class;
}
populateValues();
return type;
}
protected PropertyEditor createEditor(RemoteParameter param) {
Class<?> type = ctx.getSchema(param.type()).getType();
PropertyEditor editor = PropertyEditorManager.findEditor(type);
if (editor != null) {
return editor;
}
Msg.warn(this, "No editor for " + type + "? Trying String instead");
return PropertyEditorManager.findEditor(String.class);
@Override
protected String parameterLabel(RemoteParameter parameter) {
return "".equals(parameter.display()) ? parameter.name() : parameter.display();
}
void populateOptions() {
pairPanel.removeAll();
paramEditors.clear();
for (RemoteParameter param : parameters.values()) {
String text = param.display().equals("") ? param.name() : param.display();
JLabel label = new JLabel(text);
label.setToolTipText(param.description());
pairPanel.add(label);
PropertyEditor editor = createEditor(param);
Object val = computeMemorizedValue(param);
if (val == null || val.equals(TraceRmiTarget.Missing.MISSING)) {
editor.setValue("");
} else {
editor.setValue(val);
}
editor.addPropertyChangeListener(this);
pairPanel.add(MiscellaneousUtils.getEditorComponent(editor));
paramEditors.put(param, editor);
}
@Override
protected String parameterToolTip(RemoteParameter parameter) {
return parameter.description();
}
void populateValues() {
for (Map.Entry<String, Object> ent : arguments.entrySet()) {
RemoteParameter param = parameters.get(ent.getKey());
if (param == null) {
Msg.warn(this, "No parameter for argument: " + ent);
continue;
}
PropertyEditor editor = paramEditors.get(param);
editor.setValue(ent.getValue());
}
@Override
protected ValStr<?> parameterDefault(RemoteParameter parameter) {
return ValStr.from(parameter.getDefaultValue());
}
protected Map<String, Object> collectArguments() {
Map<String, Object> map = new LinkedHashMap<>();
for (RemoteParameter param : paramEditors.keySet()) {
Object val = memorized.get(NameTypePair.fromParameter(ctx, param));
if (val != null) {
map.put(param.name(), val);
}
}
return map;
@Override
protected Collection<?> parameterChoices(RemoteParameter parameter) {
return Set.of();
}
public Map<String, Object> getArguments() {
@Override
protected Map<String, ValStr<?>> validateArguments(Map<String, RemoteParameter> parameters,
Map<String, ValStr<?>> arguments) {
return arguments;
}
public <T> void setMemorizedArgument(String name, Class<T> type, T value) {
if (value == null) {
return;
}
memorized.put(new NameTypePair(name, type), value);
}
public <T> T getMemorizedArgument(String name, Class<T> type) {
return type.cast(memorized.get(new NameTypePair(name, type)));
@Override
protected void parameterSaveValue(RemoteParameter parameter, SaveState state, String key,
ValStr<?> value) {
ConfigStateField.putState(state, parameterType(parameter).asSubclass(Object.class), key,
value.val());
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
PropertyEditor editor = (PropertyEditor) evt.getSource();
RemoteParameter param = paramEditors.getKey(editor);
memorized.put(NameTypePair.fromParameter(ctx, param), editor.getValue());
protected ValStr<?> parameterLoadValue(RemoteParameter parameter, SaveState state, String key) {
return ValStr.from(
ConfigStateField.getState(state, parameterType(parameter), key));
}
public void writeConfigState(SaveState saveState) {
SaveState subState = new SaveState();
for (Map.Entry<NameTypePair, Object> ent : memorized.entrySet()) {
NameTypePair ntp = ent.getKey();
ConfigStateField.putState(subState, ntp.type().asSubclass(Object.class), ntp.name(),
ent.getValue());
}
saveState.putXmlElement(KEY_MEMORIZED_ARGUMENTS, subState.saveToXml());
}
public void readConfigState(SaveState saveState) {
Element element = saveState.getXmlElement(KEY_MEMORIZED_ARGUMENTS);
if (element == null) {
return;
}
SaveState subState = new SaveState(element);
for (String name : subState.getNames()) {
try {
NameTypePair ntp = NameTypePair.fromString(name);
memorized.put(ntp, ConfigStateField.getState(subState, ntp.type(), ntp.name()));
}
catch (Exception e) {
Msg.error(this, "Error restoring memorized parameter " + name, e);
}
}
}
public void setDescription(String htmlDescription) {
if (htmlDescription == null) {
descriptionLabel.setBorder(BorderFactory.createEmptyBorder());
descriptionLabel.setText("");
}
else {
descriptionLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
descriptionLabel.setText(htmlDescription);
}
@Override
protected void setEditorValue(PropertyEditor editor, RemoteParameter param, ValStr<?> val) {
ValStr<?> v = switch (val.val()) {
case Missing __ -> new ValStr<>(null, "");
case TraceObject obj -> new ValStr<>(obj, obj.getCanonicalPath().toString());
default -> val;
};
super.setEditorValue(editor, param, v);
}
}

View file

@ -0,0 +1,46 @@
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.debug.gui.tracermi.connection;
import java.util.Map;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.TraceRmiLaunchDialog;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.LaunchParameter;
import ghidra.framework.plugintool.PluginTool;
public class TraceRmiConnectDialog extends TraceRmiLaunchDialog {
static final LaunchParameter<String> PARAM_ADDRESS =
LaunchParameter.create(String.class, "address",
"Host/Address", "Address or hostname for interface(s) to listen on",
true, ValStr.str("localhost"), str -> str);
static final LaunchParameter<Integer> PARAM_PORT =
LaunchParameter.create(Integer.class, "port",
"Port", "TCP port number, 0 for ephemeral",
true, ValStr.from(0), Integer::decode);
private static final Map<String, LaunchParameter<?>> PARAMETERS =
LaunchParameter.mapOf(PARAM_ADDRESS, PARAM_PORT);
public TraceRmiConnectDialog(PluginTool tool, String title, String buttonText) {
super(tool, title, buttonText, DebuggerResources.ICON_CONNECTION);
}
public Map<String, ValStr<?>> promptArguments() {
return promptArguments(PARAMETERS, Map.of(), Map.of());
}
}

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -34,11 +34,9 @@ import docking.action.builder.ActionBuilder;
import docking.widgets.tree.*;
import ghidra.app.plugin.core.debug.DebuggerPluginPackage;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.app.plugin.core.debug.gui.objects.components.DebuggerMethodInvocationDialog;
import ghidra.app.plugin.core.debug.gui.tracermi.connection.tree.*;
import ghidra.app.services.*;
import ghidra.dbg.target.TargetMethod.ParameterDescription;
import ghidra.dbg.target.TargetMethod.TargetParameterMap;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.control.ControlMode;
import ghidra.debug.api.target.Target;
import ghidra.debug.api.tracemgr.DebuggerCoordinates;
@ -62,16 +60,6 @@ public class TraceRmiConnectionManagerProvider extends ComponentProviderAdapter
private static final String GROUP_CONNECT = "1. Connect";
private static final String GROUP_MAINTENANCE = "3. Maintenance";
private static final ParameterDescription<String> PARAM_ADDRESS =
ParameterDescription.create(String.class, "address", true, "localhost",
"Host/Address", "Address or hostname for interface(s) to listen on");
private static final ParameterDescription<Integer> PARAM_PORT =
ParameterDescription.create(Integer.class, "port", true, 0,
"Port", "TCP port number, 0 for ephemeral");
private static final TargetParameterMap PARAMETERS = TargetParameterMap.ofEntries(
Map.entry(PARAM_ADDRESS.name, PARAM_ADDRESS),
Map.entry(PARAM_PORT.name, PARAM_PORT));
interface StartServerAction {
String NAME = "Start Server";
String DESCRIPTION = "Start a TCP server for incoming connections (indefinitely)";
@ -344,25 +332,24 @@ public class TraceRmiConnectionManagerProvider extends ComponentProviderAdapter
return traceRmiService != null && !traceRmiService.isServerStarted();
}
private InetSocketAddress promptSocketAddress(String title, String okText) {
DebuggerMethodInvocationDialog dialog = new DebuggerMethodInvocationDialog(tool,
title, okText, DebuggerResources.ICON_CONNECTION);
Map<String, ?> arguments;
do {
dialog.forgetMemorizedArguments();
arguments = dialog.promptArguments(PARAMETERS);
}
while (dialog.isResetRequested());
private InetSocketAddress promptSocketAddress(String title, String okText,
HelpLocation helpLocation) {
TraceRmiConnectDialog dialog = new TraceRmiConnectDialog(tool, title, okText);
dialog.setHelpLocation(helpLocation);
Map<String, ValStr<?>> arguments = dialog.promptArguments();
if (arguments == null) {
// Cancelled
return null;
}
String address = PARAM_ADDRESS.get(arguments);
int port = PARAM_PORT.get(arguments);
String address = TraceRmiConnectDialog.PARAM_ADDRESS.get(arguments).val();
int port = TraceRmiConnectDialog.PARAM_PORT.get(arguments).val();
return new InetSocketAddress(address, port);
}
private void doActionStartServerActivated(ActionContext __) {
InetSocketAddress sockaddr = promptSocketAddress("Start Trace RMI Server", "Start");
InetSocketAddress sockaddr = promptSocketAddress("Start Trace RMI Server", "Start",
actionStartServer.getHelpLocation());
if (sockaddr == null) {
return;
}
@ -395,7 +382,8 @@ public class TraceRmiConnectionManagerProvider extends ComponentProviderAdapter
}
private void doActionConnectAcceptActivated(ActionContext __) {
InetSocketAddress sockaddr = promptSocketAddress("Accept Trace RMI Connection", "Listen");
InetSocketAddress sockaddr = promptSocketAddress("Accept Trace RMI Connection", "Listen",
actionConnectAccept.getHelpLocation());
if (sockaddr == null) {
return;
}
@ -420,7 +408,8 @@ public class TraceRmiConnectionManagerProvider extends ComponentProviderAdapter
}
private void doActionConnectOutboundActivated(ActionContext __) {
InetSocketAddress sockaddr = promptSocketAddress("Connect to Trace RMI", "Connect");
InetSocketAddress sockaddr = promptSocketAddress("Connect to Trace RMI", "Connect",
actionConnectOutbound.getHelpLocation());
if (sockaddr == null) {
return;
}

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -23,7 +23,8 @@ import javax.swing.Icon;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.ScriptAttributesParser.ScriptAttributes;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.ScriptAttributesParser.TtyCondition;
import ghidra.dbg.target.TargetMethod.ParameterDescription;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.LaunchParameter;
import ghidra.debug.api.tracermi.TerminalSession;
import ghidra.program.model.listing.Program;
import ghidra.util.HelpLocation;
@ -84,7 +85,7 @@ public abstract class AbstractScriptTraceRmiLaunchOffer extends AbstractTraceRmi
}
@Override
public Map<String, ParameterDescription<?>> getParameters() {
public Map<String, LaunchParameter<?>> getParameters() {
return attrs.parameters();
}
@ -93,12 +94,15 @@ public abstract class AbstractScriptTraceRmiLaunchOffer extends AbstractTraceRmi
return attrs.timeoutMillis();
}
protected abstract void prepareSubprocess(List<String> commandLine, Map<String, String> env,
Map<String, ?> args, SocketAddress address);
protected void prepareSubprocess(List<String> commandLine, Map<String, String> env,
Map<String, ValStr<?>> args, SocketAddress address) {
ScriptAttributesParser.processArguments(commandLine, env, script, attrs.parameters(), args,
address);
}
@Override
protected void launchBackEnd(TaskMonitor monitor, Map<String, TerminalSession> sessions,
Map<String, ?> args, SocketAddress address) throws Exception {
Map<String, ValStr<?>> args, SocketAddress address) throws Exception {
List<String> commandLine = new ArrayList<>();
Map<String, String> env = new HashMap<>(System.getenv());
prepareSubprocess(commandLine, env, args, address);
@ -112,7 +116,7 @@ public abstract class AbstractScriptTraceRmiLaunchOffer extends AbstractTraceRmi
}
NullPtyTerminalSession ns = nullPtyTerminal();
env.put(ent.getKey(), ns.name());
sessions.put(ns.name(), ns);
sessions.put(ent.getKey(), ns);
}
sessions.put("Shell",

View file

@ -28,7 +28,7 @@ import java.util.concurrent.*;
import javax.swing.Icon;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.app.plugin.core.debug.gui.objects.components.DebuggerMethodInvocationDialog;
import ghidra.app.plugin.core.debug.gui.action.ByModuleAutoMapSpec;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.LaunchFailureDialog.ErrPromptResponse;
import ghidra.app.plugin.core.debug.service.tracermi.DefaultTraceRmiAcceptor;
import ghidra.app.plugin.core.debug.service.tracermi.TraceRmiHandler;
@ -36,8 +36,8 @@ import ghidra.app.plugin.core.terminal.TerminalListener;
import ghidra.app.services.*;
import ghidra.app.services.DebuggerTraceManagerService.ActivationCause;
import ghidra.async.AsyncUtils;
import ghidra.dbg.target.TargetMethod.ParameterDescription;
import ghidra.dbg.util.ShellUtils;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.action.AutoMapSpec;
import ghidra.debug.api.modules.DebuggerMissingProgramActionContext;
import ghidra.debug.api.modules.DebuggerStaticMappingChangeListener;
@ -212,14 +212,13 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
return mappingService.getOpenMappedLocation(trace, probe, snap) != null;
}
protected SaveState saveLauncherArgsToState(Map<String, ?> args,
Map<String, ParameterDescription<?>> params) {
protected SaveState saveLauncherArgsToState(Map<String, ValStr<?>> args,
Map<String, LaunchParameter<?>> params) {
SaveState state = new SaveState();
for (ParameterDescription<?> param : params.values()) {
Object val = args.get(param.name);
for (LaunchParameter<?> param : params.values()) {
ValStr<?> val = args.get(param.name());
if (val != null) {
ConfigStateField.putState(state, param.type.asSubclass(Object.class),
"param_" + param.name, val);
state.putString("param_" + param.name(), val.str());
}
}
return state;
@ -233,56 +232,56 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
plugin.writeProgramLaunchConfig(program, getConfigName(), state);
}
protected void saveLauncherArgs(Map<String, ?> args,
Map<String, ParameterDescription<?>> params) {
protected void saveLauncherArgs(Map<String, ValStr<?>> args,
Map<String, LaunchParameter<?>> params) {
saveState(saveLauncherArgsToState(args, params));
}
interface ImageParamSetter {
@SuppressWarnings("unchecked")
static ImageParamSetter get(ParameterDescription<?> param) {
if (param.type == String.class) {
return new StringImageParamSetter((ParameterDescription<String>) param);
static ImageParamSetter get(LaunchParameter<?> param) {
if (param.type() == String.class) {
return new StringImageParamSetter((LaunchParameter<String>) param);
}
if (param.type == PathIsFile.class) {
return new FileImageParamSetter((ParameterDescription<PathIsFile>) param);
if (param.type() == PathIsFile.class) {
return new FileImageParamSetter((LaunchParameter<PathIsFile>) param);
}
Msg.warn(ImageParamSetter.class,
"'Image' parameter has unsupported type: " + param.type);
"'Image' parameter has unsupported type: " + param.type());
return null;
}
void setImage(Map<String, Object> map, Program program);
void setImage(Map<String, ValStr<?>> map, Program program);
}
static class StringImageParamSetter implements ImageParamSetter {
private final ParameterDescription<String> param;
private final LaunchParameter<String> param;
public StringImageParamSetter(ParameterDescription<String> param) {
public StringImageParamSetter(LaunchParameter<String> param) {
this.param = param;
}
@Override
public void setImage(Map<String, Object> map, Program program) {
public void setImage(Map<String, ValStr<?>> map, Program program) {
// str-type Image is a hint that the launcher is remote
String value = TraceRmiLauncherServicePlugin.getProgramPath(program, false);
param.set(map, value);
param.set(map, ValStr.str(value));
}
}
static class FileImageParamSetter implements ImageParamSetter {
private final ParameterDescription<PathIsFile> param;
private final LaunchParameter<PathIsFile> param;
public FileImageParamSetter(ParameterDescription<PathIsFile> param) {
public FileImageParamSetter(LaunchParameter<PathIsFile> param) {
this.param = param;
}
@Override
public void setImage(Map<String, Object> map, Program program) {
public void setImage(Map<String, ValStr<?>> map, Program program) {
// file-type Image is a hint that the launcher is local
String str = TraceRmiLauncherServicePlugin.getProgramPath(program, true);
PathIsFile value = str == null ? null : new PathIsFile(Paths.get(str));
param.set(map, value);
param.set(map, new ValStr<>(value, str));
}
}
@ -297,33 +296,34 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
* @return the default arguments
*/
@SuppressWarnings("unchecked")
protected Map<String, ?> generateDefaultLauncherArgs(
Map<String, ParameterDescription<?>> params) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
protected Map<String, ValStr<?>> generateDefaultLauncherArgs(
Map<String, LaunchParameter<?>> params) {
Map<String, ValStr<?>> map = new LinkedHashMap<>();
ImageParamSetter imageSetter = null;
for (Entry<String, ParameterDescription<?>> entry : params.entrySet()) {
ParameterDescription<?> param = entry.getValue();
map.put(entry.getKey(), param.defaultValue);
if (PARAM_DISPLAY_IMAGE.equals(param.display)) {
for (Entry<String, LaunchParameter<?>> entry : params.entrySet()) {
LaunchParameter<?> param = entry.getValue();
map.put(entry.getKey(), ValStr.cast(Object.class, param.defaultValue()));
if (PARAM_DISPLAY_IMAGE.equals(param.display())) {
imageSetter = ImageParamSetter.get(param);
// May still be null if type is not supported
}
else if (param.name.startsWith(PREFIX_PARAM_EXTTOOL)) {
String tool = param.name.substring(PREFIX_PARAM_EXTTOOL.length());
else if (param.name().startsWith(PREFIX_PARAM_EXTTOOL)) {
String tool = param.name().substring(PREFIX_PARAM_EXTTOOL.length());
List<String> names =
program.getLanguage().getLanguageDescription().getExternalNames(tool);
if (names != null && !names.isEmpty()) {
if (param.type == String.class) {
var paramStr = (ParameterDescription<String>) param;
paramStr.set(map, names.get(0));
String toolName = names.get(0);
if (param.type() == String.class) {
var paramStr = (LaunchParameter<String>) param;
paramStr.set(map, ValStr.str(toolName));
}
else if (param.type == PathIsFile.class) {
var paramPIF = (ParameterDescription<PathIsFile>) param;
paramPIF.set(map, PathIsFile.fromString(names.get(0)));
else if (param.type() == PathIsFile.class) {
var paramPIF = (LaunchParameter<PathIsFile>) param;
paramPIF.set(map, new ValStr<>(PathIsFile.fromString(toolName), toolName));
}
else if (param.type == PathIsDir.class) {
var paramPID = (ParameterDescription<PathIsDir>) param;
paramPID.set(map, PathIsDir.fromString(names.get(0)));
else if (param.type() == PathIsDir.class) {
var paramPID = (LaunchParameter<PathIsDir>) param;
paramPID.set(map, new ValStr<>(PathIsDir.fromString(toolName), toolName));
}
}
}
@ -337,50 +337,33 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
/**
* Prompt the user for arguments, showing those last used or defaults
*
* @param lastExc
*
* @param params the parameters of the model's launcher
* @param configurator a thing to generate/modify the (default) arguments
* @param lastExc if re-prompting, an error to display
* @return the arguments given by the user, or null if cancelled
*/
protected Map<String, ?> promptLauncherArgs(LaunchConfigurator configurator,
protected Map<String, ValStr<?>> promptLauncherArgs(LaunchConfigurator configurator,
Throwable lastExc) {
Map<String, ParameterDescription<?>> params = getParameters();
DebuggerMethodInvocationDialog dialog =
new DebuggerMethodInvocationDialog(tool, getTitle(), "Launch", getIcon());
Map<String, LaunchParameter<?>> params = getParameters();
TraceRmiLaunchDialog dialog =
new TraceRmiLaunchDialog(tool, getTitle(), "Launch", getIcon());
dialog.setDescription(getDescription());
dialog.setHelpLocation(getHelpLocation());
if (lastExc != null) {
dialog.setStatusText(lastExc.toString(), MessageType.ERROR);
}
else {
dialog.setStatusText("");
}
// NB. Do not invoke read/writeConfigState
Map<String, ?> args;
boolean reset = false;
do {
args =
configurator.configureLauncher(this, loadLastLauncherArgs(true), RelPrompt.BEFORE);
for (ParameterDescription<?> param : params.values()) {
Object val = args.get(param.name);
if (val != null) {
dialog.setMemorizedArgument(param.name, param.type.asSubclass(Object.class),
val);
}
}
if (lastExc != null) {
dialog.setStatusText(lastExc.toString(), MessageType.ERROR);
}
else {
dialog.setStatusText("");
}
args = dialog.promptArguments(params);
if (args == null) {
// Cancelled
return null;
}
reset = dialog.isResetRequested();
if (reset) {
args = generateDefaultLauncherArgs(params);
}
Map<String, ValStr<?>> defaultArgs = generateDefaultLauncherArgs(params);
Map<String, ValStr<?>> lastArgs =
configurator.configureLauncher(this, loadLastLauncherArgs(true), RelPrompt.BEFORE);
Map<String, ValStr<?>> args = dialog.promptArguments(params, lastArgs, defaultArgs);
if (args != null) {
saveLauncherArgs(args, params);
}
while (reset);
return args;
}
@ -398,31 +381,40 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
* @param forPrompt true if the user will be confirming the arguments
* @return the loaded arguments, or defaults
*/
protected Map<String, ?> loadLastLauncherArgs(boolean forPrompt) {
Map<String, ParameterDescription<?>> params = getParameters();
Map<String, ?> args = loadLauncherArgsFromState(loadState(forPrompt), params);
protected Map<String, ValStr<?>> loadLastLauncherArgs(boolean forPrompt) {
Map<String, LaunchParameter<?>> params = getParameters();
Map<String, ValStr<?>> args = loadLauncherArgsFromState(loadState(forPrompt), params);
saveLauncherArgs(args, params);
return args;
}
protected Map<String, ?> loadLauncherArgsFromState(SaveState state,
Map<String, ParameterDescription<?>> params) {
Map<String, ?> defaultArgs = generateDefaultLauncherArgs(params);
protected Map<String, ValStr<?>> loadLauncherArgsFromState(SaveState state,
Map<String, LaunchParameter<?>> params) {
Map<String, ValStr<?>> defaultArgs = generateDefaultLauncherArgs(params);
if (state == null) {
return defaultArgs;
}
List<String> names = List.of(state.getNames());
Map<String, Object> args = new LinkedHashMap<>();
for (ParameterDescription<?> param : params.values()) {
String key = "param_" + param.name;
Object configState =
names.contains(key) ? ConfigStateField.getState(state, param.type, key) : null;
if (configState != null) {
args.put(param.name, configState);
Map<String, ValStr<?>> args = new LinkedHashMap<>();
Set<String> names = Set.of(state.getNames());
for (LaunchParameter<?> param : params.values()) {
String key = "param_" + param.name();
if (!names.contains(key)) {
args.put(param.name(), defaultArgs.get(param.name()));
continue;
}
else {
args.put(param.name, defaultArgs.get(param.name));
String str = state.getString(key, null);
if (str != null) {
args.put(param.name(), param.decode(str));
continue;
}
// Perhaps wrong type; was saved in older version.
Object fallback = ConfigStateField.getState(state, param.type(), param.name());
if (fallback != null) {
args.put(param.name(), ValStr.from(fallback));
continue;
}
Msg.warn(this, "Could not load saved launcher arg '%s' (%s)".formatted(param.name(),
param.display()));
}
return args;
}
@ -435,7 +427,7 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
}
/**
* Obtain the launcher args
* Obtain the launcher arguments
*
* <p>
* This should either call {@link #promptLauncherArgs(LaunchConfigurator, Throwable)} or
@ -447,7 +439,7 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
* @param lastExc if retrying, the last exception to display as an error message
* @return the chosen arguments, or null if the user cancels at the prompt
*/
public Map<String, ?> getLauncherArgs(boolean prompt, LaunchConfigurator configurator,
public Map<String, ValStr<?>> getLauncherArgs(boolean prompt, LaunchConfigurator configurator,
Throwable lastExc) {
return prompt
? configurator.configureLauncher(this, promptLauncherArgs(configurator, lastExc),
@ -543,8 +535,8 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
}
protected abstract void launchBackEnd(TaskMonitor monitor,
Map<String, TerminalSession> sessions, Map<String, ?> args, SocketAddress address)
throws Exception;
Map<String, TerminalSession> sessions, Map<String, ValStr<?>> args,
SocketAddress address) throws Exception;
static class NoStaticMappingException extends Exception {
public NoStaticMappingException(String message) {
@ -557,9 +549,18 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
}
}
protected void initializeMonitor(TaskMonitor monitor) {
protected AutoMapSpec getAutoMapSpec() {
DebuggerAutoMappingService auto = tool.getService(DebuggerAutoMappingService.class);
AutoMapSpec spec = auto.getAutoMapSpec();
return auto == null ? ByModuleAutoMapSpec.instance() : auto.getAutoMapSpec();
}
protected AutoMapSpec getAutoMapSpec(Trace trace) {
DebuggerAutoMappingService auto = tool.getService(DebuggerAutoMappingService.class);
return auto == null ? ByModuleAutoMapSpec.instance() : auto.getAutoMapSpec(trace);
}
protected void initializeMonitor(TaskMonitor monitor) {
AutoMapSpec spec = getAutoMapSpec();
if (requiresImage() && spec.hasTask()) {
monitor.setMaximum(6);
}
@ -574,8 +575,7 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
if (!requiresImage()) {
return;
}
DebuggerAutoMappingService auto = tool.getService(DebuggerAutoMappingService.class);
AutoMapSpec spec = auto.getAutoMapSpec(trace);
AutoMapSpec spec = getAutoMapSpec(trace);
if (!spec.hasTask()) {
return;
}
@ -625,7 +625,7 @@ public abstract class AbstractTraceRmiLaunchOffer implements TraceRmiLaunchOffer
while (true) {
try {
monitor.setMessage("Gathering arguments");
Map<String, ?> args = getLauncherArgs(prompt, configurator, lastExc);
Map<String, ValStr<?>> args = getLauncherArgs(prompt, configurator, lastExc);
if (args == null) {
if (lastExc == null) {
lastExc = new CancelledException();

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,18 +22,31 @@ import java.util.List;
import java.util.Map;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.ScriptAttributesParser.ScriptAttributes;
import ghidra.debug.api.ValStr;
import ghidra.program.model.listing.Program;
/**
* A launcher implemented by a simple DOS/Windows batch file.
*
* <p>
* The script must start with an attributes header in a comment block.
* The script must start with an attributes header in a comment block. See
* {@link ScriptAttributesParser}.
*/
public class BatchScriptTraceRmiLaunchOffer extends AbstractScriptTraceRmiLaunchOffer {
public static final String REM = "::";
public static final int REM_LEN = REM.length();
/**
* Create a launch offer from the given batch file.
*
* @param plugin the launcher service plugin
* @param program the current program, usually the target image. In general, this should be used
* for at least two purposes. 1) To populate the default command line. 2) To ensure
* the target image is mapped in the resulting target trace.
* @param script the batch file that implements this offer
* @return the offer
* @throws FileNotFoundException if the batch file does not exist
*/
public static BatchScriptTraceRmiLaunchOffer create(TraceRmiLauncherServicePlugin plugin,
Program program, File script) throws FileNotFoundException {
ScriptAttributesParser parser = new ScriptAttributesParser() {
@ -60,11 +73,4 @@ public class BatchScriptTraceRmiLaunchOffer extends AbstractScriptTraceRmiLaunch
File script, String configName, ScriptAttributes attrs) {
super(plugin, program, script, configName, attrs);
}
@Override
protected void prepareSubprocess(List<String> commandLine, Map<String, String> env,
Map<String, ?> args, SocketAddress address) {
ScriptAttributesParser.processArguments(commandLine, env, script, attrs.parameters(), args,
address);
}
}

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -27,18 +27,23 @@ import javax.swing.Icon;
import generic.theme.GIcon;
import generic.theme.Gui;
import ghidra.dbg.target.TargetMethod.ParameterDescription;
import ghidra.dbg.util.ShellUtils;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.LaunchParameter;
import ghidra.framework.Application;
import ghidra.framework.plugintool.AutoConfigState.PathIsDir;
import ghidra.framework.plugintool.AutoConfigState.PathIsFile;
import ghidra.util.HelpLocation;
import ghidra.util.Msg;
import ghidra.util.*;
/**
* A parser for reading attributes from a script header
*/
public abstract class ScriptAttributesParser {
public static final String ENV_GHIDRA_HOME = "GHIDRA_HOME";
public static final String ENV_GHIDRA_TRACE_RMI_ADDR = "GHIDRA_TRACE_RMI_ADDR";
public static final String ENV_GHIDRA_TRACE_RMI_HOST = "GHIDRA_TRACE_RMI_HOST";
public static final String ENV_GHIDRA_TRACE_RMI_PORT = "GHIDRA_TRACE_RMI_PORT";
public static final String AT_TITLE = "@title";
public static final String AT_DESC = "@desc";
public static final String AT_MENU_PATH = "@menu-path";
@ -69,10 +74,29 @@ public abstract class ScriptAttributesParser {
public static final String MSGPAT_INVALID_ARGS_SYNTAX =
"%s: Invalid %s syntax. Use \"Display\" \"Tool Tip\"";
public static final String MSGPAT_INVALID_TTY_SYNTAX =
"%s: Invalid %s syntax. Use TTY_TARGET [if env:OPT_EXTRA_TTY]";
"%s: Invalid %s syntax. Use TTY_TARGET [if env:OPT [== VAL]]";
public static final String MSGPAT_INVALID_TTY_NO_PARAM =
"%s: In %s: No such parameter '%s'";
public static final String MSGPAT_INVALID_TTY_NOT_BOOL =
"%s: In %s: Parameter '%s' must have bool type";
public static final String MSGPAT_INVALID_TTY_BAD_VAL =
"%s: In %s: Parameter '%s' has type %s, but '%s' cannot be parsed as such";
public static final String MSGPAT_INVALID_TIMEOUT_SYNTAX = "" +
"%s: Invalid %s syntax. Use [milliseconds]";
public static class ParseException extends Exception {
private Location loc;
public ParseException(Location loc, String message) {
super(message);
this.loc = loc;
}
public Location getLocation() {
return loc;
}
}
protected record Location(String fileName, int lineNo) {
@Override
public String toString() {
@ -80,31 +104,36 @@ public abstract class ScriptAttributesParser {
}
}
protected interface OptType<T> {
static OptType<?> parse(Location loc, String typeName,
Map<String, UserType<?>> userEnums) {
protected interface OptType<T> extends ValStr.Decoder<T> {
static OptType<?> parse(Location loc, String typeName, Map<String, UserType<?>> userEnums)
throws ParseException {
OptType<?> type = BaseType.parseNoErr(typeName);
if (type == null) {
type = userEnums.get(typeName);
}
if (type == null) { // still
Msg.error(ScriptAttributesParser.class,
"%s: Invalid type %s".formatted(loc, typeName));
return null;
throw new ParseException(loc, "%s: Invalid type %s".formatted(loc, typeName));
}
return type;
}
default TypeAndDefault<T> withCastDefault(Object defaultValue) {
return new TypeAndDefault<>(this, cls().cast(defaultValue));
default TypeAndDefault<T> withCastDefault(ValStr<Object> defaultValue) {
return new TypeAndDefault<>(this, ValStr.cast(cls(), defaultValue));
}
Class<T> cls();
T decode(Location loc, String str);
default T decode(Location loc, String str) throws ParseException {
try {
return decode(str);
}
catch (Exception e) {
throw new ParseException(loc, "%s: %s".formatted(loc, e.getMessage()));
}
}
ParameterDescription<T> createParameter(String name, T defaultValue, String display,
String description);
LaunchParameter<T> createParameter(String name, String display, String description,
boolean required, ValStr<T> defaultValue);
}
protected interface BaseType<T> extends OptType<T> {
@ -120,12 +149,10 @@ public abstract class ScriptAttributesParser {
};
}
public static BaseType<?> parse(Location loc, String typeName) {
public static BaseType<?> parse(Location loc, String typeName) throws ParseException {
BaseType<?> type = parseNoErr(typeName);
if (type == null) {
Msg.error(ScriptAttributesParser.class,
"%s: Invalid base type %s".formatted(loc, typeName));
return null;
throw new ParseException(loc, "%s: Invalid base type %s".formatted(loc, typeName));
}
return type;
}
@ -137,7 +164,7 @@ public abstract class ScriptAttributesParser {
}
@Override
public String decode(Location loc, String str) {
public String decode(String str) {
return str;
}
};
@ -149,18 +176,14 @@ public abstract class ScriptAttributesParser {
}
@Override
public BigInteger decode(Location loc, String str) {
public BigInteger decode(String str) {
try {
if (str.startsWith("0x")) {
return new BigInteger(str.substring(2), 16);
}
return new BigInteger(str);
return NumericUtilities.decodeBigInteger(str);
}
catch (NumberFormatException e) {
Msg.error(ScriptAttributesParser.class,
("%s: Invalid int for %s: %s. You may prefix with 0x for hexadecimal. " +
"Otherwise, decimal is used.").formatted(loc, AT_ENV, str));
return null;
throw new IllegalArgumentException(
"Invalid int %s. Prefixes 0x, 0b, and 0 (octal) are allowed."
.formatted(str));
}
}
};
@ -172,17 +195,16 @@ public abstract class ScriptAttributesParser {
}
@Override
public Boolean decode(Location loc, String str) {
Boolean result = switch (str) {
public Boolean decode(String str) {
Boolean result = switch (str.trim().toLowerCase()) {
case "true" -> true;
case "false" -> false;
default -> null;
};
if (result == null) {
Msg.error(ScriptAttributesParser.class,
"%s: Invalid bool for %s: %s. Only true or false (in lower case) is allowed."
.formatted(loc, AT_ENV, str));
return null;
throw new IllegalArgumentException(
"Invalid bool for %s: %s. Only true or false is allowed."
.formatted(AT_ENV, str));
}
return result;
}
@ -195,7 +217,7 @@ public abstract class ScriptAttributesParser {
}
@Override
public Path decode(Location loc, String str) {
public Path decode(String str) {
return Paths.get(str);
}
};
@ -207,7 +229,7 @@ public abstract class ScriptAttributesParser {
}
@Override
public PathIsDir decode(Location loc, String str) {
public PathIsDir decode(String str) {
return new PathIsDir(Paths.get(str));
}
};
@ -219,7 +241,7 @@ public abstract class ScriptAttributesParser {
}
@Override
public PathIsFile decode(Location loc, String str) {
public PathIsFile decode(String str) {
return new PathIsFile(Paths.get(str));
}
};
@ -228,11 +250,15 @@ public abstract class ScriptAttributesParser {
return new UserType<>(this, choices.stream().map(cls()::cast).toList());
}
default UserType<T> withChoices(List<T> choices) {
return new UserType<>(this, choices);
}
@Override
default ParameterDescription<T> createParameter(String name, T defaultValue, String display,
String description) {
return ParameterDescription.create(cls(), name, false, defaultValue, display,
description);
default LaunchParameter<T> createParameter(String name, String display, String description,
boolean required, ValStr<T> defaultValue) {
return LaunchParameter.create(cls(), name, display, description, required, defaultValue,
this);
}
}
@ -243,62 +269,57 @@ public abstract class ScriptAttributesParser {
}
@Override
public T decode(Location loc, String str) {
return base.decode(loc, str);
public T decode(String str) {
return base.decode(str);
}
@Override
public ParameterDescription<T> createParameter(String name, T defaultValue, String display,
String description) {
return ParameterDescription.choices(cls(), name, choices, defaultValue, display,
description);
public LaunchParameter<T> createParameter(String name, String display, String description,
boolean required, ValStr<T> defaultValue) {
return LaunchParameter.choices(cls(), name, display, description, choices,
defaultValue);
}
}
protected record TypeAndDefault<T>(OptType<T> type, T defaultValue) {
protected record TypeAndDefault<T>(OptType<T> type, ValStr<T> defaultValue) {
public static TypeAndDefault<?> parse(Location loc, String typeName, String defaultString,
Map<String, UserType<?>> userEnums) {
Map<String, UserType<?>> userEnums) throws ParseException {
OptType<?> tac = OptType.parse(loc, typeName, userEnums);
if (tac == null) {
return null;
}
Object value = tac.decode(loc, defaultString);
if (value == null) {
return null;
}
return tac.withCastDefault(value);
return tac.withCastDefault(new ValStr<>(value, defaultString));
}
public ParameterDescription<T> createParameter(String name, String display,
String description) {
return type.createParameter(name, defaultValue, display, description);
public LaunchParameter<T> createParameter(String name, String display, String description) {
return type.createParameter(name, display, description, false, defaultValue);
}
}
public interface TtyCondition {
boolean isActive(Map<String, ?> args);
boolean isActive(Map<String, ValStr<?>> args);
}
enum ConstTtyCondition implements TtyCondition {
ALWAYS {
@Override
public boolean isActive(Map<String, ?> args) {
public boolean isActive(Map<String, ValStr<?>> args) {
return true;
}
},
}
record EqualsTtyCondition(String key, String repr) implements TtyCondition {
record EqualsTtyCondition(LaunchParameter<?> param, Object value) implements TtyCondition {
@Override
public boolean isActive(Map<String, ?> args) {
return Objects.toString(args.get(key)).equals(repr);
public boolean isActive(Map<String, ValStr<?>> args) {
ValStr<?> valStr = param.get(args);
return Objects.equals(valStr == null ? null : valStr.val(), value);
}
}
record BoolTtyCondition(String key) implements TtyCondition {
record BoolTtyCondition(LaunchParameter<Boolean> param) implements TtyCondition {
@Override
public boolean isActive(Map<String, ?> args) {
return args.get(key) instanceof Boolean b && b.booleanValue();
public boolean isActive(Map<String, ValStr<?>> args) {
ValStr<Boolean> valStr = param.get(args);
return valStr != null && valStr.val();
}
}
@ -318,9 +339,8 @@ public abstract class ScriptAttributesParser {
public record ScriptAttributes(String title, String description, List<String> menuPath,
String menuGroup, String menuOrder, Icon icon, HelpLocation helpLocation,
Map<String, ParameterDescription<?>> parameters, Map<String, TtyCondition> extraTtys,
int timeoutMillis, boolean noImage) {
}
Map<String, LaunchParameter<?>> parameters, Map<String, TtyCondition> extraTtys,
int timeoutMillis, boolean noImage) {}
/**
* Convert an arguments map into a command line and environment variables
@ -335,34 +355,35 @@ public abstract class ScriptAttributesParser {
* @param address the address of the listening TraceRmi socket
*/
public static void processArguments(List<String> commandLine, Map<String, String> env,
File script, Map<String, ParameterDescription<?>> parameters, Map<String, ?> args,
File script, Map<String, LaunchParameter<?>> parameters, Map<String, ValStr<?>> args,
SocketAddress address) {
commandLine.add(script.getAbsolutePath());
env.put("GHIDRA_HOME", Application.getInstallationDirectory().getAbsolutePath());
env.put(ENV_GHIDRA_HOME, Application.getInstallationDirectory().getAbsolutePath());
if (address != null) {
env.put("GHIDRA_TRACE_RMI_ADDR", sockToString(address));
env.put(ENV_GHIDRA_TRACE_RMI_ADDR, sockToString(address));
if (address instanceof InetSocketAddress tcp) {
env.put("GHIDRA_TRACE_RMI_HOST", tcp.getAddress().getHostAddress());
env.put("GHIDRA_TRACE_RMI_PORT", Integer.toString(tcp.getPort()));
env.put(ENV_GHIDRA_TRACE_RMI_HOST, tcp.getAddress().getHostAddress());
env.put(ENV_GHIDRA_TRACE_RMI_PORT, Integer.toString(tcp.getPort()));
}
}
ParameterDescription<?> paramDesc;
for (int i = 1; (paramDesc = parameters.get("arg:" + i)) != null; i++) {
commandLine.add(Objects.toString(paramDesc.get(args)));
LaunchParameter<?> param;
for (int i = 1; (param = parameters.get("arg:" + i)) != null; i++) {
// Don't use ValStr.str here. I'd like the script's input normalized
commandLine.add(Objects.toString(param.get(args).val()));
}
paramDesc = parameters.get("args");
if (paramDesc != null) {
commandLine.addAll(ShellUtils.parseArgs((String) paramDesc.get(args)));
param = parameters.get("args");
if (param != null) {
commandLine.addAll(ShellUtils.parseArgs(param.get(args).str()));
}
for (Entry<String, ParameterDescription<?>> ent : parameters.entrySet()) {
for (Entry<String, LaunchParameter<?>> ent : parameters.entrySet()) {
String key = ent.getKey();
if (key.startsWith(PREFIX_ENV)) {
String varName = key.substring(PREFIX_ENV.length());
env.put(varName, Objects.toString(ent.getValue().get(args)));
env.put(varName, Objects.toString(ent.getValue().get(args).val()));
}
}
}
@ -376,7 +397,7 @@ public abstract class ScriptAttributesParser {
private String iconId;
private HelpLocation helpLocation;
private final Map<String, UserType<?>> userTypes = new HashMap<>();
private final Map<String, ParameterDescription<?>> parameters = new LinkedHashMap<>();
private final Map<String, LaunchParameter<?>> parameters = new LinkedHashMap<>();
private final Map<String, TtyCondition> extraTtys = new LinkedHashMap<>();
private int timeoutMillis = AbstractTraceRmiLaunchOffer.DEFAULT_TIMEOUT_MILLIS;
private boolean noImage = false;
@ -401,9 +422,17 @@ public abstract class ScriptAttributesParser {
*/
protected abstract String removeDelimiter(String line);
public ScriptAttributes parseFile(File script) throws FileNotFoundException {
/**
* Parse the header from the give input stream
*
* @param stream the stream from of the input stream file
* @param scriptName the name of the script file
* @return the parsed attributes
* @throws IOException if there was an issue reading the stream
*/
public ScriptAttributes parseStream(InputStream stream, String scriptName) throws IOException {
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(new FileInputStream(script)))) {
new BufferedReader(new InputStreamReader(stream))) {
String line;
for (int lineNo = 1; (line = reader.readLine()) != null; lineNo++) {
if (ignoreLine(lineNo, line)) {
@ -413,9 +442,22 @@ public abstract class ScriptAttributesParser {
if (comment == null) {
break;
}
parseComment(new Location(script.getName(), lineNo), comment);
parseComment(new Location(scriptName, lineNo), comment);
}
return validate(script.getName());
return validate(scriptName);
}
}
/**
* Parse the header of the given script file
*
* @param script the file
* @return the parsed attributes
* @throws FileNotFoundException if the script file could not be found
*/
public ScriptAttributes parseFile(File script) throws FileNotFoundException {
try {
return parseStream(new FileInputStream(script), script.getName());
}
catch (FileNotFoundException e) {
// Avoid capture by IOException
@ -468,7 +510,7 @@ public abstract class ScriptAttributesParser {
protected void parseTitle(Location loc, String str) {
if (title != null) {
Msg.warn(this, "%s: Duplicate @title".formatted(loc));
reportWarning("%s: Duplicate %s".formatted(loc, AT_TITLE));
}
title = str;
}
@ -483,161 +525,222 @@ public abstract class ScriptAttributesParser {
protected void parseMenuPath(Location loc, String str) {
if (menuPath != null) {
Msg.warn(this, "%s: Duplicate %s".formatted(loc, AT_MENU_PATH));
reportWarning("%s: Duplicate %s".formatted(loc, AT_MENU_PATH));
}
menuPath = List.of(str.trim().split("\\."));
if (menuPath.isEmpty()) {
Msg.error(this,
reportError(
"%s: Empty %s. Ignoring.".formatted(loc, AT_MENU_PATH));
}
}
protected void parseMenuGroup(Location loc, String str) {
if (menuGroup != null) {
Msg.warn(this, "%s: Duplicate %s".formatted(loc, AT_MENU_GROUP));
reportWarning("%s: Duplicate %s".formatted(loc, AT_MENU_GROUP));
}
menuGroup = str;
}
protected void parseMenuOrder(Location loc, String str) {
if (menuOrder != null) {
Msg.warn(this, "%s: Duplicate %s".formatted(loc, AT_MENU_ORDER));
reportWarning("%s: Duplicate %s".formatted(loc, AT_MENU_ORDER));
}
menuOrder = str;
}
protected void parseIcon(Location loc, String str) {
if (iconId != null) {
Msg.warn(this, "%s: Duplicate %s".formatted(loc, AT_ICON));
reportWarning("%s: Duplicate %s".formatted(loc, AT_ICON));
}
iconId = str.trim();
if (!Gui.hasIcon(iconId)) {
Msg.error(this,
reportError(
"%s: Icon id %s not registered in the theme".formatted(loc, iconId));
}
}
protected void parseHelp(Location loc, String str) {
if (helpLocation != null) {
Msg.warn(this, "%s: Duplicate %s".formatted(loc, AT_HELP));
reportWarning("%s: Duplicate %s".formatted(loc, AT_HELP));
}
String[] parts = str.trim().split("#", 2);
if (parts.length != 2) {
Msg.error(this, MSGPAT_INVALID_HELP_SYNTAX.formatted(loc, AT_HELP));
reportError(MSGPAT_INVALID_HELP_SYNTAX.formatted(loc, AT_HELP));
return;
}
helpLocation = new HelpLocation(parts[0].trim(), parts[1].trim());
}
protected <T> UserType<T> parseEnumChoices(Location loc, BaseType<T> baseType,
List<String> choiceParts) {
List<T> choices = new ArrayList<>();
boolean err = false;
for (String s : choiceParts) {
try {
choices.add(baseType.decode(loc, s));
}
catch (ParseException e) {
reportError(e.getMessage());
}
}
if (err) {
return null;
}
return baseType.withChoices(choices);
}
protected void parseEnum(Location loc, String str) {
List<String> parts = ShellUtils.parseArgs(str);
if (parts.size() < 2) {
Msg.error(this, MSGPAT_INVALID_ENUM_SYNTAX.formatted(loc, AT_ENUM));
reportError(MSGPAT_INVALID_ENUM_SYNTAX.formatted(loc, AT_ENUM));
return;
}
String[] nameParts = parts.get(0).split(":", 2);
if (nameParts.length != 2) {
Msg.error(this, MSGPAT_INVALID_ENUM_SYNTAX.formatted(loc, AT_ENUM));
reportError(MSGPAT_INVALID_ENUM_SYNTAX.formatted(loc, AT_ENUM));
return;
}
String name = nameParts[0].trim();
BaseType<?> baseType = BaseType.parse(loc, nameParts[1]);
if (baseType == null) {
BaseType<?> baseType;
try {
baseType = BaseType.parse(loc, nameParts[1]);
}
catch (ParseException e) {
reportError(e.getMessage());
return;
}
List<?> choices = parts.stream().skip(1).map(s -> baseType.decode(loc, s)).toList();
if (choices.contains(null)) {
return;
UserType<?> userType = parseEnumChoices(loc, baseType, parts.subList(1, parts.size()));
if (userType == null) {
return; // errors already reported
}
UserType<?> userType = baseType.withCastChoices(choices);
if (userTypes.put(name, userType) != null) {
Msg.warn(this, "%s: Duplicate %s %s. Replaced.".formatted(loc, AT_ENUM, name));
reportWarning("%s: Duplicate %s %s. Replaced.".formatted(loc, AT_ENUM, name));
}
}
protected void parseEnv(Location loc, String str) {
List<String> parts = ShellUtils.parseArgs(str);
if (parts.size() != 3) {
Msg.error(this, MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
reportError(MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
return;
}
String[] nameParts = parts.get(0).split(":", 2);
if (nameParts.length != 2) {
Msg.error(this, MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
reportError(MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
return;
}
String trimmed = nameParts[0].trim();
String name = PREFIX_ENV + trimmed;
String[] tadParts = nameParts[1].split("=", 2);
if (tadParts.length != 2) {
Msg.error(this, MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
reportError(MSGPAT_INVALID_ENV_SYNTAX.formatted(loc, AT_ENV));
return;
}
TypeAndDefault<?> tad =
TypeAndDefault.parse(loc, tadParts[0].trim(), tadParts[1].trim(), userTypes);
ParameterDescription<?> param = tad.createParameter(name, parts.get(1), parts.get(2));
if (parameters.put(name, param) != null) {
Msg.warn(this, "%s: Duplicate %s %s. Replaced.".formatted(loc, AT_ENV, trimmed));
try {
TypeAndDefault<?> tad =
TypeAndDefault.parse(loc, tadParts[0].trim(), tadParts[1].trim(), userTypes);
LaunchParameter<?> param = tad.createParameter(name, parts.get(1), parts.get(2));
if (parameters.put(name, param) != null) {
reportWarning("%s: Duplicate %s %s. Replaced.".formatted(loc, AT_ENV, trimmed));
}
}
catch (ParseException e) {
reportError(e.getMessage());
}
}
protected void parseArg(Location loc, String str, int argNum) {
List<String> parts = ShellUtils.parseArgs(str);
if (parts.size() != 3) {
Msg.error(this, MSGPAT_INVALID_ARG_SYNTAX.formatted(loc, AT_ARG));
reportError(MSGPAT_INVALID_ARG_SYNTAX.formatted(loc, AT_ARG));
return;
}
String colonType = parts.get(0).trim();
if (!colonType.startsWith(":")) {
Msg.error(this, MSGPAT_INVALID_ARG_SYNTAX.formatted(loc, AT_ARG));
reportError(MSGPAT_INVALID_ARG_SYNTAX.formatted(loc, AT_ARG));
return;
}
OptType<?> type = OptType.parse(loc, colonType.substring(1), userTypes);
if (type == null) {
return;
OptType<?> type;
try {
type = OptType.parse(loc, colonType.substring(1), userTypes);
String name = PREFIX_ARG + argNum;
parameters.put(name,
type.createParameter(name, parts.get(1), parts.get(2), true,
new ValStr<>(null, "")));
}
catch (ParseException e) {
reportError(e.getMessage());
}
String name = PREFIX_ARG + argNum;
parameters.put(name, ParameterDescription.create(type.cls(), name, true, null,
parts.get(1), parts.get(2)));
}
protected void parseArgs(Location loc, String str) {
List<String> parts = ShellUtils.parseArgs(str);
if (parts.size() != 2) {
Msg.error(this, MSGPAT_INVALID_ARGS_SYNTAX.formatted(loc, AT_ARGS));
reportError(MSGPAT_INVALID_ARGS_SYNTAX.formatted(loc, AT_ARGS));
return;
}
ParameterDescription<String> parameter = ParameterDescription.create(String.class,
"args", false, "", parts.get(0), parts.get(1));
LaunchParameter<String> parameter = BaseType.STRING.createParameter(
"args", parts.get(0), parts.get(1), false, ValStr.str(""));
if (parameters.put(KEY_ARGS, parameter) != null) {
Msg.warn(this, "%s: Duplicate %s. Replaced".formatted(loc, AT_ARGS));
reportWarning("%s: Duplicate %s. Replaced".formatted(loc, AT_ARGS));
}
}
protected void putTty(Location loc, String name, TtyCondition condition) {
if (extraTtys.put(name, condition) != null) {
Msg.warn(this, "%s: Duplicate %s. Ignored".formatted(loc, AT_TTY));
reportWarning("%s: Duplicate %s. Ignored".formatted(loc, AT_TTY));
}
}
protected void parseTty(Location loc, String str) {
List<String> parts = ShellUtils.parseArgs(str);
switch (parts.size()) {
case 1:
case 1 -> {
putTty(loc, parts.get(0), ConstTtyCondition.ALWAYS);
return;
case 3:
}
case 3 -> {
if ("if".equals(parts.get(1))) {
putTty(loc, parts.get(0), new BoolTtyCondition(parts.get(2)));
LaunchParameter<?> param = parameters.get(parts.get(2));
if (param == null) {
reportError(
MSGPAT_INVALID_TTY_NO_PARAM.formatted(loc, AT_TTY, parts.get(2)));
return;
}
if (param.type() != Boolean.class) {
reportError(
MSGPAT_INVALID_TTY_NOT_BOOL.formatted(loc, AT_TTY, param.name()));
return;
}
@SuppressWarnings("unchecked")
LaunchParameter<Boolean> asBoolParam = (LaunchParameter<Boolean>) param;
putTty(loc, parts.get(0), new BoolTtyCondition(asBoolParam));
return;
}
case 5:
}
case 5 -> {
if ("if".equals(parts.get(1)) && "==".equals(parts.get(3))) {
putTty(loc, parts.get(0), new EqualsTtyCondition(parts.get(2), parts.get(4)));
return;
LaunchParameter<?> param = parameters.get(parts.get(2));
if (param == null) {
reportError(
MSGPAT_INVALID_TTY_NO_PARAM.formatted(loc, AT_TTY, parts.get(2)));
return;
}
try {
Object value = param.decode(parts.get(4)).val();
putTty(loc, parts.get(0), new EqualsTtyCondition(param, value));
return;
}
catch (Exception e) {
reportError(MSGPAT_INVALID_TTY_BAD_VAL.formatted(loc, AT_TTY,
param.name(), param.type(), parts.get(4)));
return;
}
}
}
}
Msg.error(this, MSGPAT_INVALID_TTY_SYNTAX.formatted(loc, AT_TTY));
reportError(MSGPAT_INVALID_TTY_SYNTAX.formatted(loc, AT_TTY));
}
protected void parseTimeout(Location loc, String str) {
@ -645,7 +748,7 @@ public abstract class ScriptAttributesParser {
timeoutMillis = Integer.parseInt(str);
}
catch (NumberFormatException e) {
Msg.error(this, MSGPAT_INVALID_TIMEOUT_SYNTAX.formatted(loc, AT_TIMEOUT));
reportError(MSGPAT_INVALID_TIMEOUT_SYNTAX.formatted(loc, AT_TIMEOUT));
}
}
@ -654,12 +757,13 @@ public abstract class ScriptAttributesParser {
}
protected void parseUnrecognized(Location loc, String line) {
Msg.warn(this, "%s: Unrecognized metadata: %s".formatted(loc, line));
reportWarning("%s: Unrecognized metadata: %s".formatted(loc, line));
}
protected ScriptAttributes validate(String fileName) {
if (title == null) {
Msg.error(this, "%s is required. Using script file name.".formatted(AT_TITLE));
reportError(
"%s is required. Using script file name: '%s'".formatted(AT_TITLE, fileName));
title = fileName;
}
if (menuPath == null) {
@ -683,4 +787,12 @@ public abstract class ScriptAttributesParser {
private String getDescription() {
return description == null ? null : description.toString();
}
protected void reportWarning(String message) {
Msg.warn(this, message);
}
protected void reportError(String message) {
Msg.error(this, message);
}
}

View file

@ -0,0 +1,86 @@
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.debug.gui.tracermi.launcher;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import ghidra.app.plugin.core.debug.gui.AbstractDebuggerParameterDialog;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.tracermi.LaunchParameter;
import ghidra.framework.options.SaveState;
import ghidra.framework.plugintool.PluginTool;
public class TraceRmiLaunchDialog extends AbstractDebuggerParameterDialog<LaunchParameter<?>> {
public TraceRmiLaunchDialog(PluginTool tool, String title, String buttonText, Icon buttonIcon) {
super(tool, title, buttonText, buttonIcon);
}
@Override
protected String parameterName(LaunchParameter<?> parameter) {
return parameter.name();
}
@Override
protected Class<?> parameterType(LaunchParameter<?> parameter) {
return parameter.type();
}
@Override
protected String parameterLabel(LaunchParameter<?> parameter) {
return parameter.display();
}
@Override
protected String parameterToolTip(LaunchParameter<?> parameter) {
return parameter.description();
}
@Override
protected ValStr<?> parameterDefault(LaunchParameter<?> parameter) {
return parameter.defaultValue();
}
@Override
protected List<?> parameterChoices(LaunchParameter<?> parameter) {
return parameter.choices();
}
@Override
protected Map<String, ValStr<?>> validateArguments(Map<String, LaunchParameter<?>> parameters,
Map<String, ValStr<?>> arguments) {
return LaunchParameter.validateArguments(parameters, arguments);
}
@Override
protected void parameterSaveValue(LaunchParameter<?> parameter, SaveState state, String key,
ValStr<?> value) {
state.putString(key, value.str());
}
@Override
protected ValStr<?> parameterLoadValue(LaunchParameter<?> parameter, SaveState state,
String key) {
String str = state.getString(key, null);
if (str == null) {
return null;
}
return parameter.decode(str);
}
}

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,6 +22,7 @@ import java.util.List;
import java.util.Map;
import ghidra.app.plugin.core.debug.gui.tracermi.launcher.ScriptAttributesParser.ScriptAttributes;
import ghidra.debug.api.ValStr;
import ghidra.program.model.listing.Program;
/**
@ -32,6 +33,8 @@ import ghidra.program.model.listing.Program;
* {@link ScriptAttributesParser}.
*/
public class UnixShellScriptTraceRmiLaunchOffer extends AbstractScriptTraceRmiLaunchOffer {
public static final String HASH = "#";
public static final int HASH_LEN = HASH.length();
public static final String SHEBANG = "#!";
/**
@ -56,10 +59,10 @@ public class UnixShellScriptTraceRmiLaunchOffer extends AbstractScriptTraceRmiLa
@Override
protected String removeDelimiter(String line) {
String stripped = line.stripLeading();
if (!stripped.startsWith("#")) {
if (!stripped.startsWith(HASH)) {
return null;
}
return stripped.substring(1);
return stripped.substring(HASH_LEN);
}
};
ScriptAttributes attrs = parser.parseFile(script);
@ -68,15 +71,7 @@ public class UnixShellScriptTraceRmiLaunchOffer extends AbstractScriptTraceRmiLa
}
private UnixShellScriptTraceRmiLaunchOffer(TraceRmiLauncherServicePlugin plugin,
Program program,
File script, String configName, ScriptAttributes attrs) {
Program program, File script, String configName, ScriptAttributes attrs) {
super(plugin, program, script, configName, attrs);
}
@Override
protected void prepareSubprocess(List<String> commandLine, Map<String, String> env,
Map<String, ?> args, SocketAddress address) {
ScriptAttributesParser.processArguments(commandLine, env, script, attrs.parameters(), args,
address);
}
}

View file

@ -54,7 +54,6 @@ import ghidra.program.model.address.*;
import ghidra.program.model.lang.*;
import ghidra.program.util.DefaultLanguageService;
import ghidra.rmi.trace.TraceRmi.*;
import ghidra.rmi.trace.TraceRmi.Compiler;
import ghidra.rmi.trace.TraceRmi.Language;
import ghidra.trace.database.DBTrace;
import ghidra.trace.model.Lifespan;
@ -129,11 +128,9 @@ public class TraceRmiHandler implements TraceRmiConnection {
}
}
protected record Tid(DoId doId, int txId) {
}
protected record Tid(DoId doId, int txId) {}
protected record OpenTx(Tid txId, Transaction tx, boolean undoable) {
}
protected record OpenTx(Tid txId, Transaction tx, boolean undoable) {}
protected class OpenTraceMap {
private final Map<DoId, OpenTrace> byId = new HashMap<>();
@ -388,7 +385,7 @@ public class TraceRmiHandler implements TraceRmiConnection {
protected static void sendDelimited(OutputStream out, RootMessage msg, long dbgSeq)
throws IOException {
ByteBuffer buf = ByteBuffer.allocate(4);
ByteBuffer buf = ByteBuffer.allocate(Integer.BYTES);
buf.putInt(msg.getSerializedSize());
out.write(buf.array());
msg.writeTo(out);
@ -867,6 +864,9 @@ public class TraceRmiHandler implements TraceRmiConnection {
throws InvalidNameException, IOException, CancelledException {
DomainFolder traces = getOrCreateNewTracesFolder();
List<String> path = sanitizePath(req.getPath().getPath());
if (path.isEmpty()) {
throw new IllegalArgumentException("CreateTrace: path (name) cannot be empty");
}
DomainFolder folder = createFolders(traces, path.subList(0, path.size() - 1));
CompilerSpec cs = requireCompilerSpec(req.getLanguage(), req.getCompiler());
DBTrace trace = new DBTrace(path.get(path.size() - 1), cs, this);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -37,6 +37,7 @@ import ghidra.dbg.target.schema.TargetObjectSchema.SchemaName;
import ghidra.dbg.util.PathMatcher;
import ghidra.dbg.util.PathPredicates;
import ghidra.dbg.util.PathPredicates.Align;
import ghidra.debug.api.ValStr;
import ghidra.debug.api.model.DebuggerObjectActionContext;
import ghidra.debug.api.model.DebuggerSingleObjectPathActionContext;
import ghidra.debug.api.target.ActionName;
@ -345,25 +346,15 @@ public class TraceRmiTarget extends AbstractTarget {
}
private Map<String, Object> promptArgs(RemoteMethod method, Map<String, Object> defaults) {
SchemaContext ctx = getSchemaContext();
/**
* TODO: RemoteMethod parameter descriptions should also use ValStr. This map conversion
* stuff is getting onerous and hacky.
*/
Map<String, ValStr<?>> defs = ValStr.fromPlainMap(defaults);
RemoteMethodInvocationDialog dialog = new RemoteMethodInvocationDialog(tool,
method.display(), method.display(), null);
while (true) {
for (RemoteParameter param : method.parameters().values()) {
Object val = defaults.get(param.name());
if (val != null) {
Class<?> type = ctx.getSchema(param.type()).getType();
dialog.setMemorizedArgument(param.name(), type.asSubclass(Object.class),
val);
}
}
Map<String, Object> args = dialog.promptArguments(ctx, method.parameters(), defaults);
if (args == null) {
// Cancelled
return null;
}
return args;
}
getSchemaContext(), method.display(), method.display(), null);
Map<String, ValStr<?>> args = dialog.promptArguments(method.parameters(), defs, defs);
return args == null ? null : ValStr.toPlainMap(args);
}
private CompletableFuture<?> invokeMethod(boolean prompt, RemoteMethod method,

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -30,7 +30,7 @@ import org.junit.Test;
import generic.Unique;
import ghidra.app.plugin.core.debug.gui.AbstractGhidraHeadedDebuggerTest;
import ghidra.app.plugin.core.debug.gui.objects.components.InvocationDialogHelper;
import ghidra.app.plugin.core.debug.gui.InvocationDialogHelper;
import ghidra.app.plugin.core.debug.gui.tracermi.connection.tree.*;
import ghidra.app.plugin.core.debug.service.control.DebuggerControlServicePlugin;
import ghidra.app.plugin.core.debug.service.tracermi.TestTraceRmiClient;
@ -60,13 +60,17 @@ public class TraceRmiConnectionManagerProviderTest extends AbstractGhidraHeadedD
provider = waitForComponentProvider(TraceRmiConnectionManagerProvider.class);
}
InvocationDialogHelper<?, ?> waitDialog() {
return InvocationDialogHelper.waitFor(TraceRmiConnectDialog.class);
}
@Test
public void testActionAccept() throws Exception {
performEnabledAction(provider, provider.actionConnectAccept, false);
InvocationDialogHelper helper = InvocationDialogHelper.waitFor();
InvocationDialogHelper<?, ?> helper = waitDialog();
helper.dismissWithArguments(Map.ofEntries(
Map.entry("address", "localhost"),
Map.entry("port", 0)));
helper.entry("address", "localhost"),
helper.entry("port", 0)));
waitForPass(() -> Unique.assertOne(traceRmiService.getAllAcceptors()));
}
@ -78,10 +82,10 @@ public class TraceRmiConnectionManagerProviderTest extends AbstractGhidraHeadedD
throw new AssertionError();
}
performEnabledAction(provider, provider.actionConnectOutbound, false);
InvocationDialogHelper helper = InvocationDialogHelper.waitFor();
InvocationDialogHelper<?, ?> helper = waitDialog();
helper.dismissWithArguments(Map.ofEntries(
Map.entry("address", sockaddr.getHostString()),
Map.entry("port", sockaddr.getPort())));
helper.entry("address", sockaddr.getHostString()),
helper.entry("port", sockaddr.getPort())));
try (SocketChannel channel = server.accept()) {
TestTraceRmiClient client = new TestTraceRmiClient(channel);
client.sendNegotiate("Test client");
@ -94,10 +98,10 @@ public class TraceRmiConnectionManagerProviderTest extends AbstractGhidraHeadedD
@Test
public void testActionStartServer() throws Exception {
performEnabledAction(provider, provider.actionStartServer, false);
InvocationDialogHelper helper = InvocationDialogHelper.waitFor();
InvocationDialogHelper<?, ?> helper = waitDialog();
helper.dismissWithArguments(Map.ofEntries(
Map.entry("address", "localhost"),
Map.entry("port", 0)));
helper.entry("address", "localhost"),
helper.entry("port", 0)));
waitForPass(() -> assertTrue(traceRmiService.isServerStarted()));
waitForPass(() -> assertFalse(provider.actionStartServer.isEnabled()));