private ArrayList<Symbol> getSymbolTable(byte[] encodedFileAsBytes) { // Finding the Divider in the file & separate the SymbolTable System.out.println("\nFileContent: "); System.out.println(Arrays.toString(encodedFileAsBytes)); int i = getDividerIndexInArray(encodedFileAsBytes); // Reading the String of symbol table from the byteArray String symbolTableString = ""; for (int j = 0; j < i; j++) { symbolTableString += String.valueOf((char) encodedFileAsBytes[j]); } // Generating the ArrayList<Symbol> String[] splitSymbolsAndCodes = symbolTableString.split(","); ArrayList<Symbol> symbols = new ArrayList<Symbol>(); for (int j = 0; j < splitSymbolsAndCodes.length; j++) { String[] symbolCodePair = splitSymbolsAndCodes[j].split(":"); Symbol symbol = new Symbol(0, symbolCodePair[0]); symbol.setCode(symbolCodePair[1]); symbols.add(symbol); } // Logging the Symbol List System.out.println("\nSymbol Table Retrived from the File"); System.out.println(Symbol.symbolListToString(symbols)); return symbols; }
public static void reconstructHeaders(Iterable<NativeLibrary> libraries, PrintWriter out) { List<MemberRef> orphanMembers = new ArrayList<MemberRef>(); Map<TypeRef, List<MemberRef>> membersByClass = new HashMap<TypeRef, List<MemberRef>>(); for (NativeLibrary library : libraries) { for (Symbol symbol : library.getSymbols()) { MemberRef mr = symbol.getParsedRef(); if (mr == null) continue; TypeRef et = mr.getEnclosingType(); if (et == null) orphanMembers.add(mr); else { List<MemberRef> mrs = membersByClass.get(et); if (mrs == null) membersByClass.put(et, mrs = new ArrayList<MemberRef>()); mrs.add(mr); } } } for (TypeRef tr : membersByClass.keySet()) out.println("class " + tr + ";"); for (MemberRef mr : orphanMembers) out.println(mr + ";"); for (Map.Entry<TypeRef, List<MemberRef>> e : membersByClass.entrySet()) { TypeRef tr = e.getKey(); List<MemberRef> mrs = e.getValue(); out.println("class " + tr + " \n{"); for (MemberRef mr : mrs) { out.println("\t" + mr + ";"); } out.println("}"); } }
private int skipOptionalSize(Symbol sig, int index) { byte c = sig.getByteAt(index); while (c >= '0' && c <= '9') { ++index; c = sig.getByteAt(index); } return index; }
boolean computeSubtypeOf(Klass k) { // An array is a subtype of Serializable, Clonable, and Object Symbol name = k.getName(); if (name != null && (name.equals(javaIoSerializableName()) || name.equals(javaLangCloneableName()) || name.equals(javaLangObjectName()))) { return true; } else { return false; } }
/** Only valid for T_ARRAY; throws unspecified exception otherwise */ public ArrayInfo getArrayInfo() { int index = 1; int dim = 1; index = skipOptionalSize(signature, index); while (signature.getByteAt(index) == '[') { index++; dim++; skipOptionalSize(signature, index); } int elementType = BasicType.charToType((char) signature.getByteAt(index)); return new ArrayInfo(dim, elementType); }
/** Field access by name. */ public Field findLocalField(Symbol name, Symbol sig) { TypeArray fields = getFields(); int n = (int) fields.getLength(); ConstantPool cp = getConstants(); for (int i = 0; i < n; i += NEXT_OFFSET) { int nameIndex = fields.getShortAt(i + NAME_INDEX_OFFSET); int sigIndex = fields.getShortAt(i + SIGNATURE_INDEX_OFFSET); Symbol f_name = cp.getSymbolAt(nameIndex); Symbol f_sig = cp.getSymbolAt(sigIndex); if (name.equals(f_name) && sig.equals(f_sig)) { return newField(i); } } return null; }
// refer to compute_modifier_flags in VM code. public long computeModifierFlags() { long access = getAccessFlags(); // But check if it happens to be member class. TypeArray innerClassList = getInnerClasses(); int length = (innerClassList == null) ? 0 : (int) innerClassList.getLength(); if (length > 0) { if (Assert.ASSERTS_ENABLED) { Assert.that(length % InnerClassAttributeOffset.innerClassNextOffset == 0, "just checking"); } for (int i = 0; i < length; i += InnerClassAttributeOffset.innerClassNextOffset) { int ioff = innerClassList.getShortAt(i + InnerClassAttributeOffset.innerClassInnerClassInfoOffset); // 'ioff' can be zero. // refer to JVM spec. section 4.7.5. if (ioff != 0) { // only look at classes that are already loaded // since we are looking for the flags for our self. Oop classInfo = getConstants().getObjAt(ioff); Symbol name = null; if (classInfo instanceof Klass) { name = ((Klass) classInfo).getName(); } else if (classInfo instanceof Symbol) { name = (Symbol) classInfo; } else { throw new RuntimeException("should not reach here"); } if (name.equals(getName())) { // This is really a member class access = innerClassList.getShortAt( i + InnerClassAttributeOffset.innerClassAccessFlagsOffset); break; } } } // for inner classes } // Remember to strip ACC_SUPER bit return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; }
public FieldType(Symbol signature) { this.signature = signature; this.first = (char) signature.getByteAt(0); if (Assert.ASSERTS_ENABLED) { switch (this.first) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 'L': case '[': break; // Ok. signature char known default: Assert.that( false, "Unknown char in field signature \"" + signature.asString() + "\": " + this.first); } } }
public void decodeFile(String encodedFileName, String decodedFileName) { try { byte[] encodedFileAsBytes = getFileAsByteArray(encodedFileName); // Generating the Symbol & Code ArrayList ArrayList<Symbol> symbols = getSymbolTable(encodedFileAsBytes); // // Generating CodeTree // Node codeTree = CodeTree.makeCodeTree(symbols); // // Logging the CodeTree whether it have been generated correctly or not. // String code = ""; // CodeTree.getCodeOfSymbol(CodeTree.Node.ROOT, symbols.get(2).getIdentifier(), // code); // System.out.println("Symbol: " + symbols.get(2) + " Code_Retrived: " + code); // Decoding the content int dividerIndex = getDividerIndexInArray(encodedFileAsBytes); byte[] encodedMessage = new byte[encodedFileAsBytes.length - dividerIndex]; for (int j = 0, i = dividerIndex + 1; i < encodedFileAsBytes.length; i++) { encodedMessage[j++] = encodedFileAsBytes[i]; } String message = ByteUtils.toBinary(encodedMessage); System.out.println("Encoded Message In File: " + message); Symbol.symbolListToString(symbols); StringBuilder decodedMessage = new StringBuilder(""); while (message.length() != 0) { // Loggin the Messages // System.out.println(""); // logger.info("Meesage: " + message); // logger.info("Message Decoded: " + decodedMessage); boolean flag = false; for (Symbol symbol : symbols) { if (message.startsWith(symbol.getCode())) { decodedMessage.append(symbol.getIdentifier()); message = message.substring(symbol.getCode().length(), message.length()); flag = true; break; } } /* * We are checking that if no symbol is there in the symbol list * then it is the EOF as some padding is done by the String to * Byte & Byte to String conversion */ if (!flag) { break; } } System.out.println("Decoded Message: " + decodedMessage); // Writing the decoded Message in the Output File File file = new File(decodedFileName); FileOutputStream fos = new FileOutputStream(file); fos.write(decodedMessage.toString().getBytes()); } catch (Exception ex) { logger.log(Level.WARNING, ex.toString()); ex.printStackTrace(); } }
public void writeBytes(OutputStream os) throws IOException { // Map between any modified UTF-8 and it's constant pool index. Map utf8ToIndex = new HashMap(); DataOutputStream dos = new DataOutputStream(os); TypeArray tags = getTags(); int len = (int) getLength(); int ci = 0; // constant pool index // collect all modified UTF-8 Strings from Constant Pool for (ci = 1; ci < len; ci++) { byte cpConstType = tags.getByteAt(ci); if (cpConstType == JVM_CONSTANT_Utf8) { Symbol sym = getSymbolAt(ci); utf8ToIndex.put(sym.asString(), new Short((short) ci)); } else if (cpConstType == JVM_CONSTANT_Long || cpConstType == JVM_CONSTANT_Double) { ci++; } } for (ci = 1; ci < len; ci++) { int cpConstType = (int) tags.getByteAt(ci); // write cp_info // write constant type switch (cpConstType) { case JVM_CONSTANT_Utf8: { dos.writeByte(cpConstType); Symbol sym = getSymbolAt(ci); dos.writeShort((short) sym.getLength()); dos.write(sym.asByteArray()); if (DEBUG) debugMessage("CP[" + ci + "] = modified UTF-8 " + sym.asString()); break; } case JVM_CONSTANT_Unicode: throw new IllegalArgumentException("Unicode constant!"); case JVM_CONSTANT_Integer: dos.writeByte(cpConstType); dos.writeInt(getIntAt(ci)); if (DEBUG) debugMessage("CP[" + ci + "] = int " + getIntAt(ci)); break; case JVM_CONSTANT_Float: dos.writeByte(cpConstType); dos.writeFloat(getFloatAt(ci)); if (DEBUG) debugMessage("CP[" + ci + "] = float " + getFloatAt(ci)); break; case JVM_CONSTANT_Long: { dos.writeByte(cpConstType); long l = getLongAt(ci); // long entries occupy two pool entries ci++; dos.writeLong(l); break; } case JVM_CONSTANT_Double: dos.writeByte(cpConstType); dos.writeDouble(getDoubleAt(ci)); // double entries occupy two pool entries ci++; break; case JVM_CONSTANT_Class: { dos.writeByte(cpConstType); // Klass already resolved. ConstantPool constains klassOop. Klass refKls = (Klass) getObjAt(ci); String klassName = refKls.getName().asString(); Short s = (Short) utf8ToIndex.get(klassName); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = class " + s); break; } // case JVM_CONSTANT_ClassIndex: case JVM_CONSTANT_UnresolvedClass: { dos.writeByte(JVM_CONSTANT_Class); String klassName = getSymbolAt(ci).asString(); Short s = (Short) utf8ToIndex.get(klassName); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = class " + s); break; } case JVM_CONSTANT_String: { dos.writeByte(cpConstType); String str = OopUtilities.stringOopToString(getObjAt(ci)); Short s = (Short) utf8ToIndex.get(str); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = string " + s); break; } // case JVM_CONSTANT_StringIndex: case JVM_CONSTANT_UnresolvedString: { dos.writeByte(JVM_CONSTANT_String); String val = getSymbolAt(ci).asString(); Short s = (Short) utf8ToIndex.get(val); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = string " + s); break; } // all external, internal method/field references case JVM_CONSTANT_Fieldref: case JVM_CONSTANT_Methodref: case JVM_CONSTANT_InterfaceMethodref: { dos.writeByte(cpConstType); int value = getIntAt(ci); short klassIndex = (short) extractLowShortFromInt(value); short nameAndTypeIndex = (short) extractHighShortFromInt(value); dos.writeShort(klassIndex); dos.writeShort(nameAndTypeIndex); if (DEBUG) debugMessage( "CP[" + ci + "] = ref klass = " + klassIndex + ", N&T = " + nameAndTypeIndex); break; } case JVM_CONSTANT_NameAndType: { dos.writeByte(cpConstType); int value = getIntAt(ci); short nameIndex = (short) extractLowShortFromInt(value); short signatureIndex = (short) extractHighShortFromInt(value); dos.writeShort(nameIndex); dos.writeShort(signatureIndex); if (DEBUG) debugMessage( "CP[" + ci + "] = N&T name = " + nameIndex + ", type = " + signatureIndex); break; } } // switch } dos.flush(); return; }
private boolean isInInnerClasses(Symbol sym, boolean includeLocals) { TypeArray innerClassList = getInnerClasses(); int length = (innerClassList == null) ? 0 : (int) innerClassList.getLength(); if (length > 0) { if (Assert.ASSERTS_ENABLED) { Assert.that(length % InnerClassAttributeOffset.innerClassNextOffset == 0, "just checking"); } for (int i = 0; i < length; i += InnerClassAttributeOffset.innerClassNextOffset) { int ioff = innerClassList.getShortAt(i + InnerClassAttributeOffset.innerClassInnerClassInfoOffset); // 'ioff' can be zero. // refer to JVM spec. section 4.7.5. if (ioff != 0) { Oop iclassInfo = getConstants().getObjAt(ioff); Symbol innerName = null; if (iclassInfo instanceof Klass) { innerName = ((Klass) iclassInfo).getName(); } else if (iclassInfo instanceof Symbol) { innerName = (Symbol) iclassInfo; } else { throw new RuntimeException("should not reach here"); } Symbol myname = getName(); int ooff = innerClassList.getShortAt( i + InnerClassAttributeOffset.innerClassOuterClassInfoOffset); // for anonymous classes inner_name_index of InnerClasses // attribute is zero. int innerNameIndex = innerClassList.getShortAt(i + InnerClassAttributeOffset.innerClassInnerNameOffset); // if this is not a member (anonymous, local etc.), 'ooff' will be zero // refer to JVM spec. section 4.7.5. if (ooff == 0) { if (includeLocals) { // does it looks like my local class? if (innerName.equals(sym) && innerName.asString().startsWith(myname.asString())) { // exclude anonymous classes. return (innerNameIndex != 0); } } } else { Oop oclassInfo = getConstants().getObjAt(ooff); Symbol outerName = null; if (oclassInfo instanceof Klass) { outerName = ((Klass) oclassInfo).getName(); } else if (oclassInfo instanceof Symbol) { outerName = (Symbol) oclassInfo; } else { throw new RuntimeException("should not reach here"); } // include only if current class is outer class. if (outerName.equals(myname) && innerName.equals(sym)) { return true; } } } } // for inner classes return false; } else { return false; } }
/** * Main method. * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); String newInput = " "; File f = null; boolean loopForFileName = true; boolean loopForFileLocation = true; // Looping to get correct input while (loopForFileLocation == true) { while (loopForFileName == true) { System.out.print("Please enter a filename: "); newInput = scanner.nextLine(); if (newInput.length() == 0) { System.out.println(""); System.out.println("You must enter a file name. "); System.out.println(""); } else { loopForFileName = false; } } File file = new File(newInput); if (file.exists() == false) { System.out.println(""); System.out.println("The file you entered was not found."); System.out.println(""); loopForFileName = true; } else { loopForFileLocation = false; f = file; } } scanner.close(); System.out.println(""); // Character is the Key and Symbol is the Value HashMap<Character, Symbol> Letters = new HashMap<Character, Symbol>(); String line; BufferedReader reader = new BufferedReader(new FileReader(f)); // Reading data and putting it into the HashMap while ((line = reader.readLine()) != null) { for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); Symbol s = Letters.get(c); if (s == null) { s = new Symbol(c, 0); Letters.put(c, s); } s.addToFrequency(); } } reader.close(); ArrayHeap<Node> arrayHeap = new ArrayHeap<Node>(); // Adding to the ArrayHeap of Nodes for (Symbol s : Letters.values()) { Node n = new Node(); n.addSymbols(s); arrayHeap.add(n); } ArrayHeap<Node> arrayOfNodes = arrayHeap; Node results = new Node(); int counter = 0; // Calculating code words using Nodes while (arrayOfNodes.isEmpty() == false) { Node rightNode = arrayOfNodes.removeMin(); if (arrayOfNodes.isEmpty()) { if (counter == 0) { rightNode.createNewCodeWord("1"); } results = rightNode; } else { Node leftNode = arrayOfNodes.removeMin(); rightNode.createNewCodeWord("0"); leftNode.createNewCodeWord("1"); leftNode.addNode(rightNode); arrayOfNodes.add(leftNode); } counter++; } // Displaying output System.out.println("Variable Length Code Output"); System.out.println("____________________________________________________"); for (Symbol s : results.getSymbols()) { System.out.printf( "Symbol: %3s Codeword: %10s Frequency: %5d", s.getCharacter(), s.getCodeWord(), s.getFrequency()); System.out.print("\n"); } System.out.println(""); System.out.println( "Average VLC codeword length: " + String.format("%.2f", results.getAvgVlcLength()) + " bits per symbol"); System.out.println( "Average Fixed length codeword length: " + String.format("%.2f", results.getAvgFixedLength()) + " bits per symbol"); System.out.println(""); }