Ejemplo n.º 1
0
  /**
   * Compute the set of all IA32 opcodes that have emit methods in the Assembler. This method uses
   * the stylized form of all emit method names in the Assembler to extract the opcode of each one.
   * It returns a set of all such distinct names, as a set of Strings.
   *
   * @param emitters the set of all emit methods in the Assembler
   * @return the set of all opcodes handled by the Assembler
   */
  private static Set<String> getOpcodes(Method[] emitters) {
    Set<String> s = new HashSet<String>();
    for (int i = 0; i < emitters.length; i++) {
      String name = emitters[i].getName();
      if (DEBUG) System.err.println(name);
      if (name.startsWith("emit")) {
        int posOf_ = name.indexOf('_');
        if (posOf_ != -1) {
          String opcode = name.substring(4, posOf_);
          if (!excludedOpcodes.contains(opcode)) {
            s.add(opcode);
          }
        } else {
          String opcode = name.substring(4);
          // make sure it is an opcode
          if (opcode.equals(opcode.toUpperCase(Locale.getDefault()))) {
            if (!excludedOpcodes.contains(opcode)) {
              s.add(opcode);
            }
          }
        }
      }
    }

    return s;
  }
  private static void check(String what, MBeanNotificationInfo[] mbnis) {
    System.out.print(what + ": checking notification info: ");

    if (mbnis.length == 0) {
      System.out.println("NONE (suspicious)");
      suspicious.add(what);
      return;
    }

    // Each MBeanNotificationInfo.getName() should be an existent
    // Java class that is Notification or a subclass of it
    for (int j = 0; j < mbnis.length; j++) {
      String notifClassName = mbnis[j].getName();
      Class notifClass;
      try {
        notifClass = Class.forName(notifClassName);
      } catch (Exception e) {
        System.out.print("FAILED(" + notifClassName + ": " + e + ") ");
        failed.add(what);
        continue;
      }
      if (!Notification.class.isAssignableFrom(notifClass)) {
        System.out.print("FAILED(" + notifClassName + ": not a Notification) ");
        failed.add(what);
        continue;
      }
      System.out.print("OK(" + notifClassName + ") ");
    }
    System.out.println();
  }
  public Set<String> getOperatorClasses(String parent, String searchTerm)
      throws ClassNotFoundException {
    if (CollectionUtils.isEmpty(operatorClassNames)) {
      loadOperatorClass();
    }
    if (parent == null) {
      parent = Operator.class.getName();
    } else {
      if (!typeGraph.isAncestor(Operator.class.getName(), parent)) {
        throw new IllegalArgumentException("Argument must be a subclass of Operator class");
      }
    }

    Set<String> filteredClass =
        Sets.filter(
            operatorClassNames,
            new Predicate<String>() {
              @Override
              public boolean apply(String className) {
                OperatorClassInfo oci = classInfo.get(className);
                return oci == null || !oci.tags.containsKey("@omitFromUI");
              }
            });

    if (searchTerm == null && parent.equals(Operator.class.getName())) {
      return filteredClass;
    }

    if (searchTerm != null) {
      searchTerm = searchTerm.toLowerCase();
    }

    Set<String> result = new HashSet<String>();
    for (String clazz : filteredClass) {
      if (parent.equals(Operator.class.getName()) || typeGraph.isAncestor(parent, clazz)) {
        if (searchTerm == null) {
          result.add(clazz);
        } else {
          if (clazz.toLowerCase().contains(searchTerm)) {
            result.add(clazz);
          } else {
            OperatorClassInfo oci = classInfo.get(clazz);
            if (oci != null) {
              if (oci.comment != null && oci.comment.toLowerCase().contains(searchTerm)) {
                result.add(clazz);
              } else {
                for (Map.Entry<String, String> entry : oci.tags.entrySet()) {
                  if (entry.getValue().toLowerCase().contains(searchTerm)) {
                    result.add(clazz);
                    break;
                  }
                }
              }
            }
          }
        }
      }
    }
    return result;
  }
Ejemplo n.º 4
0
  private void checkStartup(
      Map<String, ServiceData> map,
      List<ServiceData> start,
      ServiceData sd,
      Set<ServiceData> cyclic) {
    if (sd.after.isEmpty() || start.contains(sd)) return;

    if (cyclic.contains(sd)) {
      reporter.error("Cyclic dependency for " + sd.name);
      return;
    }

    cyclic.add(sd);

    for (String dependsOn : sd.after) {
      if (dependsOn.equals("boot")) continue;

      ServiceData deps = map.get(dependsOn);
      if (deps == null) {
        reporter.error("No such service " + dependsOn + " but " + sd.name + " depends on it");
      } else {
        checkStartup(map, start, deps, cyclic);
      }
    }
    start.add(sd);
  }
Ejemplo n.º 5
0
 /**
  * Returns the children name associated with this config instance. This is by definition a subset
  * of the element names as known to the model {#see ConfigModel.getElementNames(). @Return list of
  * elements names associated with this config instance
  */
 public Set<String> getElementNames() {
   Set<String> names = new HashSet<String>();
   for (Child child : children) {
     names.add(child.name);
   }
   return names;
 }
Ejemplo n.º 6
0
 public Set<String> listResources(String subdir) {
   try {
     Set<String> result = new HashSet<String>();
     if (resourceURL != null) {
       String protocol = resourceURL.getProtocol();
       if (protocol.equals("jar")) {
         String resPath = resourceURL.getPath();
         int pling = resPath.lastIndexOf("!");
         URL jarURL = new URL(resPath.substring(0, pling));
         String resDirInJar = resPath.substring(pling + 2);
         String prefix = resDirInJar + subdir + "/";
         // System.out.printf("BaseMod.listResources: looking for names starting with %s\n",
         // prefix);
         JarFile jar = new JarFile(new File(jarURL.toURI()));
         Enumeration<JarEntry> entries = jar.entries();
         while (entries.hasMoreElements()) {
           String name = entries.nextElement().getName();
           if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) {
             // System.out.printf("BaseMod.listResources: name = %s\n", name);
             result.add(name.substring(prefix.length()));
           }
         }
       } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported");
     }
     return result;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 7
0
 @Override
 public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
   for (AnnotationMirror annotationMirror : elements.getAllAnnotationMirrors(e)) {
     Element e2 = annotationMirror.getAnnotationType().asElement();
     p.add((TypeElement) e2);
   }
   return super.scan(e, p);
 }
 /**
  * Returns a string array containing the default JMX domains of all available MBeanServers in this
  * JVM.
  *
  * @return a string array of JMX default domains
  */
 public static String[] getMBeanServerDomains() {
   Set<String> domains = new HashSet<String>();
   for (MBeanServer mbs : MBeanServerFactory.findMBeanServer(null)) {
     String domain = mbs.getDefaultDomain();
     if (domain == null) domain = "DefaultDomain";
     domains.add(domain);
   }
   return domains.toArray(new String[domains.size()]);
 }
Ejemplo n.º 9
0
  /**
   * Adds <tt>listener</tt> to the list of {@link CapsVerListener}s that we notify when new features
   * occur and the version hash needs to be regenerated. The method would also notify
   * <tt>listener</tt> if our current caps version has been generated and is different than
   * <tt>null</tt>.
   *
   * @param listener the {@link CapsVerListener} we'd like to register.
   */
  public void addCapsVerListener(CapsVerListener listener) {
    synchronized (capsVerListeners) {
      if (capsVerListeners.contains(listener)) return;

      capsVerListeners.add(listener);

      if (currentCapsVersion != null) listener.capsVerUpdated(currentCapsVersion);
    }
  }
Ejemplo n.º 10
0
  /**
   * returns a list of all IA32_ opt compiler operators that do not correspond to real IA32 opcodes
   * handled by the assembler. These are all supposed to have been removed by the time the assembler
   * is called, so the assembler actually seeing such an opcode is an internal compiler error. This
   * set is used during generating of error checking code.
   *
   * @param emittedOpcodes the set of IA32 opcodes the assembler understands.
   * @return the set of IA32 opt operators that the assembler does not understand.
   */
  private static Set<String> getErrorOpcodes(Set<String> emittedOpcodes) {
    Iterator<String> e = OperatorFormatTables.getOpcodes();
    Set<String> errorOpcodes = new HashSet<String>();
    while (e.hasNext()) {
      String opcode = (String) e.next();
      if (!emittedOpcodes.contains(opcode)) errorOpcodes.add(opcode);
    }

    return errorOpcodes;
  }
Ejemplo n.º 11
0
  /**
   * Given an IA32 opcode, return the set of opt compiler IA32_ operators that translate to it.
   * There is, by and large, a one-to-one mapping in each each IA332_ opt operator represents an
   * IA32 opcde, so this method might seem useless. However, there are some special cases, notably
   * for operand size. In this case, an opt operator of the form ADD__B would mean use the ADD IA32
   * opcode with a byte operand size.
   */
  private static Set<String> getMatchingOperators(String lowLevelOpcode) {
    Iterator<String> e = OperatorFormatTables.getOpcodes();
    Set<String> matchingOperators = new HashSet<String>();
    while (e.hasNext()) {
      String o = (String) e.next();
      if (o.equals(lowLevelOpcode) || o.startsWith(lowLevelOpcode + "__")) matchingOperators.add(o);
    }

    return matchingOperators;
  }
Ejemplo n.º 12
0
 /**
  * Initialize the set of opcodes to ignore
  *
  * @see #excludedOpcodes
  */
 static {
   excludedOpcodes = new HashSet<String>();
   excludedOpcodes.add("FSAVE");
   excludedOpcodes.add("FNSTSW");
   excludedOpcodes.add("FUCOMPP");
   excludedOpcodes.add("SAHF");
   excludedOpcodes.add("NOP");
   excludedOpcodes.add("ENTER");
   excludedOpcodes.add("JMP");
   excludedOpcodes.add("JCC");
   excludedOpcodes.add("EMMS");
 }
Ejemplo n.º 13
0
  /* package */ @SuppressWarnings({"unchecked"})
  void register() {
    ServiceLocator locator = getServiceLocator();

    ActiveDescriptor<?> myselfReified = locator.reifyDescriptor(this);

    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    //        habitat.add(this);
    HK2Loader loader = this.model.classLoaderHolder;

    Set<Type> ctrs = new HashSet<Type>();
    ctrs.add(myselfReified.getImplementationClass());

    if (ConfigBean.class.isAssignableFrom(this.getClass())) {
      ctrs.add(ConfigBean.class);
    }

    DomDescriptor<Dom> domDesc =
        new DomDescriptor<Dom>(
            this, ctrs, Singleton.class, getImplementation(), new HashSet<Annotation>());
    domDesc.setLoader(loader);
    domDescriptor = dc.addActiveDescriptor(domDesc, false);

    String key = getKey();
    for (String contract : model.contracts) {
      ActiveDescriptor<Dom> alias = new AliasDescriptor<Dom>(locator, domDescriptor, contract, key);
      dc.addActiveDescriptor(alias, false);
    }
    if (key != null) {
      ActiveDescriptor<Dom> alias =
          new AliasDescriptor<Dom>(locator, domDescriptor, model.targetTypeName, key);
      dc.addActiveDescriptor(alias, false);
    }

    dc.commit();

    serviceHandle = getHabitat().getServiceHandle(domDescriptor);
  }
Ejemplo n.º 14
0
 private void handleRtpPacket(RawPacket pkt) {
   if (pkt != null && pkt.getPayloadType() == vp8PayloadType) {
     int ssrc = pkt.getSSRC();
     if (!activeVideoSsrcs.contains(ssrc & 0xffffffffL)) {
       synchronized (activeVideoSsrcs) {
         if (!activeVideoSsrcs.contains(ssrc & 0xffffffffL)) {
           activeVideoSsrcs.add(ssrc & 0xffffffffL);
           rtcpFeedbackSender.sendFIR(ssrc);
         }
       }
     }
   }
 }
Ejemplo n.º 15
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
 private static Set<String> findStandardMBeansFromJar(URL codeBase) throws Exception {
   InputStream is = codeBase.openStream();
   JarInputStream jis = new JarInputStream(is);
   Set<String> names = new TreeSet<String>();
   JarEntry entry;
   while ((entry = jis.getNextJarEntry()) != null) {
     String name = entry.getName();
     if (!name.endsWith(".class")) continue;
     name = name.substring(0, name.length() - 6);
     name = name.replace('/', '.');
     names.add(name);
   }
   return names;
 }
 private static void scanDir(File dir, String prefix, Set<String> names) throws Exception {
   File[] files = dir.listFiles();
   if (files == null) return;
   for (int i = 0; i < files.length; i++) {
     File f = files[i];
     String name = f.getName();
     String p = (prefix.equals("")) ? name : prefix + "." + name;
     if (f.isDirectory()) scanDir(f, p, names);
     else if (name.endsWith(".class")) {
       p = p.substring(0, p.length() - 6);
       names.add(p);
     }
   }
 }
Ejemplo n.º 18
0
 static {
   // compute primitives/primitiveMap/primitiveToWrapper
   for (Class<?> c : primitiveWrappers) {
     try {
       Field f = c.getField("TYPE");
       Class<?> p = (Class<?>) f.get(null);
       primitives.add(p);
       primitiveMap.put(p.getName(), p);
       primitiveToWrapper.put(p.getName(), c);
     } catch (Exception e) {
       throw new AssertionError(e);
     }
   }
   // compute editableTypes
   for (Class<?> c : primitives) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : primitiveWrappers) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : extraEditableClasses) {
     editableTypes.add(c.getName());
   }
   // compute numericalTypes
   for (Class<?> c : primitives) {
     String name = c.getName();
     if (!name.equals(Boolean.TYPE.getName())) {
       numericalTypes.add(name);
     }
   }
   for (Class<?> c : primitiveWrappers) {
     String name = c.getName();
     if (!name.equals(Boolean.class.getName())) {
       numericalTypes.add(name);
     }
   }
 }
Ejemplo n.º 19
0
 @Override
 public boolean handleEvent(RecorderEvent ev) {
   if (ev == null) return true;
   if (RecorderEvent.Type.RECORDING_STARTED.equals(ev.getType())) {
     long instant = getSynchronizer().getLocalTime(ev.getSsrc(), ev.getRtpTimestamp());
     if (instant != -1) {
       ev.setInstant(instant);
       return handler.handleEvent(ev);
     } else {
       pendingEvents.add(ev);
       return true;
     }
   }
   return handler.handleEvent(ev);
 }
  private static String[] findStandardMBeans(URL codeBase) throws Exception {
    Set<String> names;
    if (codeBase.getProtocol().equalsIgnoreCase("file") && codeBase.toString().endsWith("/"))
      names = findStandardMBeansFromDir(codeBase);
    else names = findStandardMBeansFromJar(codeBase);

    Set<String> standardMBeanNames = new TreeSet<String>();
    for (String name : names) {
      if (name.endsWith("MBean")) {
        String prefix = name.substring(0, name.length() - 5);
        if (names.contains(prefix)) standardMBeanNames.add(prefix);
      }
    }
    return standardMBeanNames.toArray(new String[0]);
  }
Ejemplo n.º 21
0
  /**
   * ** Prints all the default values from <code>RTKey</code> and {@link RTConfig} ** to the
   * specified <code>PrintStream</code>. Used for debugging/testing ** @param out The <code>
   * PrintStream</code>
   */
  public static void printDefaults(PrintStream out) {

    /* print standard runtime entries */
    Set<String> keyList = new OrderedSet<String>();
    String keyGrp = null;

    for (Iterator<Entry> v = RTKey.getRuntimeEntryMap().values().iterator(); v.hasNext(); ) {
      Entry rtk = v.next();
      if (rtk.isHelp()) {
        out.println("");
        out.println("# ===== " + rtk.getHelp());
      } else {
        Object dft = rtk.getDefault();
        out.println("# --- " + rtk.getHelp());
        out.println("# " + rtk.toString(dft));
        String key = rtk.getKey();
        keyList.add(key);
        if (!key.equals(CONFIG_FILE) && RTConfig.hasProperty(key)) {
          String val = RTConfig.getString(key, null);
          // if ((val != null) && ((dft == null) || !val.equals(dft.toString()))) {
          out.println(rtk.toString(val));
          // }
        }
      }
    }

    /* orphaned entries */
    RTProperties cmdLineProps = RTConfig.getConfigFileProperties();
    if (cmdLineProps != null) {
      boolean orphanHeader = false;
      for (Iterator i = cmdLineProps.keyIterator(); i.hasNext(); ) {
        Object k = i.next();
        if (!k.equals(COMMAND_LINE_CONF) && !keyList.contains(k)) {
          if (!orphanHeader) {
            out.println("");
            out.println("# ===== Other entries");
            orphanHeader = true;
          }
          Object v = cmdLineProps.getProperty(k, null);
          out.println(k + "=" + ((v != null) ? v : NULL_VALUE));
        }
      }
    }

    /* final blank line */
    out.println("");
  }
Ejemplo n.º 22
0
 private Set<String> initPlatformAnnotations() {
   Set<String> platformAnnotations = new HashSet<String>();
   platformAnnotations.add("java.lang.Deprecated");
   platformAnnotations.add("java.lang.Override");
   platformAnnotations.add("java.lang.SuppressWarnings");
   platformAnnotations.add("java.lang.annotation.Documented");
   platformAnnotations.add("java.lang.annotation.Inherited");
   platformAnnotations.add("java.lang.annotation.Retention");
   platformAnnotations.add("java.lang.annotation.Target");
   return Collections.unmodifiableSet(platformAnnotations);
 }
Ejemplo n.º 23
0
  /**
   * Checks that a callback method is present and correctly defined.
   *
   * <p>Having checked it, you can call it using callback().
   *
   * @param sCallback Name of callback method
   * @throws OmDeveloperException If the method doesn't exist or is defined incorrectly
   */
  public void checkCallback(String sCallback) throws OmDeveloperException {
    try {
      Method m = getClass().getMethod(sCallback, new Class[0]);

      if (m.getReturnType() != void.class)
        throw new OmDeveloperException("Callback method " + sCallback + "() must return void");
      if (!Modifier.isPublic(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() must be public");
      if (Modifier.isStatic(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() may not be static");
      if (Modifier.isAbstract(m.getModifiers()))
        throw new OmDeveloperException("Callback method " + sCallback + "() may not be abstract");

      sCheckedCallbacks.add(sCallback);
    } catch (NoSuchMethodException e) {
      throw new OmDeveloperException("Callback method " + sCallback + "() does not exist");
    }
  }
    public void invoke(MethodInvocation method) throws Throwable {
      if (method.isGetter()) {
        if (properties.containsKey(method.getName())) {
          method.setResult(properties.get(method.getName()));
          return;
        }
        if (unknown.contains(method.getName())) {
          return;
        }

        Object value;
        next.invoke(method);
        if (!method.found()) {
          unknown.add(method.getName());
          return;
        }
        value = method.getResult();
        properties.put(method.getName(), value);
        return;
      }

      next.invoke(method);
    }
Ejemplo n.º 25
0
 public void addRedefinedClassWithNativeMethods(@Nonnull String redefinedClassInternalName) {
   redefinedClassesWithNativeMethods.add(redefinedClassInternalName.replace('/', '.'));
 }
Ejemplo n.º 26
0
 /**
  * Insert an EmitterDescriptor into this set
  *
  * @param ed the EmitterDescriptor to insert
  */
 void add(EmitterDescriptor ed) {
   emitters.add(ed);
 }
Ejemplo n.º 27
0
  /** Generate an assembler for the opt compiler */
  public static void main(String[] args) {
    try {
      out = new FileWriter(System.getProperty("generateToDir") + "/AssemblerOpt.java");
    } catch (IOException e) {
      throw new Error(e);
    }

    emit("package org.jikesrvm.compilers.opt.mir2mc.ia32;\n\n");
    emit("import org.jikesrvm.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.ir.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.ir.ia32.*;\n\n");
    emit("import static org.jikesrvm.compilers.opt.ir.ia32.ArchOperators.*;\n\n");
    emit("import static org.jikesrvm.compilers.opt.OptimizingCompilerException.opt_assert;\n\n");
    emit("\n\n");

    emit("/**\n");
    emit(" *  This class is the automatically-generated assembler for\n");
    emit(" * the optimizing compiler.  It consists of methods that\n");
    emit(" * understand the possible operand combinations of each\n");
    emit(" * instruction type, and how to translate those operands to\n");
    emit(" * calls to the Assember low-level emit method\n");
    emit(" *\n");
    emit(" * It is generated by GenerateAssembler.java\n");
    emit(" *\n");
    emit(" */\n");
    emit("public class AssemblerOpt extends AssemblerBase {\n\n");

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" * @see org.jikesrvm.ArchitectureSpecific.Assembler\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("public AssemblerOpt(int bcSize, boolean print, IR ir) {\n");
    emitTab(2);
    emit("super(bcSize, print, ir);\n");
    emitTab(1);
    emit("}");
    emit("\n\n");

    Method[] emitters = lowLevelAsm.getDeclaredMethods();
    Set<String> opcodes = getOpcodes(emitters);

    Iterator<String> i = opcodes.iterator();
    while (i.hasNext()) {
      String opcode = (String) i.next();
      setCurrentOpcode(opcode);
      emitTab(1);
      emit("/**\n");
      emitTab(1);
      emit(" *  Emit the given instruction, assuming that\n");
      emitTab(1);
      emit(" * it is a " + currentFormat + " instruction\n");
      emitTab(1);
      emit(" * and has a " + currentOpcode + " operator\n");
      emitTab(1);
      emit(" *\n");
      emitTab(1);
      emit(" * @param inst the instruction to assemble\n");
      emitTab(1);
      emit(" */\n");
      emitTab(1);
      emit("private void do" + opcode + "(Instruction inst) {\n");
      EmitterSet emitter = buildSetForOpcode(emitters, opcode);
      boolean[][] tp = new boolean[4][ArgumentType.values().length];
      emitter.emitSet(opcode, tp, 2);
      emitTab(1);
      emit("}\n\n");
    }

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" *  The number of instructions emitted so far\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("private int instructionCount = 0;\n\n");

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" *  Assemble the given instruction\n");
    emitTab(1);
    emit(" *\n");
    emitTab(1);
    emit(" * @param inst the instruction to assemble\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("public void doInst(Instruction inst) {\n");
    emitTab(2);
    emit("instructionCount++;\n");
    emitTab(2);
    emit("resolveForwardReferences(instructionCount);\n");
    emitTab(2);
    emit("switch (inst.getOpcode()) {\n");

    Set<String> emittedOpcodes = new HashSet<String>();

    i = opcodes.iterator();
    while (i.hasNext()) {
      String opcode = i.next();
      Iterator<String> operators = getMatchingOperators(opcode).iterator();
      while (operators.hasNext()) {
        String operator = operators.next();
        emitTab(3);
        emittedOpcodes.add(operator);
        emit("case IA32_" + operator + "_opcode:\n");
      }
      emitTab(4);
      emit("do" + opcode + "(inst);\n");
      emitTab(4);
      emit("break;\n");
    }

    // Special case because doJCC is handwritten to add
    // logic for short-forward branches
    emittedOpcodes.add("JCC");
    emitTab(3);
    emit("case IA32_JCC_opcode:\n");
    emitTab(4);
    emit("doJCC(inst);\n");
    emitTab(4);
    emit("break;\n");

    // Special case because doJMP is handwritten to add
    // logic for short-forward branches
    emittedOpcodes.add("JMP");
    emitTab(3);
    emit("case IA32_JMP_opcode:\n");
    emitTab(4);
    emit("doJMP(inst);\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for IA32_LOCK which needs to call emitLockNextInstruction
    emittedOpcodes.add("LOCK");
    emitTab(3);
    emit("case IA32_LOCK_opcode:\n");
    emitTab(4);
    emit("emitLockNextInstruction();\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for PATCH_POINT
    emitTab(3);
    emit("case IG_PATCH_POINT_opcode:\n");
    emitTab(4);
    emit("emitPatchPoint();\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for LOWTABLESWITCH
    emitTab(3);
    emit("case MIR_LOWTABLESWITCH_opcode:\n");
    emitTab(4);
    emit("doLOWTABLESWITCH(inst);\n");
    emitTab(4);
    emit("// kludge table switches that are unusually long instructions\n");
    emitTab(4);
    emit("instructionCount += MIR_LowTableSwitch.getNumberOfTargets(inst);\n");
    emitTab(4);
    emit("break;\n");

    Set<String> errorOpcodes = getErrorOpcodes(emittedOpcodes);
    if (!errorOpcodes.isEmpty()) {
      i = errorOpcodes.iterator();
      while (i.hasNext()) {
        emitTab(3);
        emit("case IA32_" + i.next() + "_opcode:\n");
      }
      emitTab(4);
      emit(
          "throw new OptimizingCompilerException(inst + \" has unimplemented IA32 opcode (check excludedOpcodes)\");\n");
    }

    emitTab(2);
    emit("}\n");
    emitTab(2);
    emit("inst.setmcOffset( mi );\n");
    emitTab(1);
    emit("}\n\n");

    emit("\n}\n");

    try {
      out.close();
    } catch (IOException e) {
      throw new Error(e);
    }
  }
Ejemplo n.º 28
0
  // TODO: internal catch clauses?; catch and rethrow an annotation
  // processing error
  public JavaCompiler doProcessing(
      Context context,
      List<JCCompilationUnit> roots,
      List<ClassSymbol> classSymbols,
      Iterable<? extends PackageSymbol> pckSymbols) {

    TaskListener taskListener = context.get(TaskListener.class);
    log = Log.instance(context);

    Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>();
    for (PackageSymbol psym : pckSymbols) specifiedPackages.add(psym);
    this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages);

    Round round = new Round(context, roots, classSymbols);

    boolean errorStatus;
    boolean moreToDo;
    do {
      // Run processors for round n
      round.run(false, false);

      // Processors for round n have run to completion.
      // Check for errors and whether there is more work to do.
      errorStatus = round.unrecoverableError();
      moreToDo = moreToDo();

      round.showDiagnostics(errorStatus || showResolveErrors);

      // Set up next round.
      // Copy mutable collections returned from filer.
      round =
          round.next(
              new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()),
              new LinkedHashMap<String, JavaFileObject>(filer.getGeneratedClasses()));

      // Check for errors during setup.
      if (round.unrecoverableError()) errorStatus = true;

    } while (moreToDo && !errorStatus);

    // run last round
    round.run(true, errorStatus);
    round.showDiagnostics(true);

    filer.warnIfUnclosedFiles();
    warnIfUnmatchedOptions();

    /*
     * If an annotation processor raises an error in a round,
     * that round runs to completion and one last round occurs.
     * The last round may also occur because no more source or
     * class files have been generated.  Therefore, if an error
     * was raised on either of the last *two* rounds, the compile
     * should exit with a nonzero exit code.  The current value of
     * errorStatus holds whether or not an error was raised on the
     * second to last round; errorRaised() gives the error status
     * of the last round.
     */
    if (messager.errorRaised() || werror && round.warningCount() > 0 && round.errorCount() > 0)
      errorStatus = true;

    Set<JavaFileObject> newSourceFiles =
        new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects());
    roots = cleanTrees(round.roots);

    JavaCompiler compiler = round.finalCompiler(errorStatus);

    if (newSourceFiles.size() > 0) roots = roots.appendList(compiler.parseFiles(newSourceFiles));

    errorStatus = errorStatus || (compiler.errorCount() > 0);

    // Free resources
    this.close();

    if (taskListener != null)
      taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));

    if (errorStatus) {
      if (compiler.errorCount() == 0) compiler.log.nerrors++;
      return compiler;
    }

    if (procOnly && !foundTypeProcessors) {
      compiler.todo.clear();
    } else {
      if (procOnly && foundTypeProcessors) compiler.shouldStopPolicy = CompileState.FLOW;

      compiler.enterTrees(roots);
    }

    return compiler;
  }
Ejemplo n.º 29
0
  private void discoverAndRunProcs(
      Context context,
      Set<TypeElement> annotationsPresent,
      List<ClassSymbol> topLevelClasses,
      List<PackageSymbol> packageInfoFiles) {
    Map<String, TypeElement> unmatchedAnnotations =
        new HashMap<String, TypeElement>(annotationsPresent.size());

    for (TypeElement a : annotationsPresent) {
      unmatchedAnnotations.put(a.getQualifiedName().toString(), a);
    }

    // Give "*" processors a chance to match
    if (unmatchedAnnotations.size() == 0) unmatchedAnnotations.put("", null);

    DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
    // TODO: Create proper argument values; need past round
    // information to fill in this constructor.  Note that the 1
    // st round of processing could be the last round if there
    // were parse errors on the initial source files; however, we
    // are not doing processing in that case.

    Set<Element> rootElements = new LinkedHashSet<Element>();
    rootElements.addAll(topLevelClasses);
    rootElements.addAll(packageInfoFiles);
    rootElements = Collections.unmodifiableSet(rootElements);

    RoundEnvironment renv =
        new JavacRoundEnvironment(false, false, rootElements, JavacProcessingEnvironment.this);

    while (unmatchedAnnotations.size() > 0 && psi.hasNext()) {
      ProcessorState ps = psi.next();
      Set<String> matchedNames = new HashSet<String>();
      Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();

      for (Map.Entry<String, TypeElement> entry : unmatchedAnnotations.entrySet()) {
        String unmatchedAnnotationName = entry.getKey();
        if (ps.annotationSupported(unmatchedAnnotationName)) {
          matchedNames.add(unmatchedAnnotationName);
          TypeElement te = entry.getValue();
          if (te != null) typeElements.add(te);
        }
      }

      if (matchedNames.size() > 0 || ps.contributed) {
        boolean processingResult = callProcessor(ps.processor, typeElements, renv);
        ps.contributed = true;
        ps.removeSupportedOptions(unmatchedProcessorOptions);

        if (printProcessorInfo || verbose) {
          log.printNoteLines(
              "x.print.processor.info",
              ps.processor.getClass().getName(),
              matchedNames.toString(),
              processingResult);
        }

        if (processingResult) {
          unmatchedAnnotations.keySet().removeAll(matchedNames);
        }
      }
    }
    unmatchedAnnotations.remove("");

    if (lint && unmatchedAnnotations.size() > 0) {
      // Remove annotations processed by javac
      unmatchedAnnotations.keySet().removeAll(platformAnnotations);
      if (unmatchedAnnotations.size() > 0) {
        log = Log.instance(context);
        log.warning("proc.annotations.without.processors", unmatchedAnnotations.keySet());
      }
    }

    // Run contributing processors that haven't run yet
    psi.runContributingProcs(renv);

    // Debugging
    if (options.isSet("displayFilerState")) filer.displayState();
  }
  public void buildTypeGraph() {
    Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>();
    Map<String, File> openClassFiles = new HashMap<String, File>();
    // use global cache to load resource in/out of the same jar as the classes
    Set<String> resourceCacheSet = new HashSet<>();
    try {
      for (String path : pathsToScan) {
        File f = null;
        try {
          f = new File(path);
          if (!f.exists()
              || f.isDirectory()
              || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) {
            continue;
          }
          if (GENERATED_CLASSES_JAR.equals(f.getName())) {
            continue;
          }
          if (f.getName().endsWith("class")) {
            typeGraph.addNode(f);
            openClassFiles.put(path, f);
          } else {
            JarFile jar = new JarFile(path);
            openJarFiles.put(path, jar);
            java.util.Enumeration<JarEntry> entriesEnum = jar.entries();
            while (entriesEnum.hasMoreElements()) {
              final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
              String entryName = jarEntry.getName();
              if (jarEntry.isDirectory()) {
                continue;
              }
              if (entryName.endsWith("-javadoc.xml")) {
                try {
                  processJavadocXml(jar.getInputStream(jarEntry));
                  // break;
                } catch (Exception ex) {
                  LOG.warn("Cannot process javadoc {} : ", entryName, ex);
                }
              } else if (entryName.endsWith(".class")) {
                TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar);
                // check if any visited resources belong to this type
                for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext(); ) {
                  String entry = iter.next();
                  if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) {
                    newNode.setHasResource(true);
                    iter.remove();
                  }
                }
              } else {
                String className = entryName;
                boolean foundClass = false;
                // check if this resource belongs to any visited type
                while (className.contains("/")) {
                  className = className.substring(0, className.lastIndexOf('/'));
                  TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.'));
                  if (tgv != null) {
                    tgv.setHasResource(true);
                    foundClass = true;
                    break;
                  }
                }
                if (!foundClass) {
                  resourceCacheSet.add(entryName);
                }
              }
            }
          }
        } catch (IOException ex) {
          LOG.warn("Cannot process file {}", f, ex);
        }
      }

      typeGraph.trim();

      typeGraph.updatePortTypeInfoInTypeGraph(openJarFiles, openClassFiles);
    } finally {
      for (Entry<String, JarFile> entry : openJarFiles.entrySet()) {
        try {
          entry.getValue().close();
        } catch (IOException e) {
          DTThrowable.wrapIfChecked(e);
        }
      }
    }
  }