/**
   * Sort-based shuffle data uses an index called "shuffle_ShuffleId_MapId_0.index" into a data file
   * called "shuffle_ShuffleId_MapId_0.data". This logic is from IndexShuffleBlockResolver, and the
   * block id format is from ShuffleDataBlockId and ShuffleIndexBlockId.
   */
  private ManagedBuffer getSortBasedShuffleBlockData(
      ExecutorShuffleInfo executor, int shuffleId, int mapId, int reduceId) {
    File indexFile =
        getFile(
            executor.localDirs,
            executor.subDirsPerLocalDir,
            "shuffle_" + shuffleId + "_" + mapId + "_0.index");

    DataInputStream in = null;
    try {
      in = new DataInputStream(new FileInputStream(indexFile));
      in.skipBytes(reduceId * 8);
      long offset = in.readLong();
      long nextOffset = in.readLong();
      return new FileSegmentManagedBuffer(
          conf,
          getFile(
              executor.localDirs,
              executor.subDirsPerLocalDir,
              "shuffle_" + shuffleId + "_" + mapId + "_0.data"),
          offset,
          nextOffset - offset);
    } catch (IOException e) {
      throw new RuntimeException("Failed to open file: " + indexFile, e);
    } finally {
      if (in != null) {
        JavaUtils.closeQuietly(in);
      }
    }
  }
Beispiel #2
0
  /** Creates new ScriptTable */
  protected Script(DataInputStream dis, int offset) throws IOException {

    // Ensure we're in the right place
    dis.reset();
    dis.skipBytes(offset);

    // Start reading
    _defaultLangSysOffset = dis.readUnsignedShort();
    _langSysCount = dis.readUnsignedShort();
    if (_langSysCount > 0) {
      _langSysRecords = new LangSysRecord[_langSysCount];
      for (int i = 0; i < _langSysCount; i++) {
        _langSysRecords[i] = new LangSysRecord(dis);
      }
    }

    // Read the LangSys tables
    if (_langSysCount > 0) {
      _langSys = new LangSys[_langSysCount];
      for (int i = 0; i < _langSysCount; i++) {
        dis.reset();
        dis.skipBytes(offset + _langSysRecords[i].getOffset());
        _langSys[i] = new LangSys(dis);
      }
    }
    if (_defaultLangSysOffset > 0) {
      dis.reset();
      dis.skipBytes(offset + _defaultLangSysOffset);
      _defaultLangSys = new LangSys(dis);
    }
  }
Beispiel #3
0
  /**
   * Read the xml format
   *
   * @param name filename or url
   * @param iStream input stream
   * @return List of point sets
   */
  private List doReadGmap(String name, InputStream iStream) {
    List sets = new ArrayList();
    try {
      if (iStream == null) {
        iStream = IOUtil.getInputStream(name);
      }
      DataInputStream dis = new DataInputStream(iStream);
      short numBlks = dis.readShort();
      System.err.println("numBlks:" + numBlks);
      dis.skipBytes(252);

      for (int blockIdx = 0; blockIdx < numBlks; blockIdx++) {
        short numSegments = dis.readShort();
        System.err.println("segs=" + numSegments);
        dis.skipBytes(4);
        for (int segIdx = 0; segIdx < numSegments; segIdx++) {
          int nPts = dis.readShort();
          System.err.println("  pts=" + nPts);
          dis.skipBytes(4 * 5);
          for (int ptIdx = 0; ptIdx < nPts; ptIdx++) {
            float lat = Float.intBitsToFloat(dis.readShort());
            float lon = Float.intBitsToFloat(dis.readShort());
            //                        System.err.println("     lat:" + lat+"/"+lon);
          }

          //                    if(true)
          //                        break;
        }
      }

      double[] points = new double[] {-107, 40};

      RealTupleType coordMathType = new RealTupleType(RealType.Longitude, RealType.Latitude);
      float[][] part = new float[2][points.length / 2];
      for (int ptIdx = 0; ptIdx < points.length / 2; ptIdx++) {
        part[1][ptIdx] = (float) points[ptIdx * 2];
        part[0][ptIdx] = (float) points[ptIdx * 2 + 1];
      }
      sets.add(
          new MapSet(
              coordMathType,
              part,
              points.length / 2,
              (CoordinateSystem) null,
              (Unit[]) null,
              (ErrorEstimate[]) null,
              false /* no copy */));
    } catch (Exception exc) {
      exc.printStackTrace();
    }
    return sets;
  }
Beispiel #4
0
 protected void processOtherMsg(int msgsize, int msgtype, DataInputStream dIn)
     throws SocketException, IOException, java.lang.NullPointerException {
   dIn.skipBytes(msgsize - 2); // need to just skip this message because we don't recognize it
   ExpCoordinator.printer.print(
       new String("NCCPConnection.processOtherMsg skipping message " + msgsize + " " + msgtype));
   ExpCoordinator.printer.printHistory();
 }
Beispiel #5
0
 public static LigatureSubst read(DataInputStream dis, int offset) throws IOException {
   dis.reset();
   dis.skipBytes(offset);
   int format = dis.readUnsignedShort();
   if (format == 1) {
     return new LigatureSubstFormat1(dis, offset);
   }
   return null;
 }
Beispiel #6
0
  /** Read annotation element value from classfile. */
  private Object readAnnotationElementValue(final DataInputStream inp, Object[] constantPool)
      throws IOException {
    int tag = inp.readUnsignedByte();
    switch (tag) {
      case 'B':
      case 'C':
      case 'D':
      case 'F':
      case 'I':
      case 'J':
      case 'S':
      case 's':
        return readRefdString(inp, constantPool);

      case 'Z':
        {
          final Object s = readRefd(inp, constantPool);
          return s != null && s instanceof Integer && ((Integer) s).intValue() != 0;
        }
      case 'e':
        // enum_const_value
        inp.skipBytes(4);
        break;
      case 'c':
        // class_info_index
        inp.skipBytes(2);
        break;
      case '@':
        // Complex (nested) annotation
        return readAnnotation(inp, constantPool);
      case '[':
        // array_value
        final int count = inp.readUnsignedShort();
        for (int l = 0; l < count; ++l) {
          // Nested annotation element value
          readAnnotationElementValue(inp, constantPool);
        }
        break;
      default:
        throw new ClassFormatError(
            "Invalid annotation element type tag: 0x" + Integer.toHexString(tag));
    }
    return null;
  }
Beispiel #7
0
  public int skipBytesFromDataStream(DataInputStream in) {
    try {
      in.skipBytes(BYTESIZE);
    } catch (IOException ioerr) {
      ioerr.printStackTrace();
      return 0;
    }

    return BYTESIZE;
  }
  private static boolean littleEndian(String fn) throws IOException {
    InputStream is = new FileInputStream(fn);
    if (fn.endsWith(".gz")) is = new GZIPInputStream(is);
    DataInputStream di = new DataInputStream(is);

    di.skipBytes(40);
    short s = di.readShort();

    di.close();
    return (s < 1) || (s > 7);
  }
Beispiel #9
0
 @Override
 public Field parse(DataInputStream dis) throws ParseException {
   try {
     int strLen = dis.readInt();
     byte bs[] = new byte[strLen];
     dis.read(bs);
     dis.skipBytes(STRING_LEN - strLen);
     return new StringField(new String(bs), STRING_LEN);
   } catch (IOException e) {
     throw new ParseException("couldn't parse string", 0);
   }
 }
  @Override
  public final void visit(Set<Instance> resultSet, Filter filter) {
    if (resultSet.contains(this)) {
      return;
    }

    if (filter != null) {
      if (filter.accept(this)) {
        resultSet.add(this);
      }
    } else {
      resultSet.add(this);
    }

    State state = mHeap.mState;
    ClassObj isa = state.findClass(mClassId);
    int[] types = isa.mFieldTypes;
    ByteArrayInputStream bais = new ByteArrayInputStream(mFieldValues);
    DataInputStream dis = new DataInputStream(bais);
    final int N = types.length;

    /*
     * Spin through the list of fields, find all object references,
     * and list ourselves as a reference holder.
     */
    try {
      for (int i = 0; i < N; i++) {
        int type = types[i];
        int size = Types.getTypeSize(type);

        if (type == Types.OBJECT) {
          long id;

          if (size == 4) {
            id = dis.readInt();
          } else {
            id = dis.readLong();
          }

          Instance instance = state.findReference(id);

          if (instance != null) {
            instance.visit(resultSet, filter);
          }
        } else {
          dis.skipBytes(size);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  public String describeReferenceTo(long referent) {
    ClassObj isa = mHeap.mState.findClass(mClassId);
    int[] types = isa.mFieldTypes;
    String[] fieldNames = isa.mFieldNames;
    ByteArrayInputStream bais = new ByteArrayInputStream(mFieldValues);
    DataInputStream dis = new DataInputStream(bais);
    final int N = types.length;
    StringBuilder result = new StringBuilder("Referenced in field(s):");
    int numReferences = 0;

    /*
     * Spin through the list of fields, add info about the field
     * references to the output text.
     */
    try {
      for (int i = 0; i < N; i++) {
        int type = types[i];
        int size = Types.getTypeSize(type);

        if (type == Types.OBJECT) {
          long id;

          if (size == 4) {
            id = dis.readInt();
          } else {
            id = dis.readLong();
          }

          if (id == referent) {
            numReferences++;
            result.append("\n    ");
            result.append(fieldNames[i]);
          }
        } else {
          dis.skipBytes(size);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    /*
     *  TODO:  perform a similar loop over the static fields of isa
     */

    if (numReferences == 0) {
      return super.describeReferenceTo(referent);
    }

    return result.toString();
  }
 private long getLogOffsetEnd(File indexFile) throws Exception {
   long fileEndPointer;
   DataInputStream stream = new DataInputStream(new FileInputStream(indexFile));
   short version = stream.readShort();
   if (version == 0) {
     stream.skipBytes((2 * Integer.SIZE) / Byte.SIZE);
     fileEndPointer = stream.readLong();
   } else {
     throw new Exception(
         "Version read from " + indexFile.getName() + " is " + version + " (not 0)");
   }
   return fileEndPointer;
 }
  /** @tests java.io.DataInputStream#skipBytes(int) */
  public void test_skipBytesI() throws IOException {
    byte fileBytes[] = fileString.getBytes();
    os.write(fileBytes);
    os.close();
    openDataInputStream();
    dis.skipBytes(100);
    byte rbytes[] = new byte[fileString.length()];
    dis.read(rbytes, 0, 50);
    dis.close();
    assertTrue(
        "Incorrect data read", new String(rbytes, 0, 50).equals(fileString.substring(100, 150)));

    int skipped = 0;
    openDataInputStream();
    try {
      skipped = dis.skipBytes(50000);
    } catch (EOFException e) {
    }
    assertTrue(
        "Skipped should report " + fileString.length() + " not " + skipped,
        skipped == fileString.length());
  }
 @Override
 @Nonnull
 public OffsetInfo next() {
   try {
     long indexOffset = countingInputStream.getByteCount();
     int keysize = input.readUnsignedShort();
     input.skipBytes(keysize);
     Long dataOffset = input.readLong();
     skipPromotedIndexes();
     return new OffsetInfo(dataOffset, indexOffset);
   } catch (IOException e) {
     throw new IOError(e);
   }
 }
Beispiel #15
0
  /**
   * Set the starting position of the file
   *
   * @param startpos Starting position
   * @return -1 if fileIn is null or if dcc receive, else the result of fileIn.skipBytes()
   */
  public int setFileStart(final int startpos) {
    this.startpos = startpos;
    this.readSize = startpos;

    if (transferType == TransferType.SEND && fileIn != null) {
      try {
        this.startpos = fileIn.skipBytes(startpos);
        this.readSize = this.startpos;
        return this.startpos;
      } catch (IOException ioe) {
      }
    }

    return -1;
  }
Beispiel #16
0
  public static CaptureHeader read(InputStream in) throws IOException {
    CaptureHeader header = new CaptureHeader();

    DataInputStream data = new DataInputStream(in);
    int sizeRemaining = data.readInt();
    if (sizeRemaining >= size) {
      header.packetType = data.readInt();
      sizeRemaining -= 4;
      data.skipBytes(sizeRemaining);
      // VideoEngine.log.info("CaptureHeader type " + header.packetType);
    } else {
      throw new IOException("Not enough bytes remaining in stream");
    }

    return header;
  }
Beispiel #17
0
  /**
   * Skip a number of bits in the current input stream
   *
   * @param len The number of bits to skip
   * @throws IOException if an I/O error occurs
   */
  public void skipBits(int len) throws IOException {
    // the number of bits to skip is within the current byte
    if (8 - bitOffset > len) {
      bitOffset += len;
      return;
    }

    len += bitOffset - 8;
    final int i = len >> 3;
    if (i > 0) {
      dis.skipBytes(i);
      byteOffset += i;
    }
    byteRead = dis.readByte();
    byteOffset++;
    bitOffset = len & 7;
  }
Beispiel #18
0
  @NotNull
  private static String extract(@NotNull InputStream in, boolean forViewing)
      throws IOException, ParseException {
    StringBuffer sb = new StringBuffer();
    DataInputStream dis = new DataInputStream(in);

    /*
     * Check if the file starts with the FLAC identifier.
     */
    int id = dis.readInt();
    if (id != 0x664C6143) { // "fLaC"
      return sb.toString();
    }

    /*
     * Loop through each metadata block until METADATA BLOCK VORBIS COMMENT IS FOUND
     */
    long[] typesize = null;
    for (int i = 0;
        i < 100;
        i++) { // 100 is a safe-guard number to prevent an infinite loop due to corrupted data
      // stream
      byte[] data = new byte[4];
      dis.readFully(data);
      typesize = readMetadataBlock(data);
      long last = typesize[0];
      long type = typesize[1];
      long size = typesize[2];

      if (type != 0x04) {
        dis.skipBytes((int) size);
      } else {
        break;
      }
      if (last != 0) {
        break;
      }
    }

    VorbisComment vb = new VorbisComment();
    vb.parse(dis, sb, forViewing);

    return sb.toString();
  }
  /*
   * Get the lat/lons for the current segment
   */
  private float[][] getLatLons() throws VisADException {

    int numPairs = segList[segmentPointer][5] / 2;

    // DRM 4/20/2000
    if (numPairs < 0)
      throw new VisADException("Error in map file: Negative number of lat/lon pairs");

    int lat;
    int lon;
    int skipByte;
    long rc;
    float[][] lalo;

    float dLonMin = (float) lonMin / 10000.0f;

    try {
      skipByte = segList[segmentPointer][4] * 4 - position;
      try {
        din.skipBytes(skipByte);
      } catch (Exception e) {
        throw new VisADException("Base Map: IOException in skip" + e);
      }

      lalo = new float[2][numPairs];
      for (int i = 0; i < numPairs; i++) {
        lat = din.readInt();
        lon = din.readInt();
        lalo[0][i] = (float) lat / 10000.f;
        lalo[1][i] = (float) lon / 10000.f;
        if (isEastPositive) {
          lalo[1][i] = -lalo[1][i];
          if (lalo[1][i] < 0.0 && lalo[1][i] < dLonMin && lonMax > 1800000)
            lalo[1][i] = 360.f + lalo[1][i];
        }
      }
    } catch (IOException e) {
      throw new VisADException("Base Map: read past EOF");
    }
    position = position + skipByte + (8 * numPairs);
    return lalo;
  }
  public static CaptureRAM read(InputStream in) throws IOException {
    CaptureRAM ramFragment = new CaptureRAM();

    DataInputStream data = new DataInputStream(in);
    int sizeRemaining = data.readInt();
    if (sizeRemaining >= 8) {
      ramFragment.address = data.readInt();
      sizeRemaining -= 4;
      ramFragment.length = data.readInt();
      sizeRemaining -= 4;

      if (sizeRemaining > data.available()) {
        VideoEngine.log.warn(
            "CaptureRAM read want=" + sizeRemaining + " available=" + data.available());
      }

      if (sizeRemaining >= ramFragment.length) {
        ByteBuffer bb = ByteBuffer.allocate(ramFragment.length);
        byte[] b = bb.array();
        if (b == null) {
          throw new IOException("Buffer is not backed by an array");
        }
        data.readFully(b, 0, ramFragment.length);
        ramFragment.buffer = bb;
        sizeRemaining -= ramFragment.length;

        data.skipBytes(sizeRemaining);

        VideoEngine.log.info(
            String.format(
                "Loaded memory %08x - %08x (len %08x)",
                ramFragment.address, ramFragment.address + ramFragment.length, ramFragment.length));
      } else {
        throw new IOException("Not enough bytes remaining in stream");
      }
    } else {
      throw new IOException("Not enough bytes remaining in stream");
    }

    return ramFragment;
  }
  private void resolve(State state, ClassObj isa, int[] types, byte[] values) {
    ByteArrayInputStream bais = new ByteArrayInputStream(values);
    DataInputStream dis = new DataInputStream(bais);
    final int N = types.length;

    /*
     * Spin through the list of fields, find all object references,
     * and list ourselves as a reference holder.
     */
    try {
      for (int i = 0; i < N; i++) {
        int type = types[i];
        int size = Types.getTypeSize(type);

        if (type == Types.OBJECT) {
          long id;

          if (size == 4) {
            id = dis.readInt();
          } else {
            id = dis.readLong();
          }

          Instance instance = state.findReference(id);

          if (instance != null) {
            instance.addParent(this);
          }
        } else {
          dis.skipBytes(size);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #22
0
 /**
  * Reads a MIDI track chunk
  *
  * @param DataInputStream dis - the input stream to read from
  * @exception IOException
  */
 private void readTrackChunk(DataInputStream dis) throws IOException {
   // local variables for Track class
   Track track = new Track();
   // Insert new Track into a list of tracks
   this.trackList.addElement(track);
   int deltaTime = 0;
   if (VERBOSE) System.out.println("Reading Track ..........");
   // Read track header
   if (dis.readInt() != 0x4D54726B) { // If MTrk read is wrong
     throw new IOException("Track started in wrong place!!!!  ABORTING");
   } else { // If MTrk read ok get bytesRemaining
     dis.readInt();
   }
   // loop variables
   int status, oldStatus = 0, eventLength = 0;
   // Start gathering event data
   Event event = null;
   while (true) {
     try {
       // get variable length timestamp
       deltaTime = MidiUtil.readVarLength(dis);
       // mark stream so we can return if we need running status
       dis.mark(2);
       status = dis.readUnsignedByte();
       // decide on running status
       if (status < 0x80) { // set running status
         status = oldStatus;
         // return stream to before status read
         dis.reset();
       }
       // create default event of correct type
       if (status >= 0xFF) { // Meta Event
         int type = dis.readUnsignedByte();
         eventLength = MidiUtil.readVarLength(dis);
         event = MidiUtil.createMetaEvent(type);
       } else if (status >= 0xF0) { // System Exclusive --- NOT SUPPORTED
         System.out.println("SysEX---");
         eventLength = MidiUtil.readVarLength(dis);
       } else if (status >= 0x80) { // MIDI voice event
         short selection = (short) (status / 0x10);
         short midiChannel = (short) (status - (selection * 0x10));
         VoiceEvt evt = (VoiceEvt) MidiUtil.createVoiceEvent(selection);
         evt.setMidiChannel(midiChannel);
         event = evt;
         if (event == null) {
           throw new IOException("MIDI file read error: invalid voice event type!");
         }
       }
       oldStatus = status;
     } catch (Exception e) {
       e.printStackTrace();
       System.exit(1);
     }
     if (event != null) {
       // read data into the new event and
       // add the new event to the Track object
       event.setTime(deltaTime);
       event.read(dis);
       // if (VERBOSE) event.print();
       track.addEvent(event);
       // event.print();
       if (event instanceof EndTrack) break;
     } else {
       // skip the stream ahead to next valid event
       dis.skipBytes(eventLength);
     }
   }
 }
 @Override
 public int skipBytes(int n) throws IOException {
   return dataInput.skipBytes(n);
 }
  /**
   * Called from {@link ClassFileReader#readClass(TypeReference,DataInputStream)} to create an
   * instance of a RVMMethod by reading the relevant data from the argument bytecode stream.
   *
   * @param declaringClass the TypeReference of the class being loaded
   * @param constantPool the constantPool of the RVMClass object that's being constructed
   * @param memRef the canonical memberReference for this member.
   * @param modifiers modifiers associated with this member.
   * @param input the DataInputStream to read the method's attributes from
   */
  static RVMMethod readMethod(
      TypeReference declaringClass,
      int[] constantPool,
      MemberReference memRef,
      short modifiers,
      DataInputStream input)
      throws IOException {
    short tmp_localWords = 0;
    short tmp_operandWords = 0;
    byte[] tmp_bytecodes = null;
    ExceptionHandlerMap tmp_exceptionHandlerMap = null;
    TypeReference[] tmp_exceptionTypes = null;
    int[] tmp_lineNumberMap = null;
    LocalVariableTable tmp_localVariableTable = null;
    Atom tmp_signature = null;
    RVMAnnotation[] annotations = null;
    RVMAnnotation[][] parameterAnnotations = null;
    Object tmp_annotationDefault = null;

    // Read the attributes
    for (int i = 0, n = input.readUnsignedShort(); i < n; i++) {
      Atom attName = ClassFileReader.getUtf(constantPool, input.readUnsignedShort());
      int attLength = input.readInt();

      // Only bother to interpret non-boring Method attributes
      if (attName == RVMClassLoader.codeAttributeName) {
        tmp_operandWords = input.readShort();
        tmp_localWords = input.readShort();
        tmp_bytecodes = new byte[input.readInt()];
        input.readFully(tmp_bytecodes);
        tmp_exceptionHandlerMap = ExceptionHandlerMap.readExceptionHandlerMap(input, constantPool);

        // Read the attributes portion of the code attribute
        for (int j = 0, n2 = input.readUnsignedShort(); j < n2; j++) {
          attName = ClassFileReader.getUtf(constantPool, input.readUnsignedShort());
          attLength = input.readInt();

          if (attName == RVMClassLoader.lineNumberTableAttributeName) {
            int cnt = input.readUnsignedShort();
            if (cnt != 0) {
              tmp_lineNumberMap = new int[cnt];
              for (int k = 0; k < cnt; k++) {
                int startPC = input.readUnsignedShort();
                int lineNumber = input.readUnsignedShort();
                tmp_lineNumberMap[k] = (lineNumber << BITS_IN_SHORT) | startPC;
              }
            }
          } else if (attName == RVMClassLoader.localVariableTableAttributeName) {
            tmp_localVariableTable = LocalVariableTable.readLocalVariableTable(input, constantPool);
          } else {
            // All other entries in the attribute portion of the code attribute are boring.
            int skippedAmount = input.skipBytes(attLength);
            if (skippedAmount != attLength) {
              throw new IOException("Unexpected short skip");
            }
          }
        }
      } else if (attName == RVMClassLoader.exceptionsAttributeName) {
        int cnt = input.readUnsignedShort();
        if (cnt != 0) {
          tmp_exceptionTypes = new TypeReference[cnt];
          for (int j = 0, m = tmp_exceptionTypes.length; j < m; ++j) {
            tmp_exceptionTypes[j] =
                ClassFileReader.getTypeRef(constantPool, input.readUnsignedShort());
          }
        }
      } else if (attName == RVMClassLoader.syntheticAttributeName) {
        modifiers |= ACC_SYNTHETIC;
      } else if (attName == RVMClassLoader.signatureAttributeName) {
        tmp_signature = ClassFileReader.getUtf(constantPool, input.readUnsignedShort());
      } else if (attName == RVMClassLoader.runtimeVisibleAnnotationsAttributeName) {
        annotations =
            AnnotatedElement.readAnnotations(constantPool, input, declaringClass.getClassLoader());
      } else if (attName == RVMClassLoader.runtimeVisibleParameterAnnotationsAttributeName) {
        int numParameters = input.readByte() & 0xFF;
        parameterAnnotations = new RVMAnnotation[numParameters][];
        for (int a = 0; a < numParameters; ++a) {
          parameterAnnotations[a] =
              AnnotatedElement.readAnnotations(
                  constantPool, input, declaringClass.getClassLoader());
        }
      } else if (attName == RVMClassLoader.annotationDefaultAttributeName) {
        try {
          tmp_annotationDefault =
              RVMAnnotation.readValue(
                  memRef.asMethodReference().getReturnType(),
                  constantPool,
                  input,
                  declaringClass.getClassLoader());
        } catch (ClassNotFoundException e) {
          throw new Error(e);
        }
      } else {
        // all other method attributes are boring
        int skippedAmount = input.skipBytes(attLength);
        if (skippedAmount != attLength) {
          throw new IOException("Unexpected short skip");
        }
      }
    }
    RVMMethod method;
    if ((modifiers & ACC_NATIVE) != 0) {
      method =
          new NativeMethod(
              declaringClass,
              memRef,
              modifiers,
              tmp_exceptionTypes,
              tmp_signature,
              annotations,
              parameterAnnotations,
              tmp_annotationDefault);
    } else if ((modifiers & ACC_ABSTRACT) != 0) {
      method =
          new AbstractMethod(
              declaringClass,
              memRef,
              modifiers,
              tmp_exceptionTypes,
              tmp_signature,
              annotations,
              parameterAnnotations,
              tmp_annotationDefault);

    } else {
      method =
          new NormalMethod(
              declaringClass,
              memRef,
              modifiers,
              tmp_exceptionTypes,
              tmp_localWords,
              tmp_operandWords,
              tmp_bytecodes,
              tmp_exceptionHandlerMap,
              tmp_lineNumberMap,
              tmp_localVariableTable,
              constantPool,
              tmp_signature,
              annotations,
              parameterAnnotations,
              tmp_annotationDefault);
    }
    return method;
  }
Beispiel #25
0
  /** Directly examine contents of classfile binary header. */
  private void readFromInputStream(final InputStream inputStream) throws IOException {
    DataInputStream inp = new DataInputStream(new BufferedInputStream(inputStream, 1024));

    // Magic
    if (inp.readInt() != 0xCAFEBABE) {
      // Not classfile
      throw new IOException("Not a class file");
    }

    // Minor version
    inp.readUnsignedShort();
    // Major version
    inp.readUnsignedShort();

    // Constant pool count (1-indexed, zeroth entry not used)
    int cpCount = inp.readUnsignedShort();
    // Constant pool
    Object[] constantPool = new Object[cpCount];
    for (int i = 1; i < cpCount; ++i) {
      final int tag = inp.readUnsignedByte();
      switch (tag) {
        case 1: // Modified UTF8
          constantPool[i] = inp.readUTF();
          break;
        case 3: // int
          constantPool[i] = inp.readInt();
          break;
        case 4: // float
          constantPool[i] = inp.readFloat();
          break;
        case 5: // long
          constantPool[i] = inp.readLong();
          i++;
          break;
        case 6: // double
          constantPool[i] = inp.readDouble();
          i++; // double slot
          break;
        case 7: // Class
        case 8: // String
          // Forward or backward reference a Modified UTF8 entry
          constantPool[i] = inp.readUnsignedShort();
          break;
        case 9: // field ref
        case 10: // method ref
        case 11: // interface ref
        case 12: // name and type
          inp.skipBytes(4); // two shorts
          break;
        case 15: // method handle
          inp.skipBytes(3);
          break;
        case 16: // method type
          inp.skipBytes(2);
          break;
        case 18: // invoke dynamic
          inp.skipBytes(4);
          break;
        default:
          throw new ClassFormatError("Unkown tag value for constant pool entry: " + tag);
      }
    }

    // Access flags
    int flags = inp.readUnsignedShort();
    isInterface = (flags & 0x0200) != 0;

    // This class name, with slashes replaced with dots
    String name = readRefdString(inp, constantPool).replace('/', '.');
    if (this.name == null) {
      this.name = name;
    } else {
      if (!this.name.equals(name))
        throw new IllegalStateException(
            format("Class name %s and %s do not match", name, this.name));
    }
    // Superclass name, with slashes replaced with dots
    final String superclassName = toClassName(readRefdString(inp, constantPool));
    superclass = superclassName == null ? null : classInfoLoader.get(superclassName);

    // Interfaces
    int interfaceCount = inp.readUnsignedShort();
    for (int i = 0; i < interfaceCount; i++) {
      interfaces.add(classInfoLoader.get(toClassName(readRefdString(inp, constantPool))));
    }

    // Fields
    int fieldCount = inp.readUnsignedShort();
    for (int i = 0; i < fieldCount; i++) {
      inp.skipBytes(2); // access_flags
      final String fieldName = readRefdString(inp, constantPool); // name_index,

      String fieldDescriptor = readRefdString(inp, constantPool); // name_index,
      if (fieldDescriptor.startsWith("L") && fieldDescriptor.endsWith(";")) {
        fieldDescriptor =
            fieldDescriptor.substring(1, fieldDescriptor.length() - 1).replace("/", ".");
      }

      final FieldInfo fieldInfo = new FieldInfo(fieldName, classInfoLoader.get(fieldDescriptor));
      fields.put(fieldName, fieldInfo);

      int attributesCount = inp.readUnsignedShort();
      for (int j = 0; j < attributesCount; j++) {
        String attributeName = readRefdString(inp, constantPool);
        int attributeLength = inp.readInt();
        if ("RuntimeVisibleAnnotations".equals(attributeName)) {
          int annotationCount = inp.readUnsignedShort();
          for (int m = 0; m < annotationCount; m++) {
            AnnotationInfo annotation = readAnnotation(inp, constantPool);
            fieldInfo.annotations.put(annotation.annotationClass.getName(), annotation);
          }
        } else {
          inp.skipBytes(attributeLength);
        }
      }
    }

    // Methods
    int methodCount = inp.readUnsignedShort();
    for (int i = 0; i < methodCount; i++) {
      inp.skipBytes(6); // access_flags, name_index, descriptor_index
      int attributesCount = inp.readUnsignedShort();
      for (int j = 0; j < attributesCount; j++) {
        inp.skipBytes(2); // attribute_name_index
        int attributeLength = inp.readInt();
        inp.skipBytes(attributeLength);
      }
    }

    // Attributes (including class annotations)
    int attributesCount = inp.readUnsignedShort();
    for (int i = 0; i < attributesCount; i++) {
      String attributeName = readRefdString(inp, constantPool);
      int attributeLength = inp.readInt();
      if ("RuntimeVisibleAnnotations".equals(attributeName)) {
        int annotationCount = inp.readUnsignedShort();
        for (int m = 0; m < annotationCount; m++) {
          AnnotationInfo annotation = readAnnotation(inp, constantPool);
          annotations.put(annotation.annotationClass.getName(), annotation);
        }
      } else {
        inp.skipBytes(attributeLength);
      }
    }
  }
Beispiel #26
0
  private DF selectDFInternal(CommandAPDU cmd, TokenPath targetPath) throws IOException {

    try {
      ResponseAPDU resp = this.channel.transmit(cmd);

      DataInputStream dis = getSelectFileData(resp);

      long bodySize = 0;
      int acLifeCycle = TokenFileAcl.AC_ALWAYS;
      int acUpdate = TokenFileAcl.AC_ALWAYS;
      int acAppend = TokenFileAcl.AC_ALWAYS;
      int acDeactivate = TokenFileAcl.AC_ALWAYS;
      int acActivate = TokenFileAcl.AC_ALWAYS;
      int acDelete = TokenFileAcl.AC_ALWAYS;
      int acAdmin = TokenFileAcl.AC_ALWAYS;
      int acCreate = TokenFileAcl.AC_ALWAYS;

      int tag;

      while ((tag = dis.read()) >= 0) {
        int n = dis.read();
        if (n < 0) break;

        switch (tag) {
          case 0x81:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x81.");
            bodySize = dis.readUnsignedShort();
            break;

          case 0x83:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
            int tpath = dis.readUnsignedShort();
            if (tpath != targetPath.getTailID())
              throw new IOException(
                  "File ID ["
                      + PathHelper.formatID(tpath)
                      + "] reported by SELECT FILE differs from requested ID ["
                      + PathHelper.formatID(targetPath.getTailID())
                      + "].");
            break;

          case 0x86:
            if (n >= 1) acLifeCycle = dis.read();
            if (n >= 2) acUpdate = dis.read();
            if (n >= 3) acAppend = dis.read();
            if (n >= 4) acDeactivate = dis.read();
            if (n >= 5) acActivate = dis.read();
            if (n >= 6) acDelete = dis.read();
            if (n >= 7) acAdmin = dis.read();
            if (n >= 8) acCreate = dis.read();

            if (n != 8) log.warn("Invalid length [" + n + "] of FCI tag 0x86 for DF.");

            if (n > 8) dis.skipBytes(n - 8);
            break;

          default:
            byte[] tmp = new byte[n];
            dis.readFully(tmp);
            log.warn(
                "skipping FCI tag [0x"
                    + Integer.toHexString(tag)
                    + "], data ["
                    + Util.asHex(tmp)
                    + "].");
        }
      }

      DF df =
          new DF(
              targetPath,
              bodySize,
              acLifeCycle,
              acUpdate,
              acAppend,
              acDeactivate,
              acActivate,
              acDelete,
              acAdmin,
              acCreate);

      this.currentFile = df;
      return df;

    } catch (CardException e) {
      throw new PKCS15Exception("Error sending select MF", e);
    }
  }
 @Override
 public int skipBytes(int n) throws IOException {
   return in.skipBytes(n);
 }
Beispiel #28
0
  public static Object3D[] load(byte[] data, int offset) {
    DataInputStream old = dis;
    dis = new DataInputStream(new ByteArrayInputStream(data));

    try {
      while (dis.available() > 0) {
        int objectType = readByte();
        int length = readInt();

        System.out.println("objectType: " + objectType);
        System.out.println("length: " + length);

        dis.mark(Integer.MAX_VALUE);

        if (objectType == 0) {
          int versionHigh = readByte();
          int versionLow = readByte();
          boolean hasExternalReferences = readBoolean();
          int totolFileSize = readInt();
          int approximateContentSize = readInt();
          String authoringField = readString();

          objs.addElement(new Group()); // dummy
        } else if (objectType == 255) {
          // TODO: load external resource
          System.out.println("Loader: Loading external resources not implemented.");
          String uri = readString();
        } else if (objectType == 1) {
          System.out.println("Loader: AnimationController not implemented.");
          objs.addElement(new Group()); // dummy
        } else if (objectType == 2) {
          System.out.println("Loader: AnimationTrack not implemented.");
          objs.addElement(new Group()); // dummy
        } else if (objectType == 3) {
          // System.out.println("Appearance");
          Appearance appearance = new Appearance();
          loadObject3D(appearance);
          appearance.setLayer(readByte());
          appearance.setCompositingMode((CompositingMode) getObject(readInt()));
          appearance.setFog((Fog) getObject(readInt()));
          appearance.setPolygonMode((PolygonMode) getObject(readInt()));
          appearance.setMaterial((Material) getObject(readInt()));
          int numTextures = readInt();
          for (int i = 0; i < numTextures; ++i)
            appearance.setTexture(i, (Texture2D) getObject(readInt()));
          objs.addElement(appearance);
        } else if (objectType == 4) {
          // System.out.println("Background");
          Background background = new Background();
          loadObject3D(background);
          background.setColor(readRGBA());
          background.setImage((Image2D) getObject(readInt()));
          int modeX = readByte();
          int modeY = readByte();
          background.setImageMode(modeX, modeY);
          int cropX = readInt();
          int cropY = readInt();
          int cropWidth = readInt();
          int cropHeight = readInt();
          background.setCrop(cropX, cropY, cropWidth, cropHeight);
          background.setDepthClearEnable(readBoolean());
          background.setColorClearEnable(readBoolean());
          objs.addElement(background); // dummy
        } else if (objectType == 5) {
          // System.out.println("Camera");

          Camera camera = new Camera();
          loadNode(camera);

          int projectionType = readByte();
          if (projectionType == Camera.GENERIC) {
            Transform t = new Transform();
            t.set(readMatrix());
            camera.setGeneric(t);
          } else {
            float fovy = readFloat();
            float aspect = readFloat();
            float near = readFloat();
            float far = readFloat();
            if (projectionType == Camera.PARALLEL) camera.setParallel(fovy, aspect, near, far);
            else camera.setPerspective(fovy, aspect, near, far);
          }
          objs.addElement(camera);
        } else if (objectType == 6) {
          // System.out.println("CompositingMode");
          CompositingMode compositingMode = new CompositingMode();
          loadObject3D(compositingMode);
          compositingMode.setDepthTestEnabled(readBoolean());
          compositingMode.setDepthWriteEnabled(readBoolean());
          compositingMode.setColorWriteEnabled(readBoolean());
          compositingMode.setAlphaWriteEnabled(readBoolean());
          compositingMode.setBlending(readByte());
          compositingMode.setAlphaThreshold((float) readByte() / 255.0f);
          compositingMode.setDepthOffsetFactor(readFloat());
          compositingMode.setDepthOffsetUnits(readFloat());
          objs.addElement(compositingMode);
        } else if (objectType == 7) {
          // System.out.println("Fog");
          Fog fog = new Fog();
          loadObject3D(fog);
          fog.setColor(readRGB());
          fog.setMode(readByte());
          if (fog.getMode() == Fog.EXPONENTIAL) fog.setDensity(readFloat());
          else {
            fog.setNearDistance(readFloat());
            fog.setFarDistance(readFloat());
          }
          objs.addElement(fog);
        } else if (objectType == 9) {
          // System.out.println("Group");
          Group group = new Group();
          loadGroup(group);
          objs.addElement(group);
        } else if (objectType == 10) {
          // System.out.println("Image2D");
          Image2D image = null;
          loadObject3D(new Group()); // dummy
          int format = readByte();
          boolean isMutable = readBoolean();
          int width = readInt();
          int height = readInt();
          if (!isMutable) {
            // Read palette
            int paletteSize = readInt();
            byte[] palette = null;
            if (paletteSize > 0) {
              palette = new byte[paletteSize];
              dis.readFully(palette);
            }
            // Read pixels
            int pixelSize = readInt();
            byte[] pixel = new byte[pixelSize];
            dis.readFully(pixel);
            // Create image
            if (palette != null) image = new Image2D(format, width, height, pixel, palette);
            else image = new Image2D(format, width, height, pixel);
          } else image = new Image2D(format, width, height);

          dis.reset();
          loadObject3D(image);

          objs.addElement(image);
        } else if (objectType == 19) {
          System.out.println("Loader: KeyframeSequence not implemented.");
          /*
          Byte          interpolation;
          Byte          repeatMode;
          Byte          encoding;
          UInt32        duration;
          UInt32        validRangeFirst;
          UInt32        validRangeLast;

          UInt32        componentCount;
          UInt32        keyframeCount;

          IF encoding == 0

          FOR each key frame...

          UInt32                  time;
          Float32[componentCount] vectorValue;

          END

          ELSE IF encoding == 1

          Float32[componentCount] vectorBias;
          Float32[componentCount] vectorScale;

          FOR each key frame...

          UInt32               time;
          Byte[componentCount] vectorValue;

          END

          ELSE IF encoding == 2

          Float32[componentCount] vectorBias;
          Float32[componentCount] vectorScale;

          FOR each key frame...

          UInt32                 time;
          UInt16[componentCount] vectorValue;

          END

          END
          */
          objs.addElement(new Group()); // dummy
        } else if (objectType == 12) {
          // System.out.println("Light");
          Light light = new Light();
          loadNode(light);
          float constant = readFloat();
          float linear = readFloat();
          float quadratic = readFloat();
          light.setAttenuation(constant, linear, quadratic);
          light.setColor(readRGB());
          light.setMode(readByte());
          light.setIntensity(readFloat());
          light.setSpotAngle(readFloat());
          light.setSpotExponent(readFloat());
          objs.addElement(light);
        } else if (objectType == 13) {
          // System.out.println("Material");
          Material material = new Material();
          loadObject3D(material);
          material.setColor(Material.AMBIENT, readRGB());
          material.setColor(Material.DIFFUSE, readRGBA());
          material.setColor(Material.EMISSIVE, readRGB());
          material.setColor(Material.SPECULAR, readRGB());
          material.setShininess(readFloat());
          material.setVertexColorTrackingEnable(readBoolean());
          objs.addElement(material);
        } else if (objectType == 14) {
          // System.out.println("Mesh");

          loadNode(new Group()); // dummy

          VertexBuffer vertices = (VertexBuffer) getObject(readInt());
          int submeshCount = readInt();

          IndexBuffer[] submeshes = new IndexBuffer[submeshCount];
          Appearance[] appearances = new Appearance[submeshCount];
          for (int i = 0; i < submeshCount; ++i) {
            submeshes[i] = (IndexBuffer) getObject(readInt());
            appearances[i] = (Appearance) getObject(readInt());
          }
          Mesh mesh = new Mesh(vertices, submeshes, appearances);

          dis.reset();
          loadNode(mesh);

          objs.addElement(mesh);
        } else if (objectType == 15) {
          System.out.println("Loader: MorphingMesh not implemented.");
          /*
          UInt32        morphTargetCount;

          FOR each target buffer...

          ObjectIndex   morphTarget;
          Float32       initialWeight;

          END
          */
          objs.addElement(new Group()); // dummy
        } else if (objectType == 8) {
          // System.out.println("PolygonMode");
          PolygonMode polygonMode = new PolygonMode();
          loadObject3D(polygonMode);
          polygonMode.setCulling(readByte());
          polygonMode.setShading(readByte());
          polygonMode.setWinding(readByte());
          polygonMode.setTwoSidedLightingEnable(readBoolean());
          polygonMode.setLocalCameraLightingEnable(readBoolean());
          polygonMode.setPerspectiveCorrectionEnable(readBoolean());
          objs.addElement(polygonMode);
        } else if (objectType == 16) {
          System.out.println("Loader: SkinnedMesh not implemented.");
          /*
          ObjectIndex   skeleton;

          UInt32        transformReferenceCount;

          FOR each bone reference...

          ObjectIndex   transformNode;
          UInt32        firstVertex;
          UInt32        vertexCount;
          Int32         weight;

          END
          */
          objs.addElement(new Group()); // dummy
        } else if (objectType == 18) {
          System.out.println("Loader: Sprite not implemented.");
          /*
          ObjectIndex   image;
          ObjectIndex   appearance;

          Boolean       isScaled;

          Int32         cropX;
          Int32         cropY;
          Int32         cropWidth;
          Int32         cropHeight;
          */
          objs.addElement(new Group()); // dummy
        } else if (objectType == 17) {
          // System.out.println("Texture2D");

          loadTransformable(new Group()); // dummy

          Texture2D texture = new Texture2D((Image2D) getObject(readInt()));
          texture.setBlendColor(readRGB());
          texture.setBlending(readByte());
          int wrapS = readByte();
          int wrapT = readByte();
          texture.setWrapping(wrapS, wrapT);
          int levelFilter = readByte();
          int imageFilter = readByte();
          texture.setFiltering(levelFilter, imageFilter);

          dis.reset();
          loadTransformable(texture);

          objs.addElement(texture);
        } else if (objectType == 11) {
          // System.out.println("TriangleStripArray");

          loadObject3D(new Group()); // dummy

          int encoding = readByte();
          int firstIndex = 0;
          int[] indices = null;
          if (encoding == 0) firstIndex = readInt();
          else if (encoding == 1) firstIndex = readByte();
          else if (encoding == 2) firstIndex = readShort();
          else if (encoding == 128) {
            int numIndices = readInt();
            indices = new int[numIndices];
            for (int i = 0; i < numIndices; ++i) indices[i] = readInt();
          } else if (encoding == 129) {
            int numIndices = readInt();
            indices = new int[numIndices];
            for (int i = 0; i < numIndices; ++i) indices[i] = readByte();
          } else if (encoding == 130) {
            int numIndices = readInt();
            indices = new int[numIndices];
            for (int i = 0; i < numIndices; ++i) indices[i] = readShort();
          }

          int numStripLengths = readInt();
          int[] stripLengths = new int[numStripLengths];
          for (int i = 0; i < numStripLengths; ++i) stripLengths[i] = readInt();

          dis.reset();

          TriangleStripArray triStrip = null;
          if (indices == null) triStrip = new TriangleStripArray(firstIndex, stripLengths);
          else triStrip = new TriangleStripArray(indices, stripLengths);

          loadObject3D(triStrip);

          objs.addElement(triStrip);
        } else if (objectType == 20) {
          // System.out.println("VertexArray");

          loadObject3D(new Group()); // dummy

          int componentSize = readByte();
          int componentCount = readByte();
          int encoding = readByte();
          int vertexCount = readShort();

          VertexArray vertices = new VertexArray(vertexCount, componentCount, componentSize);

          if (componentSize == 1) {
            byte[] values = new byte[componentCount * vertexCount];
            if (encoding == 0) dis.readFully(values);
            else {
              byte last = 0;
              for (int i = 0; i < vertexCount * componentCount; ++i) {
                last += readByte();
                values[i] = last;
              }
            }
            vertices.set(0, vertexCount, values);
          } else {
            short last = 0;
            short[] values = new short[componentCount * vertexCount];
            for (int i = 0; i < componentCount * vertexCount; ++i) {
              if (encoding == 0) values[i] = (short) readShort();
              else {
                last += (short) readShort();
                values[i] = last;
              }
            }
            vertices.set(0, vertexCount, values);
          }

          dis.reset();
          loadObject3D(vertices);

          objs.addElement(vertices);
        } else if (objectType == 21) {
          // System.out.println("VertexBuffer");

          VertexBuffer vertices = new VertexBuffer();
          loadObject3D(vertices);

          vertices.setDefaultColor(readRGBA());

          VertexArray positions = (VertexArray) getObject(readInt());
          float[] bias = new float[3];
          bias[0] = readFloat();
          bias[1] = readFloat();
          bias[2] = readFloat();
          float scale = readFloat();
          vertices.setPositions(positions, scale, bias);

          vertices.setNormals((VertexArray) getObject(readInt()));
          vertices.setColors((VertexArray) getObject(readInt()));

          int texCoordArrayCount = readInt();
          for (int i = 0; i < texCoordArrayCount; ++i) {
            VertexArray texcoords = (VertexArray) getObject(readInt());
            bias[0] = readFloat();
            bias[1] = readFloat();
            bias[2] = readFloat();
            scale = readFloat();
            vertices.setTexCoords(i, texcoords, scale, bias);
          }

          objs.addElement(vertices);
        } else if (objectType == 22) {
          // System.out.println("World");

          World world = new World();
          loadGroup(world);

          world.setActiveCamera((Camera) getObject(readInt()));
          world.setBackground((Background) getObject(readInt()));
          objs.addElement(world);
        } else {
          System.out.println("Loader: unsupported objectType " + objectType + ".");
        }

        dis.reset();
        dis.skipBytes(length);
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e.getMessage());
      e.printStackTrace();
    }

    dis = old;
    return null;
  }
Beispiel #29
0
  /* (non-Javadoc)
   * @see org.opensc.pkcs15.token.Token#selectEF(int)
   */
  @Override
  public EF selectEF(int path) throws IOException {

    if (this.currentFile == null) throw new IOException("No current DF selected.");

    // SELECT FILE, P1=0x02, P2=0x00, no data -> select EF
    CommandAPDU cmd =
        new CommandAPDU(0x00, 0xA4, 0x02, 0x00, PathHelper.idToPath(path), DEFAULT_LE);

    try {
      ResponseAPDU resp = this.channel.transmit(cmd);

      DataInputStream dis = getSelectFileData(resp);

      long fileSize = 0;
      int acRead = TokenFileAcl.AC_ALWAYS;
      int acUpdate = TokenFileAcl.AC_ALWAYS;
      int acAppend = TokenFileAcl.AC_ALWAYS;
      int acDeactivate = TokenFileAcl.AC_ALWAYS;
      int acActivate = TokenFileAcl.AC_ALWAYS;
      int acDelete = TokenFileAcl.AC_ALWAYS;
      int acAdmin = TokenFileAcl.AC_ALWAYS;
      int acIncrease = TokenFileAcl.AC_ALWAYS;
      int acDecrease = TokenFileAcl.AC_ALWAYS;

      int tag;

      while ((tag = dis.read()) >= 0) {
        int n = dis.read();
        if (n < 0) break;

        switch (tag) {
          case 0x80:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x80.");
            fileSize = dis.readUnsignedShort();
            break;

          case 0x83:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
            int tpath = dis.readUnsignedShort();
            if (tpath != path)
              throw new IOException(
                  "File ID ["
                      + PathHelper.formatID(tpath)
                      + "] reported by SELECT FILE differs from requested ID ["
                      + PathHelper.formatID(path)
                      + "].");
            break;

          case 0x86:
            if (n >= 1) acRead = dis.read();
            if (n >= 2) acUpdate = dis.read();
            if (n >= 3) acAppend = dis.read();
            if (n >= 4) acDeactivate = dis.read();
            if (n >= 5) acActivate = dis.read();
            if (n >= 6) acDelete = dis.read();
            if (n >= 7) acAdmin = dis.read();
            if (n >= 8) acIncrease = dis.read();
            if (n >= 9) acDecrease = dis.read();

            if (n != 9) log.warn("Invalid length [" + n + "] of FCI tag 0x86 for EF.");

            if (n > 9) dis.skipBytes(n - 9);
            break;

          default:
            byte[] tmp = new byte[n];
            dis.readFully(tmp);
            log.warn(
                "skipping FCI tag [0x"
                    + Integer.toHexString(tag)
                    + "], data ["
                    + Util.asHex(tmp)
                    + "].");
        }
      }

      EF ef =
          new EF(
              new TokenPath(this.currentFile.getPath(), path),
              fileSize,
              acRead,
              acUpdate,
              acAppend,
              acDeactivate,
              acActivate,
              acDelete,
              acAdmin,
              acIncrease,
              acDecrease);

      this.currentFile = ef;
      return ef;

    } catch (CardException e) {
      throw new PKCS15Exception("Error sending select MF", e);
    }
  }
Beispiel #30
0
  /* (non-Javadoc)
   * @see org.opensc.pkcs15.token.Token#selectMF()
   */
  @Override
  public MF selectMF() throws IOException {

    // SELECT FILE, P1=0x00, P2=0x00, no data -> select MF
    CommandAPDU cmd = new CommandAPDU(0x00, 0xA4, 0x00, 0x00, DEFAULT_LE);

    try {
      ResponseAPDU resp = this.channel.transmit(cmd);

      DataInputStream dis = getSelectFileData(resp);

      long bodySize = 0;
      int acLifeCycle = TokenFileAcl.AC_ALWAYS;
      int acUpdate = TokenFileAcl.AC_ALWAYS;
      int acAppend = TokenFileAcl.AC_ALWAYS;
      int acDeactivate = TokenFileAcl.AC_ALWAYS;
      int acActivate = TokenFileAcl.AC_ALWAYS;
      int acDelete = TokenFileAcl.AC_ALWAYS;
      int acAdmin = TokenFileAcl.AC_ALWAYS;
      int acCreate = TokenFileAcl.AC_ALWAYS;
      int acExecute = TokenFileAcl.AC_ALWAYS;
      int acAllocate = TokenFileAcl.AC_ALWAYS;

      int tag;

      while ((tag = dis.read()) >= 0) {
        int n = dis.read();
        if (n < 0) break;

        switch (tag) {
          case 0x81:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x81.");
            bodySize = dis.readUnsignedShort();
            break;

          case 0x83:
            if (n != 2) throw new IOException("Invalid length [" + n + "] of FCI tag 0x83.");
            int tpath = dis.readUnsignedShort();
            if (tpath != PathHelper.MF_ID)
              throw new IOException(
                  "File ID ["
                      + PathHelper.formatID(tpath)
                      + "] reported by SELECT FILE differs from requested ID ["
                      + PathHelper.formatID(PathHelper.MF_ID)
                      + "].");
            break;

          case 0x86:
            if (n >= 1) acLifeCycle = dis.read();
            if (n >= 2) acUpdate = dis.read();
            if (n >= 3) acAppend = dis.read();
            if (n >= 4) acDeactivate = dis.read();
            if (n >= 5) acActivate = dis.read();
            if (n >= 6) acDelete = dis.read();
            if (n >= 7) acAdmin = dis.read();
            if (n >= 8) acCreate = dis.read();
            if (n >= 9) acExecute = dis.read();
            if (n >= 10) acAllocate = dis.read();

            if (n != 10) log.warn("Invalid length [" + n + "] of FCI tag 0x86 for MF.");

            if (n > 10) dis.skipBytes(n - 10);
            break;

          default:
            byte[] tmp = new byte[n];
            dis.readFully(tmp);
            log.warn(
                "skipping FCI tag [0x"
                    + Integer.toHexString(tag)
                    + "], data ["
                    + Util.asHex(tmp)
                    + "].");
        }
      }

      MF mf =
          new MF(
              PathHelper.MF_PATH,
              bodySize,
              acLifeCycle,
              acUpdate,
              acAppend,
              acDeactivate,
              acActivate,
              acDelete,
              acAdmin,
              acCreate,
              acExecute,
              acAllocate);

      this.currentFile = mf;
      return mf;

    } catch (CardException e) {
      throw new PKCS15Exception("Error sending select MF", e);
    }
  }