Exemplo n.º 1
0
        public virtual ParameterInfo[] getParameters(string methodName, Type c)
        {
            ParameterInfo[] parameters = null;

            try
            {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                ClassReader cr      = new ClassReader(c.FullName.Replace('.', '/'));
                Method[]    methods = c.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
                if (methods != null)
                {
                    AnalyzerClassVisitor cn = null;
                    for (int i = 0; i < methods.Length; i++)
                    {
                        if (methodName.Equals(methods[i].Name))
                        {
                            cn = new AnalyzerClassVisitor(methods[i]);
                            break;
                        }
                    }

                    if (cn != null)
                    {
                        cr.accept(cn, 0);
                        parameters = cn.Parameters;
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("Cannot read class", e);
            }

            return(parameters);
        }
Exemplo n.º 2
0
        protected internal override Attribute Read(ClassReader classReader, int offset, int
                                                   length, char[] charBuffer, int codeAttributeOffset, Label[] labels)
        {
            var currentOffset = offset;
            var hashAlgorithm = classReader.ReadUTF8(currentOffset, charBuffer);

            currentOffset += 2;
            var numModules = classReader.ReadUnsignedShort(currentOffset);

            currentOffset += 2;
            var moduleList = new List <string>(numModules);
            var hashList   = new List <byte[]>(numModules);

            for (var i = 0; i < numModules; ++i)
            {
                var module = classReader.ReadModule(currentOffset, charBuffer);
                currentOffset += 2;
                moduleList.Add(module);
                var hashLength = classReader.ReadUnsignedShort(currentOffset);
                currentOffset += 2;
                var hash = new byte[hashLength];
                for (var j = 0; j < hashLength; ++j)
                {
                    hash[j]        = unchecked ((byte)(classReader.ReadByte(currentOffset) & 0xFF));
                    currentOffset += 1;
                }

                hashList.Add(hash);
            }

            return(new ModuleHashesAttribute(hashAlgorithm, moduleList, hashList));
        }
Exemplo n.º 3
0
        private IEnumerable <Markdown.IElement> Step4DocumentTheRequirement()
        {
            yield return(new Markdown.Header3("Fourth step: document the requirement"));

            yield return(new Markdown.Paragraph("TODO"));

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.Step4Sample))));
        }
Exemplo n.º 4
0
        protected internal virtual Attribute read(ClassReader cr, int off, int len, char[] buf, int codeOff, Label[] labels)
        {
            Attribute attr = new Attribute(type);

            attr.value = new byte[len];
            SystemJ.arraycopy(cr.b, off, attr.value, 0, len);
            return(attr);
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Reads a
        ///     <see cref="type" />
        ///     attribute. This method must return a <i>new</i>
        ///     <see cref="Attribute" />
        ///     object,
        ///     of type
        ///     <see cref="type" />
        ///     , corresponding to the 'length' bytes starting at 'offset', in the given
        ///     ClassReader.
        /// </summary>
        /// <param name="classReader">the class that contains the attribute to be read.</param>
        /// <param name="offset">
        ///     index of the first byte of the attribute's content in
        ///     <see cref="ClassReader" />
        ///     . The 6
        ///     attribute header bytes (attribute_name_index and attribute_length) are not taken into
        ///     account here.
        /// </param>
        /// <param name="length">
        ///     the length of the attribute's content (excluding the 6 attribute header bytes).
        /// </param>
        /// <param name="charBuffer">
        ///     the buffer to be used to call the ClassReader methods requiring a
        ///     'charBuffer' parameter.
        /// </param>
        /// <param name="codeAttributeOffset">
        ///     index of the first byte of content of the enclosing Code attribute
        ///     in
        ///     <see cref="ClassReader" />
        ///     , or -1 if the attribute to be read is not a Code attribute. The 6
        ///     attribute header bytes (attribute_name_index and attribute_length) are not taken into
        ///     account here.
        /// </param>
        /// <param name="labels">
        ///     the labels of the method's code, or
        ///     <literal>null</literal>
        ///     if the attribute to be read
        ///     is not a Code attribute.
        /// </param>
        /// <returns>
        ///     a <i>new</i>
        ///     <see cref="Attribute" />
        ///     object corresponding to the specified bytes.
        /// </returns>
        protected internal virtual Attribute Read(ClassReader classReader, int offset, int
                                                  length, char[] charBuffer, int codeAttributeOffset, Label[] labels)
        {
            var attribute = new Attribute(type);

            attribute.content = new byte[length];
            Array.Copy(classReader.classFileBuffer, offset, attribute.content, 0, length
                       );
            return(attribute);
        }
Exemplo n.º 6
0
        private IEnumerable <Markdown.IElement> Sample1()
        {
            var balance = -10;

            this.Act(() =>
                     this.QuickSample1(balance)
                     )
            .AssertException($"balance cannot be < 0 and actually is {balance}");

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.QuickSample1))));
        }
Exemplo n.º 7
0
        public static IConstantInfo ReadConstantInfo(this ClassReader reader, ConstantPool pool)
        {
            var tag  = reader.ReadU1();
            var type = (ConstantType)tag;

            switch (type)
            {
            case ConstantType.Class:
                return(new ClassConstantInfo(pool, reader.ReadU2()));

            case ConstantType.FieldRef:
                return(new FieldRefConstantInfo(pool, reader.ReadU2(), reader.ReadU2()));

            case ConstantType.MethodRef:
                return(new MethodRefConstantInfo(pool, reader.ReadU2(), reader.ReadU2()));

            case ConstantType.InterfaceMethodRef:
                return(new InterfaceMethodRefConstantInfo(pool, reader.ReadU2(), reader.ReadU2()));

            case ConstantType.String:
                return(new StringConstantInfo(pool, reader.ReadU2()));

            case ConstantType.Integer:
                return(new IntegerConstantInfo(reader.ReadInt()));

            case ConstantType.Float:
                return(new FloatConstantInfo(reader.ReadFloat()));

            case ConstantType.Long:
                return(new LongConstantInfo(reader.ReadLong()));

            case ConstantType.Double:
                return(new DoubleConstantInfo(reader.ReadDouble()));

            case ConstantType.NameAndType:
                return(new NameAndTypeConstantInfo(reader.ReadU2(), reader.ReadU2()));

            case ConstantType.Utf8:
                return(new Utf8ConstantInfo(reader.ReadUTF()));

            case ConstantType.MethodHandle:
                break;

            case ConstantType.MethodType:
                break;

            case ConstantType.InvokeDynamic:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            throw new NotImplementedException();
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            var jrePath = Environment.GetEnvironmentVariable("JAVA_HOME");
            var entry   = EntryFactory.CreateEntry(Path.Combine(jrePath, "jre", "*"));
            var data    = entry.ReadClass("java.lang.Object");

            Console.WriteLine(data);
            var reader = new ClassReader(data);//@"E:\workcode\zbj\八戒招聘\hr-saas\zbj-zhaopin-admin\zbj-hr-saas-web-manage-ui\target\classes\com\zbj\hr\listener\TaskServlet.class"

            Console.WriteLine("jvm class magic:{0}", reader.ReadU4());
        }
Exemplo n.º 9
0
        public void TestsTwoConstructors()
        {
            ClassReader      reader    = new ClassReader();
            ClassWriter      writer    = new ClassWriter("result3");
            GeneratorOptions options   = new GeneratorOptions(2, 2, 2);
            Generator        generator = new Generator(options, reader, writer);
            List <string>    files     = new List <string>(Directory.GetFiles("test3"));

            generator.Generate(files).Wait();
            Assert.AreEqual(2, ParseCompilationUnit(File.ReadAllText(Directory.GetFiles("result3")[0])).DescendantNodes().OfType <MethodDeclarationSyntax>().Count());
        }
Exemplo n.º 10
0
        public static IAttribute[] ReadAttributes(this ClassReader reader, ConstantPool pool)
        {
            var count      = reader.ReadU2();
            var attributes = new IAttribute[count];

            for (int i = 0; i < attributes.Length; i++)
            {
                attributes[i] = ReadAttribute(reader, pool);
            }
            return(attributes);
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            TestObject   TO     = new TestObject();
            StreamWriter Writer = new StreamWriter("./Out.txt", false);

            ClassWriter.WriteObject(TO, Writer);
            Writer.Flush(); Writer.Close();

            StreamReader Reader = new StreamReader("./Out.txt");
            var          V      = ClassReader.ReadObject(typeof(TestObject), Reader);
        }
Exemplo n.º 12
0
        public async Task Tests_Creation()
        {
            ClassReader      reader    = new ClassReader();
            ClassWriter      writer    = new ClassWriter("result1");
            GeneratorOptions options   = new GeneratorOptions(2, 2, 2);
            Generator        generator = new Generator(options, reader, writer);
            List <string>    files     = new List <string>(Directory.GetFiles("test1"));
            await generator.Generate(files);

            Assert.AreEqual(1, Directory.GetFiles("result1").Length);
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            ClassReader      reader    = new ClassReader();
            ClassWriter      writer    = new ClassWriter("result1");
            GeneratorOptions options   = new GeneratorOptions(1, 1, 1);
            Generator        generator = new Generator(options, reader, writer);
            List <string>    files     = new List <string>(Directory.GetFiles("D:\\test1"));

            generator.Generate(files).Wait();
            Console.WriteLine("Finish...");
            Console.ReadKey();
        }
Exemplo n.º 14
0
        public MemberInfo(ClassReader classReader, ConstantPool constantPool)
        {
            this.accessFlag      = classReader.ReadU2();
            this.nameIndex       = classReader.ReadU2();
            this.descriptorIndex = classReader.ReadU2();
            this.attributesCount = classReader.ReadU2();
            this.attributes      = new AttributeInfo[this.attributesCount];

            for (int i = 0; i < this.attributesCount; i++)
            {
                this.attributes[i] = AttributeInfoReader.Read(classReader, constantPool);
            }
        }
Exemplo n.º 15
0
        private IEnumerable <Markdown.IElement> Sample2()
        {
            TransactionType transactionType    = TransactionType.OnlinePayment;
            double?         onlinePaymentLimit = 10;
            double          paymentAmount      = 11;

            this.Act(() =>
                     this.QuickSample2(transactionType, onlinePaymentLimit, paymentAmount)
                     )
            .AssertException($"Online Payment Amount ({paymentAmount}) exceeds the Online Payment Limit ({onlinePaymentLimit})");

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.QuickSample2))));
        }
Exemplo n.º 16
0
        public void ReadClasses()
        {
            var absPathDll = Path.GetFullPath(Path.Combine(@"..\..\..\", AssemblyName, @"bin\Debug", AssemblyName + ".dll"));

            var classTypes = ClassReader.GetAllClassesFromAssembly(absPathDll, new[] { AssemblyName + ".Entities" }).ToList();

            Assert.AreNotEqual(null, classTypes.Count);
            Assert.AreEqual(4, classTypes.Count);

            Assert.IsNotNull(classTypes.FirstOrDefault(x => x.Name == "Person"));
            Assert.IsNotNull(classTypes.FirstOrDefault(x => x.Name == "Course"));
            Assert.IsNotNull(classTypes.FirstOrDefault(x => x.Name == "Student"));
            Assert.IsNotNull(classTypes.FirstOrDefault(x => x.Name == "Teacher"));
        }
Exemplo n.º 17
0
        private static LineNumberTableEntry[] ReadLineNumberTableEntrys(this ClassReader reader)
        {
            var count  = reader.ReadU2();
            var tables = new LineNumberTableEntry[count];

            for (var i = 0; i < tables.Length; i++)
            {
                tables[i] = new LineNumberTableEntry()
                {
                    StartPc    = reader.ReadU2(),
                    LineNumber = reader.ReadU2()
                };
            }
            return(tables);
        }
Exemplo n.º 18
0
        public static IConstantInfo[] ReadConstantInfos(this ClassReader reader, ConstantPool pool)
        {
            var count = reader.ReadU2();
            var infos = new IConstantInfo[count];

            for (int i = 1; i < infos.Length; i++)
            {
                infos[i] = reader.ReadConstantInfo(pool);
                if (infos[i].Type == ConstantType.Double || infos[i].Type == ConstantType.Long)
                {
                    i++;
                }
            }
            return(infos);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Reads avaliable elements at start
        /// </summary>
        private void ReadAvailableElements()
        {
            ClassReader         reader = new ClassReader(null, IsTypeToolboxVisible);
            var                 types  = reader.GetTypes();
            ClassAssemblyReader classAssemblyReader = new ClassAssemblyReader(Settings.Default.Assemblies);

            types.AddRange(classAssemblyReader.GetTypes(IsTypeToolboxVisible));
            foreach (Type type in types)
            {
                ElementCreatorViewModel model = new ElementCreatorViewModel(type);
                ActivityMapperAttribute activityMapperAttribute = type.GetCustomAttribute <ActivityMapperAttribute>();
                activityMapperAttribute?.Register();
                Elements.Add(model);
            }
        }
Exemplo n.º 20
0
        public void LoadClassesFromFile(string path)
        {
            ClassReader reader = new ClassReader(Engine);
            JArray      json   = FileHandler.FromPath <JArray>(path);

            foreach (JToken entry in json)
            {
                if (entry.Type != JTokenType.Object)
                {
                    throw new MeException($"Expected a json object \"{path}\"at  \"{entry}\".");
                }

                ClassTemplate newEntry = reader.FromJson(entry.ToObject <JObject>());
                AddClass(newEntry);
            }
        }
Exemplo n.º 21
0
        private static ExceptionTable[] ReadExceptionTables(this ClassReader reader)
        {
            var count  = reader.ReadU2();
            var tables = new ExceptionTable[count];

            for (int i = 0; i < tables.Length; i++)
            {
                tables[i] = new ExceptionTable()
                {
                    StartPc   = reader.ReadU2(),
                    EndPc     = reader.ReadU2(),
                    HandlePc  = reader.ReadU2(),
                    CatchType = reader.ReadU2()
                };
            }
            return(tables);
        }
Exemplo n.º 22
0
        private IEnumerable <Markdown.IElement> Step2MakeItWorking()
        {
            yield return(new Markdown.Header3("Second step: make it working"));

            yield return(new Markdown.Paragraph("When time comes you should implement the business requirement. It might look like that:"));

            var withdrawLimit  = 100;
            var withdrawAmount = 110;

            this.Act(() =>
                     this.Step2Sample(withdrawLimit, withdrawAmount)
                     )
            .AssertException($"Withdraw Amount ({withdrawAmount}) exceeds the Withdraw Limit ({withdrawLimit})");

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.Step2Sample))));

            yield return(new Markdown.Paragraph("This sample is simplified for sure, but remember that simple solutions are the best."));
        }
Exemplo n.º 23
0
        public void TestsMethodsCount_EqualsToClassMethodsCount()
        {
            ClassReader      reader    = new ClassReader();
            ClassWriter      writer    = new ClassWriter("result2");
            GeneratorOptions options   = new GeneratorOptions(2, 2, 2);
            Generator        generator = new Generator(options, reader, writer);
            List <string>    files     = new List <string>(Directory.GetFiles("test2"));

            generator.Generate(files).Wait();
            int method_count = 0;

            foreach (string file in Directory.GetFiles("test2"))
            {
                method_count += ParseCompilationUnit(File.ReadAllText(file)).DescendantNodes().OfType <MethodDeclarationSyntax>().Count();
            }

            Assert.AreEqual(method_count, ParseCompilationUnit(File.ReadAllText(Directory.GetFiles("test2")[0])).DescendantNodes().OfType <MethodDeclarationSyntax>().Count());
        }
Exemplo n.º 24
0
        private static LocalVariableTableEntry[] ReadLocalVariableTableEntrys(this ClassReader reader)
        {
            var count  = reader.ReadU2();
            var tables = new LocalVariableTableEntry[count];

            for (var i = 0; i < tables.Length; i++)
            {
                tables[i] = new LocalVariableTableEntry()
                {
                    StartPc         = reader.ReadU2(),
                    Length          = reader.ReadU2(),
                    NameIndex       = reader.ReadU2(),
                    DescriptorIndex = reader.ReadU2(),
                    Index           = reader.ReadU2()
                };
            }
            return(tables);
        }
Exemplo n.º 25
0
        public static AttributeInfo Read(ClassReader classReader, ConstantPool constantPool)
        {
            ushort        attributeNameIndex = classReader.ReadU2();
            string        attributeName      = Encoding.UTF8.GetString(((ConstantUtf8)constantPool.ConstantPoolInfo[attributeNameIndex]).Bytes);
            AttributeInfo attributeInfo      = null;

            switch (attributeName)
            {
            case "ConstantValue":
                attributeInfo = new ConstantValue(); break;

            case "Code":
                attributeInfo = new Code(); break;

            case "Deprecated":
                attributeInfo = new Deprecated(); break;

            case "LineNumberTable":
                attributeInfo = new LineNumberTable(); break;

            case "LocalVariableTable":
                attributeInfo = new LocalVariableTable(); break;

            case "SourceFile":
                attributeInfo = new SourceFile(); break;

            case "Synthetic":
                attributeInfo = new Synthetic(); break;

            case "Exceptions":
                attributeInfo = new Exceptions(); break;

            case "Signature":
                attributeInfo = new Signature(); break;

            //case "StackMapTable":
            //    attributeInfo = null;
            default:
                throw new Exception("no such attribute error");
            }
            attributeInfo.AttributeName = attributeName;
            attributeInfo.ReadAttributeInfo(classReader, constantPool);
            return(attributeInfo);
        }
Exemplo n.º 26
0
        public static IAttribute ReadAttribute(this ClassReader reader, ConstantPool pool)
        {
            var nameIndex = reader.ReadU2();
            var length    = reader.ReadU4();
            var name      = pool.GetUtf8String(nameIndex);

            if (!Enum.TryParse <AttributeType>(name, true, out var type))
            {
                type = AttributeType.Unparsed;
            }
            switch (type)
            {
            case AttributeType.Deprecated:
                return(new DeprecatedAttribute());

            case AttributeType.Synthetic:
                return(new SyntheticAttribute());

            case AttributeType.SourceFile:
                var fileNameIndex = reader.ReadU2();
                return(new SourceFileAttribute(pool.GetUtf8String(fileNameIndex)));

            case AttributeType.ConstantValue:
                var constantIndex = reader.ReadU2();
                return(new ConstantValueAttribute(pool.GetConstant(constantIndex)));

            case AttributeType.Code:
                ushort stack = reader.ReadU2(), locals = reader.ReadU2();
                var    codelength = reader.ReadU4();
                var    code       = reader.ReadBytes((int)codelength);
                return(new CodeAttribute(stack, locals, code, ReadExceptionTables(reader), ReadAttributes(reader, pool)));

            case AttributeType.Exceptions:
                return(new ExceptionsAttribute(reader.ReadU2S()));

            case AttributeType.LineNumberTable:
                return(new LineNumberTableAttribute(ReadLineNumberTableEntrys(reader)));

            case AttributeType.LocalVariableTable:
                return(new LocalVariableTableAttribute(ReadLocalVariableTableEntrys(reader)));
            }
            return(new UnparsedAttribute(reader.ReadBytes((int)length)));
        }
Exemplo n.º 27
0
        private IEnumerable <Markdown.IElement> Step1GatherRequirements()
        {
            yield return(new Markdown.Header3("First step: business requirements gathering"));

            yield return(new Markdown.Paragraph("Quite often you might hear during analysis phase of your project such words:"));

            yield return(new Markdown.Quote("When withdraw limit is set, withdrawn amount cannot exceed the limit"));

            yield return(new Markdown.Paragraph("When you hear such sentence just start your development by writing it down like that:"));

            this.Act(() =>
                     this.Step1Sample()
                     )
            .AssertException("NOT IMPLEMENTED");

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.Step1Sample))));

            yield return(new Markdown.Paragraph("This will throw `NotImplementedException` for sure. But we have not finished our job yet."));
        }
Exemplo n.º 28
0
        private IEnumerable <Markdown.IElement> Step3IntroduceDedicatedException()
        {
            yield return(new Markdown.Header3("Third step: introduce dedicated exception"));

            yield return(new Markdown.Paragraph($"I like this step very much. Instead of using some generic exception thrown by" +
                                                $" `{nameof(Business.Requirement.Throws)}()` method introduce your own meaningful exception:"));

            var withdrawLimit  = 100;
            var withdrawAmount = 110;

            this.Act(() =>
                     this.Step3Sample(withdrawLimit, withdrawAmount)
                     )
            .AssertException($"Withdraw Amount ({withdrawAmount}) exceeds the Withdraw Limit ({withdrawLimit})");

            yield return(new Markdown.Code(ClassReader.ReadMethodBody(nameof(this.Step3Sample))));

            yield return(new Markdown.Paragraph("Introducing dedicated exception is not always needed. " +
                                                "It allows you to handle (catch) some situations properly. " +
                                                "It also gives you a way to derive all thrown business exceptions from your own base `Exception` class."));
        }
Exemplo n.º 29
0
        public virtual Type specialize(string name, Type c, Dictionary <string, object> variables)
        {
            ClassWriter  cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
            ClassVisitor cv = cw;

            StringWriter debugOutput = null;

            if (log.TraceEnabled)
            {
                // Dump the class to be specialized (only once)
                if (!tracedClasses.Contains(c))
                {
                    StringWriter classTrace   = new StringWriter();
                    ClassVisitor classTraceCv = new TraceClassVisitor(new PrintWriter(classTrace));
                    try
                    {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                        ClassReader cr = new ClassReader(c.FullName.Replace('.', '/'));
                        cr.accept(classTraceCv, 0);
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                        log.trace(string.Format("Dump of class to be specialized: {0}", c.FullName));
                        log.trace(classTrace);
                    }
                    catch (IOException)
                    {
                        // Ignore Exception
                    }
                    tracedClasses.Add(c);
                }

                log.trace(string.Format("Specializing class {0}", name));
                string[] variableNames = variables.Keys.toArray(new string[variables.Count]);
                Array.Sort(variableNames);
                foreach (string variableName in variableNames)
                {
                    log.trace(string.Format("Variable {0}={1}", variableName, variables[variableName]));
                }

                debugOutput = new StringWriter();
                PrintWriter debugPrintWriter = new PrintWriter(debugOutput);
                cv = new TraceClassVisitor(cv, debugPrintWriter);
                //cv = new TraceClassVisitor(debugPrintWriter);
            }

            try
            {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                ClassReader cr = new ClassReader(c.FullName.Replace('.', '/'));
                ClassNode   cn = new SpecializedClassVisitor(name, variables);
                cr.accept(cn, 0);
                cn.accept(cv);
            }
            catch (IOException e)
            {
                Console.WriteLine("Cannot read class", e);
            }

            if (debugOutput != null)
            {
                log.trace(debugOutput.ToString());
            }

            Type specializedClass = null;

            try
            {
                specializedClass = classLoader.defineClass(name, cw.toByteArray());
            }
            catch (ClassFormatError e)
            {
                Console.WriteLine("Error while defining specialized class", e);
            }

            return(specializedClass);
        }
Exemplo n.º 30
0
        public void AssemblyNotExists()
        {
            var absPathDll = Path.GetFullPath(Path.Combine(@"..\..\", AssemblyName, @"bin\Debug", AssemblyName + ".dll"));

            ClassReader.GetAllClassesFromAssembly(absPathDll);
        }