示例#1
0
  /**
   * Convert the given bytes into a <code>JdwpPacket</code>. Uses the abstract method <code>
   * myFromBytes</code> to allow subclasses to process data.
   *
   * <p>If the given data does not represent a valid JDWP packet, it returns <code>null</code>.
   *
   * @param bytes packet data from the wire
   * @return number of bytes in <code>bytes</code> processed
   */
  public static JdwpPacket fromBytes(byte[] bytes) {
    int i = 0;
    int length =
        ((bytes[i++] & 0xff) << 24
            | (bytes[i++] & 0xff) << 16
            | (bytes[i++] & 0xff) << 8
            | (bytes[i++] & 0xff));
    int id = 0;
    byte flags = 0;

    if (bytes.length == length) {
      id =
          ((bytes[i++] & 0xff) << 24
              | (bytes[i++] & 0xff) << 16
              | (bytes[i++] & 0xff) << 8
              | (bytes[i++] & 0xff));
      flags = bytes[i++];

      Class clazz = null;
      if (flags == 0) clazz = JdwpCommandPacket.class;
      else if ((flags & JDWP_FLAG_REPLY) != 0) clazz = JdwpReplyPacket.class;
      else {
        // Malformed packet. Discard it.
        return null;
      }

      JdwpPacket pkt = null;
      try {
        pkt = (JdwpPacket) clazz.newInstance();
      } catch (InstantiationException ie) {
        // Discard packet
        return null;
      } catch (IllegalAccessException iae) {
        // Discard packet
        return null;
      }

      pkt.setId(id);
      pkt.setFlags(flags);

      i += pkt.myFromBytes(bytes, i);
      byte[] data = new byte[length - i];
      System.arraycopy(bytes, i, data, 0, data.length);
      pkt.setData(data);

      return pkt;
    }

    return null;
  }