Search in sources :

Example 1 with IEnvironmentVariable

use of org.eclipse.cdt.core.envvar.IEnvironmentVariable in project usbdm-eclipse-plugins by podonoghue.

the class DisassembleCFileHandler method execute.

// public static void pipeStream(InputStream input, OutputStream output)
// throws IOException {
// 
// byte buffer[] = new byte[1024];
// int numRead = 0;
// 
// while (input.available() > 0) {
// numRead = input.read(buffer);
// output.write(buffer, 0, numRead);
// }
// output.flush();
// }
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    String os = System.getProperty("os.name");
    boolean isLinux = (os != null) && os.toUpperCase().contains("LINUX");
    Object source = HandlerUtil.getCurrentSelection(event);
    // System.err.println("Event source = "+source.toString()+"\n class = "+source.getClass().toString());
    if (!(source instanceof TreeSelection)) {
        // System.err.println("Source is not an instance of TreeSelection");
        return null;
    }
    TreeSelection selection = (TreeSelection) source;
    if (!(selection.getFirstElement() instanceof IBinary)) {
        // System.err.println("Selection.getFirstElement() is not an instance of org.eclipse.cdt.core.model.IBinary");
        return null;
    }
    IBinary binary = (IBinary) selection.getFirstElement();
    IResource resource = binary.getUnderlyingResource();
    IPath resourcePath = resource.getLocation();
    IPath dissassemblyPath = resourcePath.removeFileExtension().addFileExtension("lis");
    // Get Environment (path etc)
    CoreModel cdtCoreModel = org.eclipse.cdt.core.model.CoreModel.getDefault();
    ICProjectDescription cProjectDescription = cdtCoreModel.getProjectDescription(resource.getProject());
    ICConfigurationDescription cConfigurationDescription = cProjectDescription.getActiveConfiguration();
    IContributedEnvironment contributedEnvironment = CCorePlugin.getDefault().getBuildEnvironmentManager().getContributedEnvironment();
    IEnvironmentVariable[] environmentVariablesArray = contributedEnvironment.getVariables(cConfigurationDescription);
    HashMap<String, String> environmentMap = new HashMap<String, String>();
    for (IEnvironmentVariable ev : environmentVariablesArray) {
        String name = ev.getName();
        if ((!isLinux) && name.equals("PATH")) {
            name = "Path";
        }
        // System.err.println("Adding Environment variable: "+name+" => "+ev.getValue());
        environmentMap.put(name, ev.getValue());
    }
    // String resourceName = resource.getName();
    // System.err.println("resourceName = "+resourceName);
    IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(resource);
    IConfiguration configuration = buildInfo.getDefaultConfiguration();
    // System.err.println("configuration = "+configuration);
    // Find lister tool in configuration
    ITool[] toolArray = configuration.getTools();
    ITool tool = null;
    for (ITool t : toolArray) {
        Pattern p = Pattern.compile("net\\.sourceforge\\.usbdm\\.cdt\\..*\\.toolchain\\.lister\\..*");
        if (p.matcher(t.getId()).matches()) {
            tool = configuration.getTool(t.getId());
            break;
        }
    }
    if (tool == null) {
        return null;
    }
    // System.err.println("tool.getName = "+tool.getName());
    // System.err.println("tool.getToolCommand = "+tool.getToolCommand());
    // Get command line generator
    IManagedCommandLineGenerator commandLineGenerator = tool.getCommandLineGenerator();
    // Get command line
    try {
        String[] inputs = { resourcePath.lastSegment() };
        IManagedCommandLineInfo commandLineInfo = commandLineGenerator.generateCommandLineInfo(tool, tool.getToolCommand(), tool.getToolCommandFlags(resourcePath, dissassemblyPath), "", ">", dissassemblyPath.lastSegment(), inputs, "${COMMAND} ${INPUTS} ${FLAGS} ${OUTPUT_FLAG}${OUTPUT_PREFIX}${OUTPUT}");
        // System.err.println("cl.toString() = "+commandLineInfo.toString());
        // System.err.println("cl.getCommandLine() = "+commandLineInfo.getCommandLine());
        String[] commandArray = null;
        if (isLinux) {
            // Construct command (Use cmd for PATH changes!)
            ArrayList<String> command = new ArrayList<String>(20);
            command.add("/bin/sh");
            command.add("-c");
            command.add(commandLineInfo.getCommandLine());
            commandArray = (String[]) command.toArray(new String[command.size()]);
        } else {
            // Construct command (Use cmd for PATH changes!)
            ArrayList<String> command = new ArrayList<String>(20);
            command.add("cmd.exe");
            command.add("/C");
            command.add(commandLineInfo.getCommandLine());
            commandArray = (String[]) command.toArray(new String[command.size()]);
        }
        // Run command
        // System.err.println("Running...");
        ProcessBuilder pb = new ProcessBuilder(commandArray);
        pb.environment().putAll(environmentMap);
        File commandFile = findExecutableOnPath(pb.environment().get("PATH"), commandLineInfo.getCommandName());
        if (commandFile != null) {
        // System.err.println("commandFile.toPath() = "+ commandFile.toPath());
        // System.err.println("pwd = "+ resourcePath.removeLastSegments(1).toFile());
        }
        // System.err.println("=================== Environment variables ===================");
        // for (String envName : pb.environment().keySet()) {
        // System.err.println("Environment variable: "+envName+" => "+pb.environment().get(envName));
        // }
        // System.err.println("=================== End of Environment variables ===================");
        pb.redirectInput(Redirect.INHERIT);
        pb.redirectError(Redirect.INHERIT);
        pb.redirectOutput(Redirect.INHERIT);
        pb.directory(resourcePath.removeLastSegments(1).toFile());
        // System.err.println("WD =" + pb.directory());
        Process p = pb.start();
        // System.err.println("Waiting...");
        p.waitFor();
    // System.err.println("Exit value = " + p.waitFor());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (BuildException e) {
        e.printStackTrace();
    }
    try {
        // Refresh parent directory so file is visible
        resource.getParent().refreshLocal(1, null);
    } catch (CoreException e) {
        e.printStackTrace();
    }
    try {
        // Open disassembled file in editor
        IPath asmPath = resource.getFullPath().removeFileExtension().addFileExtension("lis");
        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        IDE.openEditor(page, ResourcesPlugin.getWorkspace().getRoot().getFile(asmPath));
    } catch (PartInitException e) {
        e.printStackTrace();
    }
    // System.err.println("Completed");
    return null;
}
Also used : ICProjectDescription(org.eclipse.cdt.core.settings.model.ICProjectDescription) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TreeSelection(org.eclipse.jface.viewers.TreeSelection) PartInitException(org.eclipse.ui.PartInitException) Pattern(java.util.regex.Pattern) IPath(org.eclipse.core.runtime.IPath) IManagedCommandLineGenerator(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator) IBinary(org.eclipse.cdt.core.model.IBinary) IOException(java.io.IOException) ITool(org.eclipse.cdt.managedbuilder.core.ITool) IContributedEnvironment(org.eclipse.cdt.core.envvar.IContributedEnvironment) IManagedBuildInfo(org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo) CoreException(org.eclipse.core.runtime.CoreException) IManagedCommandLineInfo(org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo) CoreModel(org.eclipse.cdt.core.model.CoreModel) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) ICConfigurationDescription(org.eclipse.cdt.core.settings.model.ICConfigurationDescription) BuildException(org.eclipse.cdt.managedbuilder.core.BuildException) IConfiguration(org.eclipse.cdt.managedbuilder.core.IConfiguration) File(java.io.File) IResource(org.eclipse.core.resources.IResource)

Example 2 with IEnvironmentVariable

use of org.eclipse.cdt.core.envvar.IEnvironmentVariable in project arduino-eclipse-plugin by Sloeber.

the class CompileOptions method save.

/**
 * save the compilation options in this configuration description.
 *
 * @param configuration
 *            must be a valid configuration description
 */
public void save(ICConfigurationDescription configuration) {
    CompileOptions curOptions = new CompileOptions(configuration);
    if (needsDirtyFlag(curOptions)) {
        IProject project = configuration.getProjectDescription().getProject();
        Helpers.setDirtyFlag(project, configuration);
    }
    IEnvironmentVariableManager envManager = CCorePlugin.getDefault().getBuildEnvironmentManager();
    IContributedEnvironment contribEnv = envManager.getContributedEnvironment();
    IEnvironmentVariable var = new EnvironmentVariable(ENV_KEY_JANTJE_WARNING_LEVEL, this.myWarningLevel.toString());
    contribEnv.addVariable(var, configuration);
    if (this.isWarningLevel()) {
        var = new EnvironmentVariable(ENV_KEY_WARNING_LEVEL_OFF, ENV_KEY_WARNING_LEVEL_ON);
        contribEnv.addVariable(var, configuration);
    }
    if (this.myAlternativeSizeCommand) {
        var = new EnvironmentVariable(ENV_KEY_JANTJE_SIZE_SWITCH, // $NON-NLS-1$
        "${" + ENV_KEY_JANTJE_SIZE_COMMAND + // $NON-NLS-1$
        "}");
        contribEnv.addVariable(var, configuration);
    } else {
        var = new EnvironmentVariable(ENV_KEY_JANTJE_SIZE_SWITCH, // $NON-NLS-1$
        "${" + Common.get_ENV_KEY_RECIPE(Const.ACTION_SIZE) + // $NON-NLS-1$
        "}");
        contribEnv.addVariable(var, configuration);
    }
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ADDITIONAL_COMPILE_OPTIONS, this.my_C_andCPP_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ADDITIONAL_CPP_COMPILE_OPTIONS, this.my_CPP_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ADDITIONAL_C_COMPILE_OPTIONS, this.my_C_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ASSEMBLY_COMPILE_OPTIONS, this.my_Assembly_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ARCHIVE_COMPILE_OPTIONS, this.my_Archive_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_LINK_COMPILE_OPTIONS, this.my_Link_CompileOptions);
    contribEnv.addVariable(var, configuration);
    var = new EnvironmentVariable(ENV_KEY_JANTJE_ALL_COMPILE_OPTIONS, this.my_All_CompileOptions);
    contribEnv.addVariable(var, configuration);
}
Also used : IContributedEnvironment(org.eclipse.cdt.core.envvar.IContributedEnvironment) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) EnvironmentVariable(org.eclipse.cdt.core.envvar.EnvironmentVariable) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) IEnvironmentVariableManager(org.eclipse.cdt.core.envvar.IEnvironmentVariableManager) IProject(org.eclipse.core.resources.IProject)

Example 3 with IEnvironmentVariable

use of org.eclipse.cdt.core.envvar.IEnvironmentVariable in project arduino-eclipse-plugin by Sloeber.

the class Helpers method setTheEnvironmentVariablesPostProcessing.

/**
 * Following post processing is done
 *
 * CDT uses different keys to identify the input and output files then the
 * arduino recipes. Therefore I split the arduino recipes into parts (based on
 * the arduino keys) and connect them again in the plugin.xml using the CDT
 * keys. This code assumes that the command is in following order ${first part}
 * ${files} ${second part} [${ARCHIVE_FILE} ${third part}] with [optional]
 *
 * Secondly The handling of the upload variables is done differently in arduino
 * than here. This is taken care of here. for example the output of this input
 * tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose}
 * is changed as if it were the output of this input
 * tools.avrdude.upload.pattern="{tools.avrdude.cmd.path}"
 * "-C{tools.avrdude.config.path}" {tools.avrdude.upload.verbose}
 *
 * thirdly if a programmer is selected different from default some extra actions
 * are done here so no special code is needed to handle programmers
 *
 * Fourthly The build path for the core is {BUILD.PATH}/core/core in sloeber
 * where it is {BUILD.PATH}/core/ in arduino world and used to be {BUILD.PATH}/
 * This only gives problems in the link command as sometimes there are hardcoded
 * links to some sys files so ${A.BUILD.PATH}/core/sys* ${A.BUILD.PATH}/sys* is
 * replaced with ${A.BUILD.PATH}/core/core/sys*
 *
 * @param contribEnv
 * @param confDesc
 * @param boardsDescriptor
 */
private static void setTheEnvironmentVariablesPostProcessing(IContributedEnvironment contribEnv, ICConfigurationDescription confDesc, InternalBoardDescriptor boardsDescriptor) {
    CompileOptions compileOptions = new CompileOptions(confDesc);
    // a save will overwrite the warning settings set by arduino
    compileOptions.save(confDesc);
    String[] actions = { ACTION_C_to_O, ACTION_CPP_to_O, ACTION_S_to_O, ACTION_OBJCOPY_to_HEX, ACTION_OBJCOPY_to_EEP, ACTION_SIZE, ACTION_AR, ACTION_C_COMBINE };
    for (String action : actions) {
        String recipeKey = get_ENV_KEY_RECIPE(action);
        String recipe = getBuildEnvironmentVariable(confDesc, recipeKey, new String(), false);
        recipe = recipe.replace("-DARDUINO_BSP_VERSION=\"${A.VERSION}\"", "\"-DARDUINO_BSP_VERSION=\\\"${A.VERSION}\\\"\"");
        if (ACTION_C_COMBINE.equals(action)) {
            recipe = recipe.replace("${A.BUILD.PATH}/core/sys", "${A.BUILD.PATH}/core/core/sys");
            recipe = recipe.replace("${A.BUILD.PATH}/sys", "${A.BUILD.PATH}/core/core/sys");
            setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey, recipe);
        }
        String[] recipeParts = recipe.split("(\"\\$\\{A.OBJECT_FILE}\")|(\\$\\{A.OBJECT_FILES})|(\"\\$\\{A.SOURCE_FILE}\")|(\"[^\"]*\\$\\{A.ARCHIVE_FILE}\")|(\"[^\"]*\\$\\{A.ARCHIVE_FILE_PATH}\")", 3);
        switch(recipeParts.length) {
            case 0:
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '1', Messages.Helpers_No_command_for + recipeKey);
                break;
            case 1:
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '1', recipeParts[0]);
                break;
            case 2:
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '1', recipeParts[0]);
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '2', recipeParts[1]);
                break;
            case 3:
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '1', recipeParts[0]);
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '2', recipeParts[1]);
                setBuildEnvironmentVariable(contribEnv, confDesc, recipeKey + DOT + '3', recipeParts[2]);
                break;
            default:
        }
    }
    String programmer = boardsDescriptor.getProgrammer();
    if (programmer.equalsIgnoreCase(Defaults.getDefaultUploadProtocol())) {
        String MComPort = boardsDescriptor.getUploadPort();
        if (MComPort.isEmpty()) {
            Common.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "Upload will fail due to missing upload port"));
        }
    }
    ArrayList<String> objcopyCommand = new ArrayList<>();
    // I'm looping through the set of variables to fix some things up
    try {
        IEnvironmentVariable[] curVariables = contribEnv.getVariables(confDesc);
        for (IEnvironmentVariable curVariable : curVariables) {
            String name = curVariable.getName();
            // FQN
            if (name.startsWith("A.TOOLS.")) {
                String toolID = curVariable.getName().split("\\.")[2];
                String recipe = curVariable.getValue();
                int indexOfVar = recipe.indexOf("${A.");
                while (indexOfVar != -1) {
                    int endIndexOfVar = recipe.indexOf('}', indexOfVar);
                    if (endIndexOfVar != -1) {
                        String foundSuffix = recipe.substring(indexOfVar + 3, endIndexOfVar);
                        String foundVar = "A" + foundSuffix;
                        String replaceVar = "A.TOOLS." + toolID.toUpperCase() + foundSuffix;
                        if (contribEnv.getVariable(foundVar, confDesc) == null) {
                            // $NON-NLS-1$
                            recipe = recipe.replaceAll(foundVar, replaceVar);
                        }
                    }
                    indexOfVar = recipe.indexOf("${A.", indexOfVar + 4);
                }
                setBuildEnvironmentVariable(contribEnv, confDesc, name, recipe);
            }
            if (name.startsWith("A.RECIPE.OBJCOPY.") && name.endsWith(".PATTERN") && !curVariable.getValue().isEmpty()) {
                objcopyCommand.add(makeEnvironmentVar(name));
            }
            // Handle spaces in defines for USB stuff in windows
            if (Platform.getOS().equals(Platform.OS_WIN32)) {
                if ("A.BUILD.USB_MANUFACTURER".equalsIgnoreCase(name)) {
                    String moddedValue = curVariable.getValue().replace("\"", "\\\"");
                    setBuildEnvironmentVariable(contribEnv, confDesc, name, moddedValue);
                }
                if ("A.BUILD.USB_PRODUCT".equalsIgnoreCase(name)) {
                    String moddedValue = curVariable.getValue().replace("\"", "\\\"");
                    setBuildEnvironmentVariable(contribEnv, confDesc, name, moddedValue);
                }
                if ("A.BUILD.USB_FLAGS".equalsIgnoreCase(name)) {
                    String moddedValue = curVariable.getValue().replace("'", "\"");
                    setBuildEnvironmentVariable(contribEnv, confDesc, name, moddedValue);
                }
                if ("A.BUILD.EXTRA_FLAGS".equalsIgnoreCase(name)) {
                    // for radino
                    // radinoCC1101.build.extra_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_PRODUCT={build.usb_product}'
                    String moddedValue = curVariable.getValue().replace("'-DUSB_PRODUCT=${A.BUILD.USB_PRODUCT}'", "\"-DUSB_PRODUCT=${A.BUILD.USB_PRODUCT}\"");
                    setBuildEnvironmentVariable(contribEnv, confDesc, name, moddedValue);
                }
            }
        }
    } catch (Exception e) {
        Common.log(new Status(IStatus.WARNING, Const.CORE_PLUGIN_ID, "parsing of upload recipe failed", e));
    }
    Collections.sort(objcopyCommand);
    setBuildEnvironmentVariable(contribEnv, confDesc, "JANTJE.OBJCOPY", StringUtil.join(objcopyCommand, "\n\t"));
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ArrayList(java.util.ArrayList) CompileOptions(io.sloeber.core.api.CompileOptions) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) CoreException(org.eclipse.core.runtime.CoreException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException)

Example 4 with IEnvironmentVariable

use of org.eclipse.cdt.core.envvar.IEnvironmentVariable in project arduino-eclipse-plugin by Sloeber.

the class Common method setBuildEnvironmentVariable.

public static void setBuildEnvironmentVariable(IContributedEnvironment contribEnv, ICConfigurationDescription confdesc, String key, String value) {
    IEnvironmentVariable var = new EnvironmentVariable(key, makePathEnvironmentString(value));
    contribEnv.addVariable(var, confdesc);
}
Also used : IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) EnvironmentVariable(org.eclipse.cdt.core.envvar.EnvironmentVariable) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable)

Example 5 with IEnvironmentVariable

use of org.eclipse.cdt.core.envvar.IEnvironmentVariable in project arduino-eclipse-plugin by Sloeber.

the class arduinoUploader method setEnvironmentvarsForAutorizedUpload.

private void setEnvironmentvarsForAutorizedUpload(IContributedEnvironment contribEnv, ICConfigurationDescription configurationDescription, String host) {
    String passWord = null;
    passWord = getPasswordFromCode();
    IEnvironmentVariable var = new EnvironmentVariable(Const.ENV_KEY_NETWORK_AUTH, passWord);
    contribEnv.addVariable(var, configurationDescription);
}
Also used : IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable) EnvironmentVariable(org.eclipse.cdt.core.envvar.EnvironmentVariable) IEnvironmentVariable(org.eclipse.cdt.core.envvar.IEnvironmentVariable)

Aggregations

IEnvironmentVariable (org.eclipse.cdt.core.envvar.IEnvironmentVariable)6 EnvironmentVariable (org.eclipse.cdt.core.envvar.EnvironmentVariable)4 IOException (java.io.IOException)3 CoreException (org.eclipse.core.runtime.CoreException)3 ArrayList (java.util.ArrayList)2 IContributedEnvironment (org.eclipse.cdt.core.envvar.IContributedEnvironment)2 CompileOptions (io.sloeber.core.api.CompileOptions)1 ConfigurationPreferences (io.sloeber.core.common.ConfigurationPreferences)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 URISyntaxException (java.net.URISyntaxException)1 HashMap (java.util.HashMap)1 Pattern (java.util.regex.Pattern)1 IEnvironmentVariableManager (org.eclipse.cdt.core.envvar.IEnvironmentVariableManager)1 CoreModel (org.eclipse.cdt.core.model.CoreModel)1 IBinary (org.eclipse.cdt.core.model.IBinary)1 ICConfigurationDescription (org.eclipse.cdt.core.settings.model.ICConfigurationDescription)1 ICProjectDescription (org.eclipse.cdt.core.settings.model.ICProjectDescription)1 BuildException (org.eclipse.cdt.managedbuilder.core.BuildException)1 IConfiguration (org.eclipse.cdt.managedbuilder.core.IConfiguration)1