private String getToolName(byte[] data) {
   String text = new String(data);
   String name = null;
   Tokenizer tok = new Tokenizer();
   Program pgm = tok.tokenize(text);
   int[] code = pgm.getCode();
   Symbol[] symbolTable = pgm.getSymbolTable();
   for (int i = 0; i < code.length; i++) {
     int token = code[i] & MacroConstants.TOK_MASK;
     if (token == MacroConstants.MACRO) {
       int nextToken = code[i + 1] & MacroConstants.TOK_MASK;
       if (nextToken == MacroConstants.STRING_CONSTANT) {
         int address = code[i + 1] >> MacroConstants.TOK_SHIFT;
         Symbol symbol = symbolTable[address];
         name = symbol.str;
         break;
       }
     }
   }
   if (name == null) return null;
   int index = name.indexOf("Tool");
   if (index == -1) return null;
   name = name.substring(0, index + 4);
   name = name.replaceAll(" ", "_");
   name = name + ".ijm";
   return name;
 }
Exemplo n.º 2
0
 protected void initOptions() {
   Options options = program.options();
   options.initOptions();
   options.addKeyOption("-version");
   options.addKeyOption("-print");
   options.addKeyOption("-g");
   options.addKeyOption("-g:none");
   options.addKeyOption("-g:lines,vars,source");
   options.addKeyOption("-nowarn");
   options.addKeyOption("-verbose");
   options.addKeyOption("-deprecation");
   options.addKeyValueOption("-classpath");
   options.addKeyValueOption("-cp");
   options.addKeyValueOption("-sourcepath");
   options.addKeyValueOption("-bootclasspath");
   options.addKeyValueOption("-extdirs");
   options.addKeyValueOption("-d");
   options.addKeyValueOption("-encoding");
   options.addKeyValueOption("-source");
   options.addKeyValueOption("-target");
   options.addKeyOption("-help");
   options.addKeyOption("-O");
   options.addKeyOption("-J-Xmx128M");
   options.addKeyOption("-recover");
 }
Exemplo n.º 3
0
  // Método de entrada do Codegen
  public String translate(Program p, Env env) {
    codeGenerator = new Codegen();

    // Preenchendo a Tabela de Símbolos
    // Quem quiser usar 'env', apenas comente essa linha
    // codeGenerator.symTab.FillTabSymbol(p);

    // Formato da String para o System.out.printlnijava "%d\n"
    codeGenerator.assembler.add(
        new LlvmConstantDeclaration(
            "@.formatting.string", "private constant [4 x i8] c\"%d\\0A\\00\""));

    // NOTA: sempre que X.accept(Y), então Y.visit(X);
    // NOTA: Logo, o comando abaixo irá chamar codeGenerator.visit(Program), linha 75
    p.accept(codeGenerator);

    // Link do printf
    List<LlvmType> pts = new LinkedList<LlvmType>();
    pts.add(new LlvmPointer(LlvmPrimitiveType.I8));
    pts.add(LlvmPrimitiveType.DOTDOTDOT);
    codeGenerator.assembler.add(new LlvmExternalDeclaration("@printf", LlvmPrimitiveType.I32, pts));
    List<LlvmType> mallocpts = new LinkedList<LlvmType>();
    mallocpts.add(LlvmPrimitiveType.I32);
    codeGenerator.assembler.add(
        new LlvmExternalDeclaration("@malloc", new LlvmPointer(LlvmPrimitiveType.I8), mallocpts));

    String r = new String();
    for (LlvmInstruction instr : codeGenerator.assembler) r += instr + "\n";
    return r;
  }
Exemplo n.º 4
0
  public int ExecuteInstruction(Object inObject) {

    if (inObject instanceof Program) {
      Program p = (Program) inObject;

      if (_useFrames) {
        _execStack.push("frame.pop");
      }

      p.PushAllReverse(_execStack);

      if (_useFrames) {
        _execStack.push("frame.push");
      }

      return 0;
    }

    if (inObject instanceof Integer) {
      _intStack.push((Integer) inObject);
      return 0;
    }

    if (inObject instanceof Number) {
      _floatStack.push(((Number) inObject).floatValue());
      return 0;
    }

    if (inObject instanceof Instruction) {
      ((Instruction) inObject).Execute(this);
      return 0;
    }

    if (inObject instanceof String) {
      Instruction i = _instructions.get(inObject);

      if (i != null) {
        i.Execute(this);
      } else {
        _nameStack.push(inObject);
      }

      return 0;
    }

    return -1;
  }
Exemplo n.º 5
0
  /**
   * Generates a random Push program of a given size.
   *
   * @param inSize The requested size for the program to be generated.
   * @return A random Push program of the given size.
   */
  public Program RandomCode(int inSize) {
    Program p = new Program();

    List<Integer> distribution = RandomCodeDistribution(inSize - 1, inSize - 1);

    for (int i = 0; i < distribution.size(); i++) {
      int count = distribution.get(i);

      if (count == 1) {
        p.push(RandomAtom());
      } else {
        p.push(RandomCode(count));
      }
    }

    return p;
  }
Exemplo n.º 6
0
 private Statement generateJumpStatement(SwitchStatement stmt, int target) {
   Statement body = generateJumpStatement(program.basicBlockAt(target));
   if (body == null) {
     BreakStatement breakStmt = new BreakStatement();
     breakStmt.setTarget(stmt);
     body = breakStmt;
   }
   return body;
 }
Exemplo n.º 7
0
  // process a mouseClicked event
  // select the loop if the mouse was clicked within the edges of
  // the border
  public void mouseClicked(MouseEvent mouseEvent) {
    int x = mouseEvent.getX();
    int y = mouseEvent.getY();

    Rectangle bounds = getBounds();

    // left, top, bottom, right edge
    if ((x >= 0 && x <= SELECT_BORDER_SIZE)
        || (y >= 0 && y <= SELECT_BORDER_SIZE)
        || (y >= bounds.height - SELECT_BORDER_SIZE && y <= bounds.height)
        || (x >= bounds.width - SELECT_BORDER_SIZE && x <= bounds.width)) {
      if (isSelected()) program.setAllSelected(false);
      else {
        program.setAllSelected(false);
        setSelected(true);
        program.updateLoopDialog();
      }
      program.updateState();
      repaint();
    } else super.mouseClicked(mouseEvent);
  }
Exemplo n.º 8
0
  public boolean process(String[] args, BytecodeReader reader, JavaParser parser) {
    program.initBytecodeReader(reader);
    program.initJavaParser(parser);

    initOptions();
    processArgs(args);

    Collection files = program.options().files();

    if (program.options().hasOption("-version")) {
      printVersion();
      return false;
    }
    if (program.options().hasOption("-help") || files.isEmpty()) {
      printUsage();
      return false;
    }

    try {
      for (Iterator iter = files.iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        if (!new File(name).exists())
          System.err.println("WARNING: file \"" + name + "\" does not exist");
        program.addSourceFile(name);
      }

      for (Iterator iter = program.compilationUnitIterator(); iter.hasNext(); ) {
        CompilationUnit unit = (CompilationUnit) iter.next();
        if (unit.fromSource()) {
          Collection errors = unit.parseErrors();
          Collection warnings = new LinkedList();
          // compute static semantic errors when there are no parse errors or
          // the recover from parse errors option is specified
          if (errors.isEmpty() || program.options().hasOption("-recover"))
            unit.errorCheck(errors, warnings);
          if (!errors.isEmpty()) {
            processErrors(errors, unit);
            return false;
          } else {
            if (!warnings.isEmpty()) processWarnings(warnings, unit);
            processNoErrors(unit);
          }
        }
      }
    } catch (Exception e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    }
    return true;
  }
Exemplo n.º 9
0
  public Program build() {
    newprogram =
        new Program(
            LegacyArchitecture.INSTANCE,
            programSegment.lowest_address,
            programSegment.highest_address);

    sourceMapping = new SourceMapping(newprogram);
    newprogram.setSourceMapping(sourceMapping);
    for (Item pos : itemList) {
      simplify(pos);
    }

    return newprogram;
  }
Exemplo n.º 10
0
 private void castAndSetProperty(
     InvokeInstruction insn, String property, List<Instruction> instructions, Class<?> primitive) {
   Variable castVar = program.createVariable();
   InvokeInstruction castInvoke = new InvokeInstruction();
   castInvoke.setType(InvocationType.SPECIAL);
   String primitiveCapitalized = primitive.getName();
   primitiveCapitalized =
       Character.toUpperCase(primitiveCapitalized.charAt(0)) + primitiveCapitalized.substring(1);
   castInvoke.setMethod(
       new MethodReference(
           ResourceAccessor.class, "castFrom" + primitiveCapitalized, primitive, Object.class));
   castInvoke.getArguments().add(insn.getArguments().get(0));
   castInvoke.setReceiver(castVar);
   instructions.add(castInvoke);
   setProperty(insn, property, instructions, castVar);
 }
Exemplo n.º 11
0
 private void setProperty(
     InvokeInstruction insn, String property, List<Instruction> instructions, Variable valueVar) {
   Variable nameVar = program.createVariable();
   StringConstantInstruction nameInsn = new StringConstantInstruction();
   nameInsn.setConstant(property);
   nameInsn.setReceiver(nameVar);
   instructions.add(nameInsn);
   InvokeInstruction accessorInvoke = new InvokeInstruction();
   accessorInvoke.setType(InvocationType.SPECIAL);
   accessorInvoke.setMethod(
       new MethodReference(
           ResourceAccessor.class, "put", Object.class, String.class, Object.class, void.class));
   accessorInvoke.getArguments().add(insn.getInstance());
   accessorInvoke.getArguments().add(nameVar);
   accessorInvoke.getArguments().add(valueVar);
   instructions.add(accessorInvoke);
 }
 void installPopupMenu(String name, Program pgm) {
   Hashtable h = pgm.getMenus();
   if (h == null) return;
   String[] commands = (String[]) h.get(name);
   if (commands == null) return;
   PopupMenu popup = Menus.getPopupMenu();
   if (popup == null) return;
   popup.removeAll();
   for (int i = 0; i < commands.length; i++) {
     if (commands[i].equals("-")) popup.addSeparator();
     else {
       MenuItem mi = new MenuItem(commands[i]);
       mi.addActionListener(this);
       popup.add(mi);
     }
   }
 }
Exemplo n.º 13
0
  private List<Instruction> transformKeys(InvokeInstruction insn) {
    Variable tmp = program.createVariable();

    InvokeInstruction keysInsn = new InvokeInstruction();
    keysInsn.setType(InvocationType.SPECIAL);
    keysInsn.setMethod(
        new MethodReference(ResourceAccessor.class, "keys", Object.class, Object.class));
    keysInsn.getArguments().add(insn.getInstance());
    keysInsn.setReceiver(tmp);

    InvokeInstruction transformInsn = new InvokeInstruction();
    transformInsn.setType(InvocationType.SPECIAL);
    transformInsn.setMethod(
        new MethodReference(ResourceAccessor.class, "keysToStrings", Object.class, String[].class));
    transformInsn.getArguments().add(tmp);
    transformInsn.setReceiver(insn.getReceiver());

    return Arrays.asList(keysInsn, transformInsn);
  }
Exemplo n.º 14
0
  public Interpreter clone() {
    Interpreter clone = new Interpreter();

    clone._useFrames = _useFrames;

    Program instructionList = new Program();
    _inInstructionList.CopyTo(instructionList);
    clone.SetInstructions(instructionList);
    clone.SetRandomParameters(
        _minRandomInt,
        _maxRandomInt,
        _randomIntResolution,
        _minRandomFloat,
        _maxRandomFloat,
        _randomFloatResolution,
        _maxRandomCodeSize,
        _maxPointsInProgram);

    clone._useFrames = _useFrames;

    return clone;
  }
 void install() {
   subMenus.clear();
   if (text != null) {
     Tokenizer tok = new Tokenizer();
     pgm = tok.tokenize(text);
   }
   if (macrosMenu != null) IJ.showStatus("");
   int[] code = pgm.getCode();
   Symbol[] symbolTable = pgm.getSymbolTable();
   int count = 0, token, nextToken, address;
   String name;
   Symbol symbol;
   shortcutsInUse = null;
   inUseCount = 0;
   nShortcuts = 0;
   toolCount = 0;
   macroStarts = new int[MAX_MACROS];
   macroNames = new String[MAX_MACROS];
   boolean isPluginsMacrosMenu = false;
   if (macrosMenu != null) {
     int itemCount = macrosMenu.getItemCount();
     isPluginsMacrosMenu = macrosMenu == Menus.getMacrosMenu();
     int baseCount = isPluginsMacrosMenu ? MACROS_MENU_COMMANDS : Editor.MACROS_MENU_ITEMS;
     if (itemCount > baseCount) {
       for (int i = itemCount - 1; i >= baseCount; i--) macrosMenu.remove(i);
     }
   }
   if (pgm.hasVars() && pgm.macroCount() > 0 && pgm.getGlobals() == null)
     new Interpreter().saveGlobals(pgm);
   ArrayList tools = new ArrayList();
   for (int i = 0; i < code.length; i++) {
     token = code[i] & TOK_MASK;
     if (token == MACRO) {
       nextToken = code[i + 1] & TOK_MASK;
       if (nextToken == STRING_CONSTANT) {
         if (count == MAX_MACROS) {
           if (isPluginsMacrosMenu)
             IJ.error("Macro Installer", "Macro sets are limited to " + MAX_MACROS + " macros.");
           break;
         }
         address = code[i + 1] >> TOK_SHIFT;
         symbol = symbolTable[address];
         name = symbol.str;
         macroStarts[count] = i + 2;
         macroNames[count] = name;
         if (name.indexOf('-') != -1
             && (name.indexOf("Tool") != -1 || name.indexOf("tool") != -1)) {
           tools.add(name);
           toolCount++;
         } else if (name.startsWith("AutoRun")) {
           if (autoRunCount == 0 && !openingStartupMacrosInEditor) {
             new MacroRunner(pgm, macroStarts[count], name, (String) null);
             if (name.equals("AutoRunAndHide")) autoRunAndHideCount++;
           }
           autoRunCount++;
           count--;
         } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm);
         else if (!name.endsWith("Tool Selected")) {
           if (macrosMenu != null) {
             addShortcut(name);
             int pos = name.indexOf(">");
             boolean inSubMenu = name.startsWith("<") && (pos > 1);
             if (inSubMenu) {
               Menu parent = macrosMenu;
               Menu subMenu = null;
               String parentStr = name.substring(1, pos).trim();
               String childStr = name.substring(pos + 1).trim();
               MenuItem mnuItem = new MenuItem();
               mnuItem.setActionCommand(name);
               mnuItem.setLabel(childStr);
               for (int jj = 0; jj < subMenus.size(); jj++) {
                 String aName = subMenus.get(jj).getName();
                 if (aName.equals(parentStr)) subMenu = subMenus.get(jj);
               }
               if (subMenu == null) {
                 subMenu = new Menu(parentStr);
                 subMenu.setName(parentStr);
                 subMenu.addActionListener(this);
                 subMenus.add(subMenu);
                 parent.add(subMenu);
               }
               subMenu.add(mnuItem);
             } else macrosMenu.add(new MenuItem(name));
           }
         }
         // IJ.log(count+" "+name+" "+macroStarts[count]);
         count++;
       }
     } else if (token == EOF) break;
   }
   nMacros = count;
   if (toolCount > 0 && (isPluginsMacrosMenu || macrosMenu == null) && installTools) {
     Toolbar tb = Toolbar.getInstance();
     if (toolCount == 1) tb.addMacroTool((String) tools.get(0), this);
     else {
       for (int i = 0; i < tools.size(); i++) {
         String toolName = (String) tools.get(i);
         if (toolName.startsWith("Abort Macro or Plugin") && toolCount > 6)
           toolName = "Unused " + toolName;
         tb.addMacroTool(toolName, this, i);
       }
     }
     if (toolCount > 1 && Toolbar.getToolId() >= Toolbar.CUSTOM1) tb.setTool(Toolbar.RECTANGLE);
     tb.repaint();
   }
   if (macrosMenu != null) this.instance = this;
   if (shortcutsInUse != null && text != null)
     IJ.showMessage(
         "Install Macros",
         (inUseCount == 1 ? "This keyboard shortcut is" : "These keyboard shortcuts are")
             + " already in use:"
             + shortcutsInUse);
   if (nMacros == 0 && fileName != null) {
     if (text == null || text.length() == 0) return;
     int dotIndex = fileName.lastIndexOf('.');
     if (dotIndex > 0) anonymousName = fileName.substring(0, dotIndex);
     else anonymousName = fileName;
     if (macrosMenu != null) macrosMenu.add(new MenuItem(anonymousName));
     macroNames[0] = anonymousName;
     nMacros = 1;
   }
   String word = nMacros == 1 ? " macro" : " macros";
   if (isPluginsMacrosMenu) IJ.showStatus(nMacros + word + " installed");
 }
Exemplo n.º 16
0
  /**
   * Defines the instruction set used for random code generation in this Push interpreter.
   *
   * @param inInstructionList A program consisting of a list of string instruction names to be
   *     placed in the instruction set.
   */
  public void SetInstructions(Program inInstructionList) throws RuntimeException {
    _inInstructionList = new Program();
    inInstructionList.CopyTo(_inInstructionList);

    _randomGenerators.clear();

    for (int n = 0; n < inInstructionList.size(); n++) {
      Object o = inInstructionList.peek(n);
      String name = null;

      if (o instanceof Instruction) {
        String keys[] = _instructions.keySet().toArray(new String[_instructions.size()]);

        for (String key : keys)
          if (_instructions.get(key) == o) {
            name = key;
            break;
          }
      } else if (o instanceof String) {
        name = (String) o;
      } else
        throw new RuntimeException(
            "Instruction list must contain a list of Push instruction names only");

      // Check for registered
      if (name.indexOf("registered.") == 0) {
        String registeredType = name.substring(11);

        if (!registeredType.equals("integer")
            && !registeredType.equals("float")
            && !registeredType.equals("boolean")
            && !registeredType.equals("exec")
            && !registeredType.equals("code")
            && !registeredType.equals("name")
            && !registeredType.equals("input")
            && !registeredType.equals("frame")) {
          System.err.println("Unknown instruction \"" + name + "\" in instruction set");
        } else {
          // Legal stack type, so add all generators matching
          // registeredType to _randomGenerators.
          Object keys[] = _instructions.keySet().toArray();

          for (int i = 0; i < keys.length; i++) {
            String key = (String) keys[i];
            if (key.indexOf(registeredType) == 0) {
              AtomGenerator g = _generators.get(key);
              _randomGenerators.add(g);
            }
          }

          if (registeredType.equals("boolean")) {
            AtomGenerator t = _generators.get("true");
            _randomGenerators.add(t);
            AtomGenerator f = _generators.get("false");
            _randomGenerators.add(f);
          }
          if (registeredType.equals("integer")) {
            AtomGenerator g = _generators.get("integer.erc");
            _randomGenerators.add(g);
          }
          if (registeredType.equals("float")) {
            AtomGenerator g = _generators.get("float.erc");
            _randomGenerators.add(g);
          }
        }
      } else if (name.indexOf("input.makeinputs") == 0) {
        String strnum = name.substring(16);
        int num = Integer.parseInt(strnum);

        for (int i = 0; i < num; i++) {
          DefineInstruction("input.in" + i, new InputInN(i));
          AtomGenerator g = _generators.get("input.in" + i);
          _randomGenerators.add(g);
        }
      } else {
        AtomGenerator g = _generators.get(name);

        if (g == null) {
          throw new RuntimeException("Unknown instruction \"" + name + "\" in instruction set");
        } else {
          _randomGenerators.add(g);
        }
      }
    }
  }
Exemplo n.º 17
0
 public void transformProgram() {
   for (int i = 0; i < program.basicBlockCount(); ++i) {
     transformBasicBlock(program.basicBlockAt(i));
   }
 }
Exemplo n.º 18
0
 // set the selection state and update the GUI and loop dialog
 public void setSelected(boolean flag) {
   super.setSelected(flag);
   program.updateState();
   program.updateLoopDialog();
 }
Exemplo n.º 19
0
 protected Frontend() {
   program = new Program();
   program.state().reset();
 }
Exemplo n.º 20
0
 protected void processArgs(String[] args) {
   program.options().addOptions(args);
 }
Exemplo n.º 21
0
 public LlvmValue FillTabSymbol(Program n) {
   n.accept(this);
   return null;
 }