Esempio n. 1
0
			public FieldTableItem (FieldDef field, Location location)
			{
				flags = 0;
				Field = field;
				LocationList = new ArrayList ();
				LocationList.Add (location);
			}
 public virtual DocumentTreeNodeFilterResult GetResult(FieldDef field) => new DocumentTreeNodeFilterResult(FilterType.Hide, false);
 public virtual DocumentTreeNodeFilterResult GetResult(FieldDef field) => new DocumentTreeNodeFilterResult();
Esempio n. 4
0
        public override void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx)
        {
            output.Write(IdentifierEscaper.Escape(field.FieldType.GetFullName()), field.FieldType.ToTypeDefOrRef(), DecompilerReferenceFlags.None, TextColorHelper.GetColor(field.FieldType));
            output.Write(" ", BoxedTextColor.Text);
            output.Write(IdentifierEscaper.Escape(field.Name), field, DecompilerReferenceFlags.Definition, TextColorHelper.GetColor(field));
            var c = field.Constant;

            if (c != null)
            {
                output.Write(" ", BoxedTextColor.Text);
                output.Write("=", BoxedTextColor.Operator);
                output.Write(" ", BoxedTextColor.Text);
                if (c.Value == null)
                {
                    output.Write("null", BoxedTextColor.Keyword);
                }
                else
                {
                    switch (c.Type)
                    {
                    case ElementType.Boolean:
                        if (c.Value is bool)
                        {
                            output.Write((bool)c.Value ? "true" : "false", BoxedTextColor.Keyword);
                        }
                        else
                        {
                            goto default;
                        }
                        break;

                    case ElementType.Char:
                        output.Write($"'{c.Value}'", BoxedTextColor.Char);
                        break;

                    case ElementType.I1:
                    case ElementType.U1:
                    case ElementType.I2:
                    case ElementType.U2:
                    case ElementType.I4:
                    case ElementType.U4:
                    case ElementType.I8:
                    case ElementType.U8:
                    case ElementType.R4:
                    case ElementType.R8:
                    case ElementType.I:
                    case ElementType.U:
                        output.Write($"{c.Value}", BoxedTextColor.Number);
                        break;

                    case ElementType.String:
                        output.Write($"{c.Value}", BoxedTextColor.String);
                        break;

                    default:
                        output.Write($"{c.Value}", BoxedTextColor.Text);
                        break;
                    }
                }
            }
        }
Esempio n. 5
0
 public static bool IsInstanceField(FieldDef fldDef)
 {
     return(!fldDef.IsStatic);
 }
Esempio n. 6
0
 public FieldInfo(FieldDef fieldDef)
     : base(fieldDef)
 {
 }
Esempio n. 7
0
            ushort GetStructDef(Type type, Metadata metadata, Metadata[] fields)
            {
                var index = Schema.structs.Count;
                var structDef = new StructDef();
                Schema.structs.Add(structDef);
                structDef.metadata = metadata;

                var baseType = type.GetBaseSchemaType();
                if (baseType != null)
                    structDef.base_def = GetTypeDef(baseType);

                var i = 0;
                foreach (var field in type.GetSchemaFields())
                {
                    var fieldDef = new FieldDef
                    {
                        id = field.Id,
                        metadata = fields[i++],
                        type = GetTypeDef(field.GetSchemaType())
                    };

                    structDef.fields.Add(fieldDef);
                }

                return (ushort) index;
            }
Esempio n. 8
0
        public override void DecompileField(FieldDef field, ITextOutput output, DecompilationOptions options)
        {
            var dis = CreateReflectionDisassembler(output, options, field);

            dis.DisassembleField(field);
        }
Esempio n. 9
0
        public override void DecompileField(FieldDef field, ITextOutput output, DecompilationOptions options)
        {
            var dis = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            dis.DisassembleField(field);
        }
Esempio n. 10
0
        private void ProcessConverter(PropertyWithConverterRecord rec, TypeDef type)
        {
            TypeDef converter = ResolveType(rec.ConverterTypeId);

            if (converter.FullName == "System.ComponentModel.EnumConverter")
            {
                if (type != null && context.Modules.Contains((ModuleDefMD)type.Module))
                {
                    FieldDef enumField = type.FindField(rec.Value);
                    if (enumField != null)
                    {
                        service.AddReference(enumField, new BAMLEnumReference(enumField, rec));
                    }
                }
            }
            else if (converter.FullName == "System.Windows.Input.CommandConverter")
            {
                string cmd   = rec.Value.Trim();
                int    index = cmd.IndexOf('.');
                if (index != -1)
                {
                    string  typeName = cmd.Substring(0, index);
                    string  prefix;
                    TypeSig sig = ResolveType(typeName, out prefix);
                    if (sig != null)
                    {
                        string cmdName = cmd.Substring(index + 1);

                        TypeDef typeDef = sig.ToBasicTypeDefOrRef().ResolveTypeDefThrow();
                        if (context.Modules.Contains((ModuleDefMD)typeDef.Module))
                        {
                            PropertyDef property = typeDef.FindProperty(cmdName);
                            if (property != null)
                            {
                                var reference = new BAMLConverterMemberReference(xmlnsCtx, sig, property, rec);
                                AddTypeSigReference(sig, reference);
                                service.ReduceRenameMode(property, RenameMode.Letters);
                                service.AddReference(property, reference);
                            }
                            FieldDef field = typeDef.FindField(cmdName);
                            if (field != null)
                            {
                                var reference = new BAMLConverterMemberReference(xmlnsCtx, sig, field, rec);
                                AddTypeSigReference(sig, reference);
                                service.ReduceRenameMode(field, RenameMode.Letters);
                                service.AddReference(field, reference);
                            }
                            if (property == null && field == null)
                            {
                                context.Logger.WarnFormat("Could not resolve command '{0}' in '{1}'.", cmd, CurrentBAMLName);
                            }
                        }
                    }
                }
            }
            else if (converter.FullName == "System.Windows.Markup.DependencyPropertyConverter")
            {
                // Umm... Again nothing to do, DP already won't be renamed.
            }
            else if (converter.FullName == "System.Windows.PropertyPathConverter")
            {
                AnalyzePropertyPath(rec.Value);
            }
            else if (converter.FullName == "System.Windows.Markup.RoutedEventConverter")
            {
                ;
            }
            else if (converter.FullName == "System.Windows.Markup.TypeTypeConverter")
            {
                string  prefix;
                TypeSig sig = ResolveType(rec.Value.Trim(), out prefix);
                if (sig != null && context.Modules.Contains((ModuleDefMD)sig.ToBasicTypeDefOrRef().ResolveTypeDefThrow().Module))
                {
                    var reference = new BAMLConverterTypeReference(xmlnsCtx, sig, rec);
                    AddTypeSigReference(sig, reference);
                }
            }

            var    attrInfo = ResolveAttribute(rec.AttributeId);
            string attrName = null;

            if (attrInfo.Item1 != null)
            {
                attrName = attrInfo.Item1.Name;
            }
            else if (attrInfo.Item2 != null)
            {
                attrName = attrInfo.Item2.Name;
            }

            if (attrName == "DisplayMemberPath")
            {
                AnalyzePropertyPath(rec.Value);
            }
            else if (attrName == "Source")
            {
                string declType = null;
                if (attrInfo.Item1 is IMemberDef)
                {
                    declType = ((IMemberDef)attrInfo.Item1).DeclaringType.FullName;
                }
                else if (attrInfo.Item2 != null)
                {
                    declType = ResolveType(attrInfo.Item2.OwnerTypeId).FullName;
                }
                if (declType == "System.Windows.ResourceDictionary")
                {
                    var src = rec.Value.ToUpperInvariant();
                    if (src.EndsWith(".BAML") || src.EndsWith(".XAML"))
                    {
                        var match = WPFAnalyzer.UriPattern.Match(src);
                        if (match.Success)
                        {
                            src = match.Groups[1].Value;
                        }
                        else if (rec.Value.Contains("/"))
                        {
                            context.Logger.WarnFormat("Fail to extract XAML name from '{0}'.", rec.Value);
                        }

                        if (!src.Contains("//"))
                        {
                            var rel = new Uri(new Uri(packScheme + "application:,,,/" + CurrentBAMLName), src);
                            src = rel.LocalPath;
                        }
                        var reference = new BAMLPropertyReference(rec);
                        src = src.TrimStart('/');
                        var baml     = src.Substring(0, src.Length - 5) + ".BAML";
                        var xaml     = src.Substring(0, src.Length - 5) + ".XAML";
                        var bamlRefs = service.FindRenamer <WPFAnalyzer>().bamlRefs;
                        bamlRefs.AddListEntry(baml, reference);
                        bamlRefs.AddListEntry(xaml, reference);
                        bamlRefs.AddListEntry(Uri.EscapeUriString(baml), reference);
                        bamlRefs.AddListEntry(Uri.EscapeUriString(xaml), reference);
                    }
                }
            }
        }
Esempio n. 11
0
File: Schema.cs Progetto: zhabis/nfx
        private Schema(Type trow)
        {
            lock (s_TypeLatch)
            {
                if (s_TypeLatch.Contains(trow))
                {
                    throw new CRUDException(StringConsts.CRUD_TYPED_ROW_RECURSIVE_FIELD_DEFINITION_ERROR.Args(trow.FullName));
                }

                s_TypeLatch.Add(trow);
                try
                {
                    m_Name = trow.AssemblyQualifiedName;


                    var tattrs = trow.GetCustomAttributes(typeof(TableAttribute), false).Cast <TableAttribute>();
                    m_TableAttrs = new List <TableAttribute>(tattrs);


                    m_FieldDefs = new OrderedRegistry <FieldDef>();
                    var props = GetFieldMembers(trow);
                    var order = 0;
                    foreach (var prop in props)
                    {
                        var fattrs = prop.GetCustomAttributes(typeof(FieldAttribute), false)
                                     .Cast <FieldAttribute>()
                                     .ToArray();

                        //20160318 DKh. Interpret [Field(CloneFromType)]
                        for (var i = 0; i < fattrs.Length; i++)
                        {
                            var attr = fattrs[i];
                            if (attr.CloneFromRowType == null)
                            {
                                continue;
                            }

                            if (fattrs.Length > 1)
                            {
                                throw new CRUDException(StringConsts.CRUD_TYPED_ROW_SINGLE_CLONED_FIELD_ERROR.Args(trow.FullName, prop.Name));
                            }

                            var clonedSchema = Schema.GetForTypedRow(attr.CloneFromRowType);
                            var clonedDef    = clonedSchema[prop.Name];
                            if (clonedDef == null)
                            {
                                throw new CRUDException(StringConsts.CRUD_TYPED_ROW_CLONED_FIELD_NOTEXISTS_ERROR.Args(trow.FullName, prop.Name));
                            }

                            fattrs = clonedDef.Attrs.ToArray();//replace these attrs from the cloned target
                            break;
                        }

                        var fdef = new FieldDef(prop.Name, order, prop.PropertyType, fattrs, prop);
                        m_FieldDefs.Register(fdef);

                        order++;
                    }
                    s_TypedRegistry.Register(this);
                    m_TypedRowType = trow;
                }
                finally
                {
                    s_TypeLatch.Remove(trow);
                }
            }    //lock
        }
 protected override void GetCallInfo(object context, FieldDef field, out IMethod calledMethod, out OpCode callOpcode)
 {
     calledMethod = module.ResolveToken(0x06000000 + field.MDToken.ToInt32()) as IMethod;
     callOpcode   = OpCodes.Call;
 }
Esempio n. 13
0
 public FieldAccessNode(FieldDef analyzedField, bool showWrites)
 {
     this.analyzedField = analyzedField ?? throw new ArgumentNullException(nameof(analyzedField));
     this.showWrites    = showWrites;
 }
Esempio n. 14
0
 public RuntimeSchema GetFieldSchema(FieldDef field)
 {
     Debug.Assert(HasValue);
     return new RuntimeSchema(schemaDef, field.type);
 }
Esempio n. 15
0
        /// <summary>
        ///     Clones the specified origin FieldDef.
        /// </summary>
        /// <param name="origin">The origin FieldDef.</param>
        /// <returns>The cloned FieldDef.</returns>
        static FieldDefUser Clone(FieldDef origin)
        {
            var ret = new FieldDefUser(origin.Name, null, origin.Attributes);

            return(ret);
        }
Esempio n. 16
0
        // Constructors

        public FieldAction(TypeDef type, FieldDef field)
            : base(type)
        {
            Field = field;
        }
Esempio n. 17
0
		/// <inheritdoc/>
		public override uint GetRid(FieldDef fd) {
			uint rid;
			if (fieldDefInfos.TryGetRid(fd, out rid))
				return rid;
			if (fd == null)
				Error("Field is null");
			else
				Error("Field {0} ({1:X8}) is not defined in this module ({2}). A field was removed that is still referenced by this module.", fd, fd.MDToken.Raw, module);
			return 0;
		}
Esempio n. 18
0
        public void Analyze(ConfuserContext context, INameService service, IDnlibDef def)
        {
            var module = def as ModuleDefMD;

            if (module == null)
            {
                return;
            }

            MDTable table;
            uint    len;

            // MemberRef
            table = module.TablesStream.Get(Table.Method);
            len   = table.Rows;
            IEnumerable <MethodDef> methods = Enumerable.Range(1, (int)len)
                                              .Select(rid => module.ResolveMethod((uint)rid));

            foreach (MethodDef method in methods)
            {
                foreach (MethodOverride methodImpl in method.Overrides)
                {
                    if (methodImpl.MethodBody is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodBody);
                    }
                    if (methodImpl.MethodDeclaration is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodDeclaration);
                    }
                }
                if (!method.HasBody)
                {
                    continue;
                }
                foreach (Instruction instr in method.Body.Instructions)
                {
                    if (instr.Operand is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)instr.Operand);
                    }
                    else if (instr.Operand is MethodSpec)
                    {
                        var spec = (MethodSpec)instr.Operand;
                        if (spec.Method is MemberRef)
                        {
                            AnalyzeMemberRef(context, service, (MemberRef)spec.Method);
                        }
                    }
                }
            }


            // CustomAttribute
            table = module.TablesStream.Get(Table.CustomAttribute);
            len   = table.Rows;
            IEnumerable <CustomAttribute> attrs = Enumerable.Range(1, (int)len)
                                                  .Select(rid => module.ResolveHasCustomAttribute(module.TablesStream.ReadCustomAttributeRow((uint)rid).Parent))
                                                  .Distinct()
                                                  .SelectMany(owner => owner.CustomAttributes);

            foreach (CustomAttribute attr in attrs)
            {
                if (attr.Constructor is MemberRef)
                {
                    AnalyzeMemberRef(context, service, (MemberRef)attr.Constructor);
                }

                foreach (CAArgument arg in attr.ConstructorArguments)
                {
                    AnalyzeCAArgument(context, service, arg);
                }

                foreach (CANamedArgument arg in attr.Fields)
                {
                    AnalyzeCAArgument(context, service, arg.Argument);
                }

                foreach (CANamedArgument arg in attr.Properties)
                {
                    AnalyzeCAArgument(context, service, arg.Argument);
                }

                TypeDef attrType = attr.AttributeType.ResolveTypeDefThrow();
                if (!context.Modules.Contains((ModuleDefMD)attrType.Module))
                {
                    continue;
                }

                foreach (CANamedArgument fieldArg in attr.Fields)
                {
                    FieldDef field = attrType.FindField(fieldArg.Name, new FieldSig(fieldArg.Type));
                    if (field == null)
                    {
                        context.Logger.WarnFormat("Failed to resolve CA field '{0}::{1} : {2}'.", attrType, fieldArg.Name, fieldArg.Type);
                    }
                    else
                    {
                        service.AddReference(field, new CAMemberReference(fieldArg, field));
                    }
                }
                foreach (CANamedArgument propertyArg in attr.Properties)
                {
                    PropertyDef property = attrType.FindProperty(propertyArg.Name, new PropertySig(true, propertyArg.Type));
                    if (property == null)
                    {
                        context.Logger.WarnFormat("Failed to resolve CA property '{0}::{1} : {2}'.", attrType, propertyArg.Name, propertyArg.Type);
                    }
                    else
                    {
                        service.AddReference(property, new CAMemberReference(propertyArg, property));
                    }
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Записать таблицу dataTable в файл или поток
        /// </summary>
        public void Update(DataTable dataTable)
        {
            if (dataTable == null)
                throw new ArgumentNullException("dataTable");

            Stream stream = null;
            BinaryWriter writer = null;

            try
            {
                stream = ioStream == null ?
                    new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite) :
                    ioStream;
                writer = new BinaryWriter(stream, Encoding.Default);

                // запись заголовка
                byte fieldCnt = dataTable.Columns.Count > byte.MaxValue ?
                    byte.MaxValue : (byte)dataTable.Columns.Count;
                writer.Write(fieldCnt);
                writer.Write((ushort)0); // резерв

                if (fieldCnt > 0)
                {
                    // формирование и запись определений полей
                    FieldDef[] fieldDefs = new FieldDef[fieldCnt];
                    int recSize = 2; // размер строки в файле
                    byte[] buf = new byte[FieldDefSize];
                    buf[FieldDefSize - 1] = buf[FieldDefSize - 2] = 0; // резерв

                    for (int i = 0; i < fieldCnt; i++)
                    {
                        FieldDef fieldDef = new FieldDef();
                        DataColumn col = dataTable.Columns[i];
                        Type type = col.DataType;

                        if (type == typeof(int))
                        {
                            fieldDef.DataType = DataTypes.Integer;
                            fieldDef.DataSize = sizeof(int);
                        }
                        else if (type == typeof(double))
                        {
                            fieldDef.DataType = DataTypes.Double;
                            fieldDef.DataSize = sizeof(double);
                        }
                        else if (type == typeof(bool))
                        {
                            fieldDef.DataType = DataTypes.Boolean;
                            fieldDef.DataSize = 1;
                        }
                        else if (type == typeof(DateTime))
                        {
                            fieldDef.DataType = DataTypes.DateTime;
                            fieldDef.DataSize = sizeof(double);
                        }
                        else
                        {
                            fieldDef.DataType = DataTypes.String;
                            int maxLen = col.MaxLength;
                            fieldDef.DataSize = 0 < maxLen && maxLen <= MaxStringLen ?
                                (ushort)maxLen + 2 : (ushort)MaxStringLen + 2;
                        }

                        fieldDef.AllowNull = col.AllowDBNull;
                        fieldDef.Name = col.ColumnName;

                        recSize += fieldDef.DataSize;
                        if (fieldDef.AllowNull)
                            recSize++;
                        fieldDefs[i] = fieldDef;

                        buf[0] = (byte)fieldDef.DataType;
                        Array.Copy(BitConverter.GetBytes((ushort)fieldDef.DataSize), 0, buf, 1, 2);
                        buf[3] = fieldDef.AllowNull ? (byte)1 : (byte)0;
                        ConvertStr(fieldDef.Name, MaxFieldNameLen, buf, 4);

                        writer.Write(buf);
                    }

                    // запись строк
                    buf = new byte[recSize];
                    buf[0] = buf[1] = 0; // резерв
                    foreach (DataRow row in dataTable.Rows)
                    {
                        int bufInd = 2;

                        foreach (FieldDef fieldDef in fieldDefs)
                        {
                            int colInd = dataTable.Columns.IndexOf(fieldDef.Name);
                            object val = colInd >= 0 ? row[colInd] : null;
                            bool isNull = val == null || val == DBNull.Value;

                            if (fieldDef.AllowNull)
                                buf[bufInd++] = isNull ? (byte)1 : (byte)0;

                            switch (fieldDef.DataType)
                            {
                                case DataTypes.Integer:
                                    int intVal = isNull ? 0 : (int)val;
                                    Array.Copy(BitConverter.GetBytes(intVal), 0, buf, bufInd, fieldDef.DataSize);
                                    break;
                                case DataTypes.Double:
                                    double dblVal = isNull ? 0.0 : (double)val;
                                    Array.Copy(BitConverter.GetBytes(dblVal), 0, buf, bufInd, fieldDef.DataSize);
                                    break;
                                case DataTypes.Boolean:
                                    buf[bufInd] = (byte)(isNull ? 0 : (bool)val ? 1 : 0);
                                    break;
                                case DataTypes.DateTime:
                                    double dtVal = isNull ? 0.0 : Arithmetic.EncodeDateTime((DateTime)val);
                                    Array.Copy(BitConverter.GetBytes(dtVal), 0, buf, bufInd, fieldDef.DataSize);
                                    break;
                                default:
                                    string strVal = isNull ? "" : val.ToString();
                                    ConvertStr(strVal, fieldDef.DataSize - 2, buf, bufInd);
                                    break;
                            }

                            bufInd += fieldDef.DataSize;
                        }

                        writer.Write(buf);
                    }
                }
            }
            finally
            {
                if (fileMode)
                {
                    if (writer != null)
                        writer.Close();
                    if (stream != null)
                        stream.Close();
                }
            }
        }
Esempio n. 20
0
        public override object VisitBlockStatement(BlockStatement blockStatement, object data)
        {
            int numberOfVariablesOutsideBlock = currentlyUsedVariableNames.Count;

            base.VisitBlockStatement(blockStatement, data);
            foreach (ExpressionStatement stmt in blockStatement.Statements.OfType <ExpressionStatement>().ToArray())
            {
                Match displayClassAssignmentMatch = displayClassAssignmentPattern.Match(stmt);
                if (!displayClassAssignmentMatch.Success)
                {
                    continue;
                }

                ILVariable variable = displayClassAssignmentMatch.Get <AstNode>("variable").Single().Annotation <ILVariable>();
                if (variable == null)
                {
                    continue;
                }
                TypeDef type = variable.Type.ToTypeDefOrRef().ResolveWithinSameModule();
                if (!IsPotentialClosure(context, type))
                {
                    continue;
                }
                if (displayClassAssignmentMatch.Get <AstType>("type").Single().Annotation <ITypeDefOrRef>().ResolveWithinSameModule() != type)
                {
                    continue;
                }

                // Looks like we found a display class creation. Now let's verify that the variable is used only for field accesses:
                bool ok = true;
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name && identExpr != displayClassAssignmentMatch.Get("variable").Single())
                    {
                        if (!(identExpr.Parent is MemberReferenceExpression && identExpr.Parent.Annotation <IField>() != null))
                        {
                            ok = false;
                        }
                    }
                }
                if (!ok)
                {
                    continue;
                }
                Dictionary <IField, AstNode> dict = new Dictionary <IField, AstNode>();

                // Delete the variable declaration statement:
                VariableDeclarationStatement displayClassVarDecl = PatternStatementTransform.FindVariableDeclaration(stmt, variable.Name);
                if (displayClassVarDecl != null)
                {
                    displayClassVarDecl.Remove();
                }

                // Delete the assignment statement:
                AstNode cur = stmt.NextSibling;
                stmt.Remove();

                // Delete any following statements as long as they assign parameters to the display class
                BlockStatement    rootBlock            = blockStatement.Ancestors.OfType <BlockStatement>().LastOrDefault() ?? blockStatement;
                List <ILVariable> parameterOccurrances = rootBlock.Descendants.OfType <IdentifierExpression>()
                                                         .Select(n => n.Annotation <ILVariable>()).Where(p => p != null && p.IsParameter).ToList();
                AstNode next;
                for (; cur != null; cur = next)
                {
                    next = cur.NextSibling;

                    // Test for the pattern:
                    // "variableName.MemberName = right;"
                    ExpressionStatement closureFieldAssignmentPattern = new ExpressionStatement(
                        new AssignmentExpression(
                            new NamedNode("left", new MemberReferenceExpression {
                        Target     = new IdentifierExpression(variable.Name),
                        MemberName = Pattern.AnyString
                    }),
                            new AnyNode("right")
                            )
                        );
                    Match m = closureFieldAssignmentPattern.Match(cur);
                    if (m.Success)
                    {
                        FieldDef fieldDef    = m.Get <MemberReferenceExpression>("left").Single().Annotation <IField>().ResolveFieldWithinSameModule();
                        AstNode  right       = m.Get <AstNode>("right").Single();
                        bool     isParameter = false;
                        bool     isDisplayClassParentPointerAssignment = false;
                        if (right is ThisReferenceExpression)
                        {
                            isParameter = true;
                        }
                        else if (right is IdentifierExpression)
                        {
                            // handle parameters only if the whole method contains no other occurrence except for 'right'
                            ILVariable v = right.Annotation <ILVariable>();
                            isParameter = v.IsParameter && parameterOccurrances.Count(c => c == v) == 1;
                            if (!isParameter && IsPotentialClosure(context, v.Type.ToTypeDefOrRef().ResolveWithinSameModule()))
                            {
                                // parent display class within the same method
                                // (closure2.localsX = closure1;)
                                isDisplayClassParentPointerAssignment = true;
                            }
                        }
                        else if (right is MemberReferenceExpression)
                        {
                            // copy of parent display class reference from an outer lambda
                            // closure2.localsX = this.localsY
                            MemberReferenceExpression mre = m.Get <MemberReferenceExpression>("right").Single();
                            do
                            {
                                // descend into the targets of the mre as long as the field types are closures
                                FieldDef fieldDef2 = mre.Annotation <IField>().ResolveFieldWithinSameModule();
                                if (fieldDef2 == null || !IsPotentialClosure(context, fieldDef2.FieldType.ToTypeDefOrRef().ResolveWithinSameModule()))
                                {
                                    break;
                                }
                                // if we finally get to a this reference, it's copying a display class parent pointer
                                if (mre.Target is ThisReferenceExpression)
                                {
                                    isDisplayClassParentPointerAssignment = true;
                                }
                                mre = mre.Target as MemberReferenceExpression;
                            } while (mre != null);
                        }
                        if (isParameter || isDisplayClassParentPointerAssignment)
                        {
                            dict[fieldDef] = right;
                            cur.Remove();
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                // Now create variables for all fields of the display class (except for those that we already handled as parameters)
                List <Tuple <AstType, ILVariable> > variablesToDeclare = new List <Tuple <AstType, ILVariable> >();
                foreach (FieldDef field in type.Fields)
                {
                    if (field.IsStatic)
                    {
                        continue;                         // skip static fields
                    }
                    if (dict.ContainsKey(field))          // skip field if it already was handled as parameter
                    {
                        continue;
                    }
                    string capturedVariableName = field.Name;
                    if (capturedVariableName.StartsWith("$VB$Local_", StringComparison.Ordinal) && capturedVariableName.Length > 10)
                    {
                        capturedVariableName = capturedVariableName.Substring(10);
                    }
                    EnsureVariableNameIsAvailable(blockStatement, capturedVariableName);
                    currentlyUsedVariableNames.Add(capturedVariableName);
                    ILVariable ilVar = new ILVariable
                    {
                        IsGenerated = true,
                        Name        = capturedVariableName,
                        Type        = field.FieldType,
                    };
                    variablesToDeclare.Add(Tuple.Create(AstBuilder.ConvertType(field.FieldType, field), ilVar));
                    dict[field] = new IdentifierExpression(capturedVariableName).WithAnnotation(ilVar);
                }

                // Now figure out where the closure was accessed and use the simpler replacement expression there:
                foreach (var identExpr in blockStatement.Descendants.OfType <IdentifierExpression>())
                {
                    if (identExpr.Identifier == variable.Name)
                    {
                        MemberReferenceExpression mre = (MemberReferenceExpression)identExpr.Parent;
                        AstNode replacement;
                        if (dict.TryGetValue(mre.Annotation <IField>().ResolveFieldWithinSameModule(), out replacement))
                        {
                            mre.ReplaceWith(replacement.Clone());
                        }
                    }
                }
                // Now insert the variable declarations (we can do this after the replacements only so that the scope detection works):
                Statement insertionPoint = blockStatement.Statements.FirstOrDefault();
                foreach (var tuple in variablesToDeclare)
                {
                    var newVarDecl = new VariableDeclarationStatement(tuple.Item1, tuple.Item2.Name);
                    newVarDecl.Variables.Single().AddAnnotation(new CapturedVariableAnnotation());
                    newVarDecl.Variables.Single().AddAnnotation(tuple.Item2);
                    blockStatement.Statements.InsertBefore(insertionPoint, newVarDecl);
                }
            }
            currentlyUsedVariableNames.RemoveRange(numberOfVariablesOutsideBlock, currentlyUsedVariableNames.Count - numberOfVariablesOutsideBlock);
            return(null);
        }
Esempio n. 21
0
 public void add(FieldDef f)
 {
     fields.add(f);
 }
Esempio n. 22
0
        public Form ShowTabular(string FreeFilter,
                                object TransStartDate, object TransEndDate,
                                params object[] Parameters)
        {
            if (!BaseWinFramework.CheckModuleAccessWithError(ModuleName,
                                                             SecurityVarName.ReportView, true))
            {
                return(null);
            }

            using (new WaitCursor())
            {
                if (!TypeChecked)
                {
                    CheckEntityType();
                }

                if (_UIN != null)
                {
                    IRuleInitUI riu = (IRuleInitUI)_UIN.Entity;
                    _DataFilter   = riu.GetBrowseFilter();
                    BrowseColumns = riu.GetBrowseColumns();
                    riu.GetBrowseSql(out BrowseSql, out BrowseCondition, out BrowseOrder);
                    BrowseFormat.Clear();
                    riu.GetBrowseFormat(BrowseFormat);

                    TableDef td = MetaData.GetTableDef(riu.GetType());
                    if (riu.GetFieldTransactionDate().Length == 0)
                    {
                        fldTransactionDate = td.fldTransactionDate;
                    }
                    else
                    {
                        fldTransactionDate = td.GetFieldDef(
                            riu.GetFieldTransactionDate());
                    }
                }

                if (_BrowseForm == null || _BrowseForm.IsDisposed ||
                    _BrowseType != BrowseType.Tabular)
                {
                    if (BaseWinFramework.TouchScreenVersion)
                    {
                        _BrowseForm = new frmGridReportTC();
                    }
                    else
                    {
                        _BrowseForm = new frmGridReport();
                    }

                    _BrowseForm.MdiParent = BaseWinFramework._MdiParent;
                    _BrowseType           = BrowseType.Tabular;
                    ((IBrowseForm)_BrowseForm).ShowForm2(this, ModuleName,
                                                         FreeFilter, TransStartDate, TransEndDate, Parameters);
                }
                else
                {
                    ((IBrowseForm)_BrowseForm).ShowForm3(
                        FreeFilter, TransStartDate, TransEndDate, Parameters);
                }

                return(_BrowseForm);
            }
        }
Esempio n. 23
0
 public FieldNodeImpl(ITreeNodeGroup treeNodeGroup, FieldDef field)
     : base(field) => TreeNodeGroup = treeNodeGroup;
Esempio n. 24
0
 static FieldDefUser Clone(FieldDef originalField)
 {
     return(new FieldDefUser(originalField.Name, null, originalField.Attributes));
 }
Esempio n. 25
0
 public SelectFieldTransform(FieldDef field)
 {
     this.field = field;
 }
Esempio n. 26
0
        private FieldInfo BuildDeclaredField(TypeInfo type, FieldDef fieldDef)
        {
            BuildLog.Info(Strings.LogBuildingDeclaredFieldXY, type.Name, fieldDef.Name);

            var fieldInfo = new FieldInfo(type, fieldDef.Attributes)
            {
                UnderlyingProperty = fieldDef.UnderlyingProperty,
                Name         = fieldDef.Name,
                OriginalName = fieldDef.Name,
                MappingName  = fieldDef.MappingName,
                ValueType    = fieldDef.ValueType,
                ItemType     = fieldDef.ItemType,
                Length       = fieldDef.Length,
                Scale        = fieldDef.Scale,
                Precision    = fieldDef.Precision,
                Validators   = fieldDef.Validators,
            };

            if (fieldInfo.IsStructure && DeclaresOnValidate(fieldInfo.ValueType))
            {
                fieldInfo.Validators.Add(new StructureFieldValidator());
            }

            if (fieldInfo.IsEntitySet && DeclaresOnValidate(fieldInfo.ValueType))
            {
                fieldInfo.Validators.Add(new EntitySetFieldValidator());
            }

            type.Fields.Add(fieldInfo);

            if (fieldInfo.IsEntitySet)
            {
                AssociationBuilder.BuildAssociation(context, fieldDef, fieldInfo);
                return(fieldInfo);
            }

            if (fieldInfo.IsEntity)
            {
                var fields = context.Model.Types[fieldInfo.ValueType].Fields.Where(f => f.IsPrimaryKey);
                // Adjusting default value if any
                if (fields.Count() == 1 && fieldDef.DefaultValue != null)
                {
                    fieldInfo.DefaultValue = ValueTypeBuilder.AdjustValue(fieldInfo, fields.First().ValueType, fieldDef.DefaultValue);
                }
                BuildNestedFields(null, fieldInfo, fields);

                if (!IsAuxiliaryType(type))
                {
                    AssociationBuilder.BuildAssociation(context, fieldDef, fieldInfo);
                }

                // Adjusting type discriminator field for references
                if (fieldDef.IsTypeDiscriminator)
                {
                    type.Hierarchy.TypeDiscriminatorMap.Field = fieldInfo.Fields.First();
                }
            }

            if (fieldInfo.IsStructure)
            {
                BuildNestedFields(null, fieldInfo, context.Model.Types[fieldInfo.ValueType].Fields);
                var structureFullTextIndex = context.ModelDef.FullTextIndexes.TryGetValue(fieldInfo.ValueType);
                if (structureFullTextIndex != null)
                {
                    var hierarchyTypeInfo = context.Model.Types[fieldInfo.DeclaringType.UnderlyingType];
                    var structureTypeInfo = context.Model.Types[fieldInfo.ValueType];
                    var currentIndex      = context.ModelDef.FullTextIndexes.TryGetValue(hierarchyTypeInfo.UnderlyingType);
                    if (currentIndex == null)
                    {
                        currentIndex = new FullTextIndexDef(context.ModelDef.Types.TryGetValue(type.UnderlyingType));
                        context.ModelDef.FullTextIndexes.Add(currentIndex);
                    }
                    currentIndex.Fields.AddRange(structureFullTextIndex.Fields
                                                 .Select(f => new {
                        fieldInfo.DeclaringType.StructureFieldMapping[new Pair <FieldInfo>(fieldInfo, structureTypeInfo.Fields[f.Name])].Name,
                        f.IsAnalyzed,
                        f.Configuration,
                        f.TypeFieldName
                    })
                                                 .Select(g => new FullTextFieldDef(g.Name, g.IsAnalyzed)
                    {
                        Configuration = g.Configuration,
                        TypeFieldName = g.TypeFieldName
                    }));
                }
            }

            if (fieldInfo.IsPrimitive)
            {
                fieldInfo.DefaultValue         = fieldDef.DefaultValue;
                fieldInfo.DefaultSqlExpression = fieldDef.DefaultSqlExpression;
                fieldInfo.Column = BuildDeclaredColumn(fieldInfo);
                if (fieldDef.IsTypeDiscriminator)
                {
                    type.Hierarchy.TypeDiscriminatorMap.Field = fieldInfo;
                }
            }
            return(fieldInfo);
        }
Esempio n. 27
0
        public static void WriteOperand(ITextOutput writer, object operand, MethodDef method = null)
        {
            Instruction targetInstruction = operand as Instruction;

            if (targetInstruction != null)
            {
                WriteOffsetReference(writer, targetInstruction, method);
                return;
            }

            IList <Instruction> targetInstructions = operand as IList <Instruction>;

            if (targetInstructions != null)
            {
                WriteLabelList(writer, targetInstructions, method);
                return;
            }

            Local variable = operand as Local;

            if (variable != null)
            {
                if (string.IsNullOrEmpty(variable.Name))
                {
                    writer.WriteReference(variable.Index.ToString(), variable, TextTokenKind.Number);
                }
                else
                {
                    writer.WriteReference(Escape(variable.Name), variable, TextTokenKind.Local);
                }
                return;
            }

            Parameter paramRef = operand as Parameter;

            if (paramRef != null)
            {
                if (string.IsNullOrEmpty(paramRef.Name))
                {
                    if (paramRef.IsHiddenThisParameter)
                    {
                        writer.WriteReference("<hidden-this>", paramRef, TextTokenKind.Parameter);
                    }
                    else
                    {
                        writer.WriteReference(paramRef.MethodSigIndex.ToString(), paramRef, TextTokenKind.Parameter);
                    }
                }
                else
                {
                    writer.WriteReference(Escape(paramRef.Name), paramRef, TextTokenKind.Parameter);
                }
                return;
            }

            MemberRef memberRef = operand as MemberRef;

            if (memberRef != null)
            {
                if (memberRef.IsMethodRef)
                {
                    memberRef.WriteMethodTo(writer);
                }
                else
                {
                    memberRef.WriteFieldTo(writer);
                }
                return;
            }

            MethodDef methodDef = operand as MethodDef;

            if (methodDef != null)
            {
                methodDef.WriteMethodTo(writer);
                return;
            }

            FieldDef fieldDef = operand as FieldDef;

            if (fieldDef != null)
            {
                fieldDef.WriteFieldTo(writer);
                return;
            }

            ITypeDefOrRef typeRef = operand as ITypeDefOrRef;

            if (typeRef != null)
            {
                typeRef.WriteTo(writer, ILNameSyntax.TypeName);
                return;
            }

            IMethod m = operand as IMethod;

            if (m != null)
            {
                m.WriteMethodTo(writer);
                return;
            }

            MethodSig sig = operand as MethodSig;

            if (sig != null)
            {
                sig.WriteTo(writer);
                return;
            }

            string s = operand as string;

            if (s != null)
            {
                writer.Write("\"" + NRefactory.CSharp.TextWriterTokenWriter.ConvertString(s) + "\"", TextTokenKind.String);
            }
            else if (operand is char)
            {
                writer.Write(((int)(char)operand).ToString(), TextTokenKind.Number);
            }
            else if (operand is float)
            {
                float val = (float)operand;
                if (val == 0)
                {
                    if (1 / val == float.NegativeInfinity)
                    {
                        // negative zero is a special case
                        writer.Write("-0.0", TextTokenKind.Number);
                    }
                    else
                    {
                        writer.Write("0.0", TextTokenKind.Number);
                    }
                }
                else if (float.IsInfinity(val) || float.IsNaN(val))
                {
                    byte[] data = BitConverter.GetBytes(val);
                    writer.Write("(", TextTokenKind.Operator);
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (i > 0)
                        {
                            writer.WriteSpace();
                        }
                        writer.Write(data[i].ToString("X2"), TextTokenKind.Number);
                    }
                    writer.Write(")", TextTokenKind.Operator);
                }
                else
                {
                    writer.Write(val.ToString("R", System.Globalization.CultureInfo.InvariantCulture), TextTokenKind.Number);
                }
            }
            else if (operand is double)
            {
                double val = (double)operand;
                if (val == 0)
                {
                    if (1 / val == double.NegativeInfinity)
                    {
                        // negative zero is a special case
                        writer.Write("-0.0", TextTokenKind.Number);
                    }
                    else
                    {
                        writer.Write("0.0", TextTokenKind.Number);
                    }
                }
                else if (double.IsInfinity(val) || double.IsNaN(val))
                {
                    byte[] data = BitConverter.GetBytes(val);
                    writer.Write("(", TextTokenKind.Operator);
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (i > 0)
                        {
                            writer.WriteSpace();
                        }
                        writer.Write(data[i].ToString("X2"), TextTokenKind.Number);
                    }
                    writer.Write(")", TextTokenKind.Operator);
                }
                else
                {
                    writer.Write(val.ToString("R", System.Globalization.CultureInfo.InvariantCulture), TextTokenKind.Number);
                }
            }
            else if (operand is bool)
            {
                writer.Write((bool)operand ? "true" : "false", TextTokenKind.Keyword);
            }
            else
            {
                s = ToInvariantCultureString(operand);
                writer.Write(s, TextTokenKindUtils.GetTextTokenType(operand));
            }
        }
        void HandleInstanceFieldInitializers(IEnumerable <AstNode> members)
        {
            var instanceCtors = members.OfType <ConstructorDeclaration>().Where(c => (c.Modifiers & Modifiers.Static) == 0).ToArray();
            var instanceCtorsNotChainingWithThis = instanceCtors.Where(ctor => !thisCallPattern.IsMatch(ctor.Body.Statements.FirstOrDefault())).ToArray();

            if (instanceCtorsNotChainingWithThis.Length > 0)
            {
                MethodDef ctorMethodDef = instanceCtorsNotChainingWithThis[0].Annotation <MethodDef>();
                if (ctorMethodDef != null && DnlibExtensions.IsValueType(ctorMethodDef.DeclaringType))
                {
                    return;
                }

                // Recognize field initializers:
                // Convert first statement in all ctors (if all ctors have the same statement) into a field initializer.
                bool allSame;
                do
                {
                    Match m = fieldInitializerPattern.Match(instanceCtorsNotChainingWithThis[0].Body.FirstOrDefault());
                    if (!m.Success)
                    {
                        break;
                    }

                    FieldDef fieldDef = m.Get <AstNode>("fieldAccess").Single().Annotation <IField>().ResolveFieldWithinSameModule();
                    if (fieldDef == null)
                    {
                        break;
                    }
                    AstNode fieldOrEventDecl = members.FirstOrDefault(f => f.Annotation <FieldDef>() == fieldDef);
                    if (fieldOrEventDecl == null)
                    {
                        break;
                    }
                    Expression initializer = m.Get <Expression>("initializer").Single();
                    // 'this'/'base' cannot be used in field initializers
                    if (initializer.DescendantsAndSelf.Any(n => n is ThisReferenceExpression || n is BaseReferenceExpression))
                    {
                        break;
                    }

                    allSame = true;
                    for (int i = 1; i < instanceCtorsNotChainingWithThis.Length; i++)
                    {
                        if (!instanceCtors[0].Body.First().IsMatch(instanceCtorsNotChainingWithThis[i].Body.FirstOrDefault()))
                        {
                            allSame = false;
                            break;
                        }
                    }
                    if (allSame)
                    {
                        var ctorIlRanges = new List <Tuple <MemberMapping, List <ILRange> > >(instanceCtorsNotChainingWithThis.Length);
                        for (int i = 0; i < instanceCtorsNotChainingWithThis.Length; i++)
                        {
                            var ctor = instanceCtorsNotChainingWithThis[i];
                            var stmt = ctor.Body.First();
                            stmt.Remove();
                            var mm = ctor.Annotation <MemberMapping>() ?? ctor.Body.Annotation <MemberMapping>();
                            Debug.Assert(mm != null);
                            if (mm != null)
                            {
                                ctorIlRanges.Add(Tuple.Create(mm, stmt.GetAllRecursiveILRanges()));
                            }
                        }
                        var varInit = fieldOrEventDecl.GetChildrenByRole(Roles.Variable).Single();
                        initializer.Remove();
                        initializer.RemoveAllILRangesRecursive();
                        varInit.Initializer = initializer;
                        fieldOrEventDecl.AddAnnotation(ctorIlRanges);
                    }
                } while (allSame);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Is this a temporary variable generated by the C# compiler for instance method calls on value type values
        /// </summary>
        /// <param name="next">The next top-level expression</param>
        /// <param name="parent">The direct parent of the load within 'next'</param>
        /// <param name="pos">Index of the load within 'parent'</param>
        /// <param name="v">The variable being inlined.</param>
        /// <param name="inlinedExpression">The expression being inlined</param>
        bool IsGeneratedValueTypeTemporary(ILExpression next, ILExpression parent, int pos, ILVariable v, ILExpression inlinedExpression)
        {
            if (pos == 0 && v.Type != null && DnlibExtensions.IsValueType(v.Type))
            {
                // Inlining a value type variable is allowed only if the resulting code will maintain the semantics
                // that the method is operating on a copy.
                // Thus, we have to disallow inlining of other locals, fields, array elements, dereferenced pointers
                switch (inlinedExpression.Code)
                {
                case ILCode.Ldloc:
                case ILCode.Stloc:
                case ILCode.CompoundAssignment:
                case ILCode.Ldelem:
                case ILCode.Ldelem_I:
                case ILCode.Ldelem_I1:
                case ILCode.Ldelem_I2:
                case ILCode.Ldelem_I4:
                case ILCode.Ldelem_I8:
                case ILCode.Ldelem_R4:
                case ILCode.Ldelem_R8:
                case ILCode.Ldelem_Ref:
                case ILCode.Ldelem_U1:
                case ILCode.Ldelem_U2:
                case ILCode.Ldelem_U4:
                case ILCode.Ldobj:
                case ILCode.Ldind_Ref:
                    return(false);

                case ILCode.Ldfld:
                case ILCode.Stfld:
                case ILCode.Ldsfld:
                case ILCode.Stsfld:
                    // allow inlining field access only if it's a readonly field
                    FieldDef f = ((IField)inlinedExpression.Operand).Resolve();
                    if (!(f != null && f.IsInitOnly))
                    {
                        return(false);
                    }
                    break;

                case ILCode.Call:
                case ILCode.CallGetter:
                    // inlining runs both before and after IntroducePropertyAccessInstructions,
                    // so we have to handle both 'call' and 'callgetter'
                    IMethod mr = (IMethod)inlinedExpression.Operand;
                    // ensure that it's not an multi-dimensional array getter
                    TypeSig ts;
                    if (mr.DeclaringType is TypeSpec && (ts = ((TypeSpec)mr.DeclaringType).TypeSig.RemovePinnedAndModifiers()) != null && ts.IsSingleOrMultiDimensionalArray)
                    {
                        return(false);
                    }
                    goto case ILCode.Callvirt;

                case ILCode.Callvirt:
                case ILCode.CallvirtGetter:
                    // don't inline foreach loop variables:
                    mr = (IMethod)inlinedExpression.Operand;
                    if (mr.Name == "get_Current" && mr.MethodSig != null && mr.MethodSig.HasThis)
                    {
                        return(false);
                    }
                    break;

                case ILCode.Castclass:
                case ILCode.Unbox_Any:
                    // These are valid, but might occur as part of a foreach loop variable.
                    ILExpression arg = inlinedExpression.Arguments[0];
                    if (arg.Code == ILCode.CallGetter || arg.Code == ILCode.CallvirtGetter || arg.Code == ILCode.Call || arg.Code == ILCode.Callvirt)
                    {
                        mr = (IMethod)arg.Operand;
                        if (mr.Name == "get_Current" && mr.MethodSig != null && mr.MethodSig.HasThis)
                        {
                            return(false);                                    // looks like a foreach loop variable, so don't inline it
                        }
                    }
                    break;
                }

                // inline the compiler-generated variable that are used when accessing a member on a value type:
                switch (parent.Code)
                {
                case ILCode.Call:
                case ILCode.CallGetter:
                case ILCode.CallSetter:
                case ILCode.Callvirt:
                case ILCode.CallvirtGetter:
                case ILCode.CallvirtSetter:
                    IMethod mr = parent.Operand as IMethod;
                    return(mr == null || mr.MethodSig == null ? false : mr.MethodSig.HasThis);

                case ILCode.Stfld:
                case ILCode.Ldfld:
                case ILCode.Ldflda:
                case ILCode.Await:
                    return(true);
                }
            }
            return(false);
        }
Esempio n. 30
0
 public ModelInfo(FieldDef field)
 {
     OwnerType  = field.DeclaringType;
     FieldIndex = OwnerType.Fields.IndexOf(field);
     Debug.Assert(FieldIndex >= 0);
 }
Esempio n. 31
0
        /// <summary>
        ///     Copies the information from the origin field to injected field.
        /// </summary>
        /// <param name="fieldDef">The origin FieldDef.</param>
        /// <param name="ctx">The injection context.</param>
        static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx)
        {
            var newFieldDef = (FieldDef)ctx.Map[fieldDef];

            newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature);
        }
Esempio n. 32
0
 public virtual void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) =>
 this.WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name);
		/// <inheritdoc/>
		public override uint GetRid(FieldDef fd) {
			uint rid;
			if (fieldDefInfos.TryGetRid(fd, out rid))
				return rid;
			if (fd == null)
				Error("Field is null");
			else
				Error("Field {0} ({1:X8}) is not defined in this module ({2})", fd, fd.MDToken.Raw, module);
			return 0;
		}
Esempio n. 34
0
 public IFieldNode Create(FieldDef field) => Context.DocumentTreeView.Create(field);
Esempio n. 35
0
 public FieldInfo field(FieldDef field)
 {
     return memberInfos.field(field);
 }
Esempio n. 36
0
        void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, FieldDef field)
        {
            if (field.DeclaringType.IsVisibleOutside() &&
                (field.IsFamily || field.IsFamilyOrAssembly || field.IsPublic) &&
                !parameters.GetParameter(context, field, "renPublic", false))
            {
                service.SetCanRename(field, false);
            }

            else if (field.IsRuntimeSpecialName || field.IsSpecialName)
            {
                service.SetCanRename(field, false);
            }

            else if (parameters.GetParameter(context, field, "forceRen", false))
            {
                return;
            }

            else if (field.DeclaringType.IsSerializable && !field.IsNotSerialized)
            {
                service.SetCanRename(field, false);
            }

            else if (field.IsLiteral && field.DeclaringType.IsEnum)
            {
                service.SetCanRename(field, false);
            }
        }
Esempio n. 37
0
        /// <summary>
        /// Заполнить таблицу dataTable из файла или потока
        /// </summary>
        public void Fill(DataTable dataTable, bool allowNulls)
        {
            if (dataTable == null)
                throw new ArgumentNullException("dataTable");

            Stream stream = null;
            BinaryReader reader = null;

            try
            {
                stream = ioStream == null ?
                    new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) :
                    ioStream;
                reader = new BinaryReader(stream);

                // считывание заголовка
                byte fieldCnt = reader.ReadByte(); // количество полей
                stream.Seek(2, SeekOrigin.Current);

                if (fieldCnt > 0)
                {
                    // считывание определений полей
                    FieldDef[] fieldDefs = new FieldDef[fieldCnt];
                    int recSize = 2; // размер строки в файле
                    byte[] buf = new byte[FieldDefSize];

                    for (int i = 0; i < fieldCnt; i++)
                    {
                        // загрузка данных определения поля в буфер для увеличения скорости работы
                        int readSize = reader.Read(buf, 0, FieldDefSize);

                        // заполение определения поля из буфера
                        if (readSize == FieldDefSize)
                        {
                            FieldDef fieldDef = new FieldDef();
                            fieldDef.DataType = buf[0];
                            fieldDef.DataSize = BitConverter.ToUInt16(buf, 1);
                            fieldDef.AllowNull = buf[3] > 0;
                            fieldDef.Name = (string)BytesToObj(buf, 4, DataTypes.String);
                            if (string.IsNullOrEmpty(fieldDef.Name))
                                throw new Exception("Field name can't be empty.");
                            fieldDefs[i] = fieldDef;

                            recSize += fieldDef.DataSize;
                            if (fieldDef.AllowNull)
                                recSize++;
                        }
                    }

                    // формирование структуры таблицы
                    dataTable.BeginLoadData();
                    dataTable.DefaultView.Sort = "";

                    if (dataTable.Columns.Count == 0)
                    {
                        foreach (FieldDef fieldDef in fieldDefs)
                        {
                            DataColumn column = new DataColumn(fieldDef.Name);
                            column.AllowDBNull = fieldDef.AllowNull;

                            switch (fieldDef.DataType)
                            {
                                case DataTypes.Integer:
                                    column.DataType = typeof(int);
                                    break;
                                case DataTypes.Double:
                                    column.DataType = typeof(double);
                                    break;
                                case DataTypes.Boolean:
                                    column.DataType = typeof(bool);
                                    break;
                                case DataTypes.DateTime:
                                    column.DataType = typeof(DateTime);
                                    break;
                                default:
                                    column.DataType = typeof(string);
                                    column.MaxLength = fieldDef.DataSize - 2;
                                    break;
                            }

                            dataTable.Columns.Add(column);
                        }

                        dataTable.DefaultView.AllowNew = false;
                        dataTable.DefaultView.AllowEdit = false;
                        dataTable.DefaultView.AllowDelete = false;
                    }
                    else
                    {
                        dataTable.Rows.Clear();
                    }

                    // считывание строк
                    buf = new byte[recSize];
                    while (stream.Position < stream.Length)
                    {
                        // загрузка данных строки таблицы в буфер для увеличения скорости работы
                        int readSize = reader.Read(buf, 0, recSize);

                        // заполение строки таблицы из буфера
                        if (readSize == recSize)
                        {
                            DataRow row = dataTable.NewRow();
                            int bufInd = 2;
                            foreach (FieldDef fieldDef in fieldDefs)
                            {
                                bool isNull = fieldDef.AllowNull ? buf[bufInd++] > 0 : false;
                                int colInd = dataTable.Columns.IndexOf(fieldDef.Name);
                                if (colInd >= 0)
                                    row[colInd] = allowNulls && isNull ?
                                        DBNull.Value : BytesToObj(buf, bufInd, fieldDef.DataType);
                                bufInd += fieldDef.DataSize;
                            }
                            dataTable.Rows.Add(row);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                // нормальная ситуация окончания файла
            }
            finally
            {
                if (fileMode)
                {
                    if (reader != null)
                        reader.Close();
                    if (stream != null)
                        stream.Close();
                }

                dataTable.EndLoadData();
                dataTable.AcceptChanges();

                if (dataTable.Columns.Count > 0)
                    dataTable.DefaultView.Sort = dataTable.Columns[0].ColumnName;
            }
        }
        public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var method = def as MethodDef;

            if (method == null || !method.HasBody)
            {
                return;
            }

            // When a ldtoken instruction reference a definition,
            // most likely it would be used in reflection and thus probably should not be renamed.
            // Also, when ToString is invoked on enum,
            // the enum should not be renamed.
            for (int i = 0; i < method.Body.Instructions.Count; i++)
            {
                Instruction instr = method.Body.Instructions[i];
                if (instr.OpCode.Code == Code.Ldtoken)
                {
                    if (instr.Operand is MemberRef)
                    {
                        IMemberForwarded member = ((MemberRef)instr.Operand).ResolveThrow();
                        if (context.Modules.Contains((ModuleDefMD)member.Module))
                        {
                            service.SetCanRename(member, false);
                        }
                    }
                    else if (instr.Operand is IField)
                    {
                        FieldDef field = ((IField)instr.Operand).ResolveThrow();
                        if (context.Modules.Contains((ModuleDefMD)field.Module))
                        {
                            service.SetCanRename(field, false);
                        }
                    }
                    else if (instr.Operand is IMethod)
                    {
                        var im = (IMethod)instr.Operand;
                        if (!im.IsArrayAccessors())
                        {
                            MethodDef m = im.ResolveThrow();
                            if (context.Modules.Contains((ModuleDefMD)m.Module))
                            {
                                service.SetCanRename(method, false);
                            }
                        }
                    }
                    else if (instr.Operand is ITypeDefOrRef)
                    {
                        if (!(instr.Operand is TypeSpec))
                        {
                            TypeDef type = ((ITypeDefOrRef)instr.Operand).ResolveTypeDefThrow();
                            if (context.Modules.Contains((ModuleDefMD)type.Module) &&
                                HandleTypeOf(context, service, method, i))
                            {
                                var t = type;
                                do
                                {
                                    DisableRename(service, t, false);
                                    t = t.DeclaringType;
                                } while (t != null);
                            }
                        }
                    }
                    else
                    {
                        throw new UnreachableException();
                    }
                }
                else if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt) &&
                         ((IMethod)instr.Operand).Name == "ToString")
                {
                    HandleEnum(context, service, method, i);
                }
                else if (instr.OpCode.Code == Code.Ldstr)
                {
                    TypeDef typeDef = method.Module.FindReflection((string)instr.Operand);
                    if (typeDef != null)
                    {
                        service.AddReference(typeDef, new StringTypeReference(instr, typeDef));
                    }
                }
            }
        }
Esempio n. 39
0
		protected void AddReferenced (string signature, FieldDef field, Location location)
		{
			FieldTableItem item = new FieldTableItem (field, location);
			
			table[signature] = item;
		}
Esempio n. 40
0
        /// <summary>
        ///     Copies the information from the origin field to injected field.
        /// </summary>
        /// <param name="fieldDef">The origin FieldDef.</param>
        /// <param name="ctx">The injection context.</param>
        static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx)
        {
            var newFieldDef = ctx.Map(fieldDef).ResolveFieldDefThrow();

            newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature);
        }
Esempio n. 41
0
		protected void AddDefined (string signature, FieldDef field, Location location)
		{
			if (table.Contains (signature))
				return; 

			FieldTableItem item = new FieldTableItem (field, location);
			item.Defined = true;

			table[signature] = item;
		}
Esempio n. 42
0
        private Schema(Type tdoc)
        {
            lock (s_TypeLatch)
            {
                if (s_TypeLatch.Contains(tdoc))
                {
                    throw new DataException(StringConsts.CRUD_TYPED_DOC_RECURSIVE_FIELD_DEFINITION_ERROR.Args(tdoc.FullName));
                }

                s_TypeLatch.Add(tdoc);
                try
                {
                    m_Name = tdoc.AssemblyQualifiedName;

                    var tattrs = tdoc.GetCustomAttributes(typeof(SchemaAttribute), false).Cast <SchemaAttribute>();
                    tattrs.ForEach(a => a.StopPropAssignmentTracking());
                    m_SchemaAttrs = new List <SchemaAttribute>(tattrs);

                    //20191026 DKh. Expand resource references in Descriptions
                    m_SchemaAttrs.ForEach(a => { a.ExpandResourceReferencesRelativeTo(tdoc, null); a.Seal(); });

                    m_FieldDefs = new OrderedRegistry <FieldDef>();
                    var props = GetFieldMembers(tdoc);
                    var order = 0;
                    foreach (var prop in props)
                    {
                        var fattrs = prop.GetCustomAttributes(typeof(FieldAttribute), false)
                                     .Cast <FieldAttribute>()
                                     .ToArray();

                        fattrs.ForEach(a => a.StopPropAssignmentTracking());

                        //Interpret [Field(CloneFromType)]
                        for (var i = 0; i < fattrs.Length; i++)
                        {
                            var attr = fattrs[i];

                            if (attr.CloneFromDocType == null)
                            {
                                //20190831 DKh. Expand resource references in Descriptions
                                attr.ExpandResourceReferencesRelativeTo(tdoc, prop.Name);
                                continue;
                            }

                            if (fattrs.Length > 1)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_SINGLE_CLONED_FIELD_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            var clonedSchema = Schema.GetForTypedDoc(attr.CloneFromDocType);
                            var clonedDef    = clonedSchema[prop.Name];
                            if (clonedDef == null)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_CLONED_FIELD_NOTEXISTS_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            fattrs = clonedDef.Attrs.ToArray();//replace these attrs from the cloned target
                            break;
                        }

                        FieldAttribute.FixupInheritedTargets($"{tdoc.Name}.{prop.Name}", fattrs);

                        var fdef = new FieldDef(prop.Name, order, prop.PropertyType, fattrs, prop);
                        m_FieldDefs.Register(fdef);

                        order++;
                    }
                    s_TypedRegistry.Register(this);
                    m_TypedDocType = tdoc;
                }
                finally
                {
                    s_TypeLatch.Remove(tdoc);
                }
            }//lock
        }
Esempio n. 43
0
                public void AddFieldDef (FieldDef fielddef)
                {
                        if (current_field_native_type != null) {
                                fielddef.AddMarshalInfo (current_field_native_type);
                                current_field_native_type = null;
                        }

                        if (current_typedef != null) {
                                current_typedef.AddFieldDef (fielddef);
                        } else {
                                global_field_table.Add (
                                        new DictionaryEntry (fielddef.Name, fielddef.Type.FullName),
                                        fielddef);
                        }
                }
Esempio n. 44
0
 public FieldInfo field(FieldDef field)
 {
     return allFieldInfos[field];
 }