Пример #1
0
 private void DebugProc(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
 {
     string msg = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(message, length);
     Console.WriteLine(
         "{0} {1} {2} {3}: {4}",
         source, type, id, severity, msg);
 }
Пример #2
0
 private static void DebugCallback(DebugSource source, DebugType type, int id,
 DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
 {
     string msg = Marshal.PtrToStringAnsi(message);
     Console.WriteLine("[GL] {0}; {1}; {2}; {3}; {4}",
         source, type, id, severity, msg);
 }
 static void PCCallbackHandler(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
 {
     if (severity == DebugSeverity.DebugSeverityHigh || severity == DebugSeverity.DebugSeverityMedium)
     {
         string msg = Marshal.PtrToStringAnsi(message);
         Console.WriteLine("[GL] {0}; {1}; {2}; {3}; {4}", source, type, id, severity, msg);
     }
 }
Пример #4
0
		/// <summary>
		/// Creates an expression which, when evaluated, creates a List&lt;T&gt; in the debugee
		/// filled with contents of IEnumerable&lt;T&gt; from the debugee.
		/// </summary>
		/// <param name="iEnumerableVariable">Expression for IEnumerable variable in the debugee.</param>
		/// <param name="itemType">
		/// The generic argument of IEnumerable&lt;T&gt; that <paramref name="iEnumerableVariable"/> implements.</param>
		public static Expression CreateDebugListExpression(Expression iEnumerableVariable, DebugType itemType, out DebugType listType)
		{
			// is using itemType.AppDomain ok?
			listType = DebugType.CreateFromType(itemType.AppDomain, typeof(System.Collections.Generic.List<>), itemType);
			var iEnumerableType = DebugType.CreateFromType(itemType.AppDomain, typeof(IEnumerable<>), itemType);
			// explicitely cast the variable to IEnumerable<T>, where T is itemType
			Expression iEnumerableVariableExplicitCast = new CastExpression(iEnumerableType.GetTypeReference() , iEnumerableVariable, CastType.Cast);
			return new ObjectCreateExpression(listType.GetTypeReference(), iEnumerableVariableExplicitCast.ToList());
		}
Пример #5
0
        internal static void Debug(DebugType type, string s, params object[] args)
        {
            if (!Configuration.Debug.Contains(DebugType.All) &&
                !Configuration.Debug.Contains(type))
            {
                return;
            }

            string message = Output.Format(s, args);
            Console.WriteLine(message);
        }
Пример #6
0
        public LogEntry(char TypeId, string Tag, int Pid, string Message)
        {
            this.LogType = GetDebugTypeFromIdentifier(TypeId);

            if (this.LogType == DebugType.Unknown)
                throw new Exception("Unknown DebugType identifier");

            this.LogTag = Tag;
            this.Pid = Pid;
            this.LogMsg = Message;
        }
Пример #7
0
        /// <summary>
        /// Creates an expression which, when evaluated, creates a List&lt;T&gt; in the debugee
        /// filled with contents of IEnumerable&lt;T&gt; from the debugee.
        /// </summary>
        /// <param name="iEnumerableVariable">Expression for IEnumerable variable in the debugee.</param>
        /// <param name="itemType">
        /// The generic argument of IEnumerable&lt;T&gt; that <paramref name="iEnumerableVariable"/> implements.</param>
        public static Expression CreateDebugListExpression(Expression iEnumerableVariable, DebugType itemType, out DebugType listType)
        {
            // is using itemType.AppDomain ok?
            listType = DebugType.CreateFromType(itemType.AppDomain, typeof(System.Collections.Generic.List<>), itemType);
            var iEnumerableType = DebugType.CreateFromType(itemType.AppDomain, typeof(IEnumerable<>), itemType);
            // explicitely cast the variable to IEnumerable<T>, where T is itemType
            Expression iEnumerableVariableExplicitCast = new CastExpression { Expression = iEnumerableVariable.Clone() , Type = iEnumerableType.GetTypeReference() };

            var obj = new ObjectCreateExpression() { Type = listType.GetTypeReference() };
            obj.Arguments.Add(iEnumerableVariableExplicitCast);

            return obj;
        }
Пример #8
0
        public DebugRect(Point _Center, Point _Offset, int _Width, int _Height, DebugType _Type, Game _Game)
            : base(_Game)
        {
            Offset = _Offset;
            Color Color = Color.HotPink;
            switch (_Type)
            {
                case DebugType.View: { Color = Color.Blue; } break;
                case DebugType.Physics: { Color = Color.White; } break;
                case DebugType.Hostile: { Color = Color.Red; } break;
                case DebugType.Trigger: { Color = Color.Yellow; } break;
            }

            RectangeGraphic = new RectangeGraphic(new Rectangle(_Center.X - Offset.X, _Center.Y - Offset.Y, _Width, _Height), 3, Color, _Game);
        }
Пример #9
0
 /// <summary>
 /// 输出 debug 日志
 /// </summary>
 /// <param name="msg">输入内容</param>
 /// <param name="logType">输出的类型</param>
 private static void WriteDebug(object msg, DebugType logType)
 {
     if (!LCSConfig.IsDebugMode) return;
     switch (logType)
     {
         case DebugType.Log:
             UnityEngine.Debug.Log(msg);
             break;
         case DebugType.Warning:
             UnityEngine.Debug.LogWarning(msg);
             break;
         case DebugType.Error:
             UnityEngine.Debug.LogError(msg);
             break;
     }
 }
Пример #10
0
        internal Value(AppDomain appDomain, ICorDebugValue corValue)
        {
            if (corValue == null)
                throw new ArgumentNullException("corValue");
            this.appDomain = appDomain;
            this.corValue = corValue;
            this.corValue_pauseSession = this.Process.PauseSession;

            this.isNull = corValue is ICorDebugReferenceValue && ((ICorDebugReferenceValue)corValue).IsNull() != 0;

            if (corValue is ICorDebugReferenceValue &&
                ((ICorDebugReferenceValue)corValue).GetValue() == 0 &&
                ((ICorDebugValue2)corValue).GetExactType() == null)
            {
                // We were passed null reference and no metadata description
                // (happens during CreateThread callback for the thread object)
                this.type = appDomain.ObjectType;
            } else {
                ICorDebugType exactType = ((ICorDebugValue2)this.CorValue).GetExactType();
                this.type = DebugType.CreateFromCorType(appDomain, exactType);
            }
        }
Пример #11
0
        public static void Main(string[] args)
        {
            #region CommandlineArguments
            if (args.Length < 2 || args.Length > 3)
            {
                ShowUsage( );
                return;
            }

            string outputPath = args.Length == 3 ? args[2] : Environment.CurrentDirectory;

            string srcPath = args[1];
            if (!File.Exists(srcPath))
            {
                Console.Error.WriteLine("Src file not found: '{0}'", srcPath);
                return;
            }

            srcPath = Path.GetFullPath(srcPath);
            #endregion

            using var libLLVM = InitializeLLVM( );

            #region TargetDetailsSelection
            switch (args[0].ToUpperInvariant( ))
            {
            case "M3":
                TargetDetails = new CortexM3Details(libLLVM);
                break;

            case "X64":
                TargetDetails = new X64Details(libLLVM);
                break;

            default:
                ShowUsage( );
                return;
            }

            string moduleName = $"test_{TargetDetails.ShortName}.bc";
            #endregion

            #region CreatingModule
            using var context     = new Context( );
            using var module      = context.CreateBitcodeModule(moduleName, SourceLanguage.C99, srcPath, VersionIdentString);
            module.SourceFileName = Path.GetFileName(srcPath);
            module.TargetTriple   = TargetDetails.TargetMachine.Triple;
            module.Layout         = TargetDetails.TargetMachine.TargetData;
            Debug.Assert(!(module.DICompileUnit is null), "Expected module with non-null compile unit");

            TargetDependentAttributes = TargetDetails.BuildTargetDependentFunctionAttributes(context);
            #endregion

            var diFile = module.DIBuilder.CreateFile(srcPath);

            #region CreatingBasicTypesWithDebugInfo
            // Create basic types used in this compilation
            var i32           = new DebugBasicType(module.Context.Int32Type, module, "int", DiTypeKind.Signed);
            var f32           = new DebugBasicType(module.Context.FloatType, module, "float", DiTypeKind.Float);
            var voidType      = DebugType.Create <ITypeRef, DIType>(module.Context.VoidType, null);
            var i32Array_0_32 = i32.CreateArrayType(module, 0, 32);
            #endregion

            #region CreatingStructureTypes
            // create the LLVM structure type and body with full debug information
            var fooBody = new[]
            {
                new DebugMemberInfo(0, "a", diFile, 3, i32),
                new DebugMemberInfo(1, "b", diFile, 4, f32),
                new DebugMemberInfo(2, "c", diFile, 5, i32Array_0_32),
            };

            var fooType = new DebugStructType(module, "struct.foo", module.DICompileUnit, "foo", diFile, 1, DebugInfoFlags.None, fooBody);
            #endregion

            #region CreatingGlobalsAndMetadata
            // add global variables and constants
            var constArray = ConstantArray.From(i32, 32, module.Context.CreateConstant(3), module.Context.CreateConstant(4));
            var barValue   = module.Context.CreateNamedConstantStruct(fooType
                                                                      , module.Context.CreateConstant(1)
                                                                      , module.Context.CreateConstant(2.0f)
                                                                      , constArray
                                                                      );

            var bar = module.AddGlobal(fooType, false, 0, barValue, "bar");
            bar.Alignment = module.Layout.AbiAlignmentOf(fooType);
            bar.AddDebugInfo(module.DIBuilder.CreateGlobalVariableExpression(module.DICompileUnit, "bar", string.Empty, diFile, 8, fooType.DIType, false, null));

            var baz = module.AddGlobal(fooType, false, Linkage.Common, Constant.NullValueFor(fooType), "baz");
            baz.Alignment = module.Layout.AbiAlignmentOf(fooType);
            baz.AddDebugInfo(module.DIBuilder.CreateGlobalVariableExpression(module.DICompileUnit, "baz", string.Empty, diFile, 9, fooType.DIType, false, null));

            // add module flags and compiler identifiers...
            // this can technically occur at any point, though placing it here makes
            // comparing against clang generated files easier
            AddModuleFlags(module);
            #endregion

            #region CreatingQualifiedTypes
            // create types for function args
            var constFoo = module.DIBuilder.CreateQualifiedType(fooType.DIType, QualifiedTypeTag.Const);
            var fooPtr   = new DebugPointerType(fooType, module);
            #endregion

            // Create the functions
            // NOTE: The declaration ordering is reversed from that of the sample code file (test.c)
            //       However, this is what Clang ends up doing for some reason so it is
            //       replicated here to aid in comparing the generated LL files.
            IrFunction doCopyFunc = DeclareDoCopyFunc(module, diFile, voidType);
            IrFunction copyFunc   = DeclareCopyFunc(module, diFile, voidType, constFoo, fooPtr);

            CreateCopyFunctionBody(module, copyFunc, diFile, fooType, fooPtr, constFoo);
            CreateDoCopyFunctionBody(module, doCopyFunc, fooType, bar, baz, copyFunc);

            // finalize the debug information
            // all temporaries must be replaced by now, this resolves any remaining
            // forward declarations and marks the builder to prevent adding any
            // nodes that are not completely resolved.
            module.DIBuilder.Finish( );

            // verify the module is still good and print any errors found
            if (!module.Verify(out string msg))
            {
                Console.Error.WriteLine("ERROR: {0}", msg);
            }
            else
            {
                // test optimization works, but don't save it as that makes it harder to do a compare with official clang builds
                {// force a GC to verify callback delegate for diagnostics is still valid, this is for test only and wouldn't
                    // normally be done in production code.
                    GC.Collect(GC.MaxGeneration);
                    using var modForOpt = module.Clone( );
                    // NOTE:
                    // The ordering of passes can matter depending on the pass, and passes may be added more than once
                    // the caller has full control of ordering, this is just a sample of effectively randomly picked
                    // passes and not necessarily a reflection of any particular use case.
                    var pm = new ModulePassManager( );
                    pm.AddAlwaysInlinerPass( )
                    .AddAggressiveDCEPass( )
                    .AddArgumentPromotionPass( )
                    .AddBasicAliasAnalysisPass( )
                    .AddBitTrackingDCEPass( )
                    .AddCFGSimplificationPass( )
                    .AddConstantMergePass( )
                    .AddConstantPropagationPass( )
                    .AddFunctionInliningPass( )
                    .AddGlobalOptimizerPass( )
                    .AddInstructionCombiningPass( )
                    .Run(modForOpt);
                }

                // Module is good, so generate the output files
                module.WriteToFile(Path.Combine(outputPath, "test.bc"));
                File.WriteAllText(Path.Combine(outputPath, "test.ll"), module.WriteToString( ));
                TargetDetails.TargetMachine.EmitToFile(module, Path.Combine(outputPath, "test.o"), CodeGenFileType.ObjectFile);
                TargetDetails.TargetMachine.EmitToFile(module, Path.Combine(outputPath, "test.s"), CodeGenFileType.AssemblySource);
                Console.WriteLine("Generated test.bc, test.ll, test.o, and test.s");
            }
        }
Пример #12
0
 /// <summary>
 /// Outputs the Debug-Messages to the debug-console.
 /// </summary>
 /// <param name="pMessage">Debug-Message</param>
 /// <param name="pParameters">Output-Parameters [Not required for ToDebug-Method]</param>
 public static void ToDebug(string pMessage, DebugType pDebugType, params object[] pParameters) => Debug.Print(pMessage);
Пример #13
0
        /// <summary>
        /// Retrives a number of messages from message log and return the messages in array.
        /// </summary>
        /// <param name="sources"></param>
        /// <param name="types"></param>
        /// <param name="ids"></param>
        /// <param name="severities"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string[] GetDebugMessageLog(DebugSource[] sources, DebugType[] types, uint[] ids, DebugSeverity[] severities, int count = -1)
        {
            if (count == -1)
            {
                count = GetIntegerv(GetParameters.DebugLoggedMessages);
            }
            else
                count = Math.Min(sources.Length, Math.Min(types.Length, Math.Min(ids.Length, severities.Length))); // , MessageLogs.Length))));

            var maxmessagelength = GetIntegerv(GetParameters.MaxDebugMessageLength);
            var sb = new StringBuilder(count * maxmessagelength + 4);

            var lengths = new int[count];

            var result = (int)Delegates.glGetDebugMessageLog((uint)count, sb.Capacity - 2, ref sources[0], ref types[0], ref ids[0], ref severities[0], ref lengths[0], sb);

            if (result > 0)
            {
                var messages = new string[Math.Min(result, lengths.Length)];
                int lastpos = 0;
                for (int i = 0; i < messages.Length; i++)
                {
                    messages[i] = sb.ToString(lastpos, lengths[i] - 1);
                    lastpos = lengths[i];
                }

                return messages;
            }
            else
                return new string[0];
        }
Пример #14
0
        private static void DebugCallback(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            string debugMessage = Marshal.PtrToStringAnsi(message, length);

            Debug.WriteLine(String.Format("{0} {1} {2}", severity, type, debugMessage));
        }
Пример #15
0
        /// <exception cref="GetValueException"><c>GetValueException</c>.</exception>
        private static void MethodInvokeStarter(Eval eval, DebugMethodInfo method, Value thisValue, Value[] args)
        {
            List <ICorDebugValue> corArgs = new List <ICorDebugValue>();

            args = args ?? new Value[0];
            if (args.Length != method.ParameterCount)
            {
                throw new GetValueException("Invalid parameter count");
            }
            if (!method.IsStatic)
            {
                if (thisValue == null)
                {
                    throw new GetValueException("'this' is null");
                }
                if (thisValue.IsNull)
                {
                    throw new GetValueException("Null reference");
                }
                // if (!(thisValue.IsObject)) // eg Can evaluate on array
                if (!method.DeclaringType.IsInstanceOfType(thisValue))
                {
                    throw new GetValueException(
                              "Can not evaluate because the object is not of proper type.  " +
                              "Expected: " + method.DeclaringType.FullName + "  Seen: " + thisValue.Type.FullName
                              );
                }
                corArgs.Add(thisValue.CorValue);
            }
            for (int i = 0; i < args.Length; i++)
            {
                Value     arg       = args[i];
                DebugType paramType = (DebugType)method.GetParameters()[i].ParameterType;
                if (!arg.Type.CanImplicitelyConvertTo(paramType))
                {
                    throw new GetValueException("Inncorrect parameter type");
                }
                // Implicitely convert to correct primitve type
                if (paramType.IsPrimitive && args[i].Type != paramType)
                {
                    object oldPrimVal = arg.PrimitiveValue;
                    object newPrimVal = Convert.ChangeType(oldPrimVal, paramType.PrimitiveType);
                    arg = CreateValue(method.AppDomain, newPrimVal);
                }
                // It is importatnt to pass the parameted in the correct form (boxed/unboxed)
                if (paramType.IsValueType)
                {
                    corArgs.Add(arg.CorGenericValue);
                }
                else
                {
                    if (args[i].Type.IsValueType)
                    {
                        corArgs.Add(arg.Box().CorValue);
                    }
                    else
                    {
                        corArgs.Add(arg.CorValue);
                    }
                }
            }

            ICorDebugType[] genericArgs = ((DebugType)method.DeclaringType).GenericArgumentsAsCorDebugType;
            eval.CorEval2.CallParameterizedFunction(
                method.CorFunction,
                (uint)genericArgs.Length, genericArgs,
                (uint)corArgs.Count, corArgs.ToArray()
                );
        }
Пример #16
0
        void debugOutput(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            string msg = Marshal.PtrToStringAnsi(message, length);

            Info.print("GL Debug Message: {0} \n\tSource:{1} \n\tType:{2} \n\tSeverity:{3} \n\tID:{4} ", msg, source, type, severity, id);
        }
Пример #17
0
		public TypedValue(Value value, DebugType type)
		{
			this.value = value;
			this.type = type;
		}
Пример #18
0
        void DebugMessage(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            var msg = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(message, length);

            Console.WriteLine(string.Format("{0} {1} {2}", severity, type, msg));
        }
Пример #19
0
 public bool IsVisualizerAvailable(DebugType type)
 {
     return(type.FullName == typeof(string).FullName);
 }
Пример #20
0
        /// <summary>
        /// Outputs the Debug-Messages to the system-console.
        /// </summary>
        /// <param name="pMessage">Debug-Message</param>
        /// <param name="pParameters">Output-Parameters [Not required for ToConsole-Method]</param>
        public static void ToConsole(string pMessage, DebugType pDebugType, params object[] pParameters)
        {
            Console.Write($"({Thread.CurrentThread.ManagedThreadId.ToString("D3")})");

            switch (pDebugType)
            {
            case DebugType.Info:
                Console.ForegroundColor = ConsoleColor.Green;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[ ~INFO ] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine(pMessage);
                break;

            case DebugType.Warning:
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[WARNING] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine(pMessage);
                break;

            case DebugType.Cronjob:
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[CRONJOB] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine(pMessage);
                break;

            case DebugType.Confirmation:
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[CONFIRM] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine(pMessage);
                break;

            case DebugType.Error:
                Console.ForegroundColor = ConsoleColor.Red;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[ ERROR ] ");

                Console.WriteLine(pMessage);
                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                break;

            case DebugType.Fatal:
                Console.ForegroundColor = ConsoleColor.Black;
                Console.BackgroundColor = ConsoleColor.DarkRed;

                Console.Write("[ FATAL ] ");

                Console.WriteLine(pMessage);
                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                break;

            case DebugType.Remote:
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[~REMOTE] ");

                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine(pMessage);

                break;

            case DebugType.Exception:
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write("[EXCEPT.] ");

                Console.WriteLine(pMessage);
                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.Black;

                break;
            }
        }
Пример #21
0
#pragma warning disable IDE0060 // unused arguments

        // ╔════╤════════════════════════════════════════════════════════╗
        // ║ 4d │ M E T H O D S   ( P U B L I C )                        ║
        // ╟────┴────────────────────────────────────────────────────────╢
        // ║ N O N - S T A T I C   &   S T A T I C                       ║
        // ╚═════════════════════════════════════════════════════════════╝

        #region ═╣ M E T H O D S   ( P U B L I C ) ╠═

        /// <summary>
        /// Disables all debug-outputs.
        /// </summary>
        /// <param name="pMessage"></param>
        /// <param name="pParameters"></param>
        public static void Disable(string pMessage, DebugType pDebugType, params object[] pParameters)
        {
        }
Пример #22
0
 /// <summary>
 /// Outputs the Debug-Messages to a given WinForms-Textbox.
 /// </summary>
 /// <param name="pMessage">Debug-Message</param>
 /// <param name="pParameters">Output-Parameters - First parameter: the target textbox-instance</param>
 public static void ToTextbox(string pMessage, DebugType pDebugType, params object[] pParameters)
 {
     (pParameters[0] as TextBox).Text += pMessage + "\r\n";
     (pParameters[0] as TextBox).ScrollToCaret();
 }
Пример #23
0
		public static Value NewObjectNoConstructor(DebugType debugType)
		{
			return AsyncNewObjectNoConstructor(debugType).WaitForResult();
		}
Пример #24
0
 static M SetStaticType <M>(this M expr, DebugType type) where M : AstNode
 {
     expr.AddAnnotation(type);
     return(expr);
 }
Пример #25
0
 private bool DoMatchForLogType(DebugType type)
 {
     switch (Oper)
     {
         case FilterOperator.Equal:
             return ((DebugType)Value) == type;
         case FilterOperator.NotEqual:
             return ((DebugType)Value) != type;
         default:
             return false;
     }
 }
Пример #26
0
        public override bool Execute(out IList <Exception> thrownExceptions)
        {
            thrownExceptions = null;
            LoggingHelper.LogMessage(Normal, $"{new string(' ', 0)}Compiling Xaml, assembly: {Assembly}");
            var  skipassembly = !CompileByDefault;
            bool success      = true;

            if (!File.Exists(Assembly))
            {
                LoggingHelper.LogMessage(Normal, $"{new string(' ', 2)}Assembly file not found. Skipping XamlC.");
                return(true);
            }

            var resolver = DefaultAssemblyResolver ?? new XamlCAssemblyResolver();

            if (resolver is XamlCAssemblyResolver xamlCResolver)
            {
                if (!string.IsNullOrEmpty(DependencyPaths))
                {
                    foreach (var dep in DependencyPaths.Split(';').Distinct())
                    {
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {dep}");
                        xamlCResolver.AddSearchDirectory(dep);
                    }
                }

                if (!string.IsNullOrEmpty(ReferencePath))
                {
                    var paths = ReferencePath.Replace("//", "/").Split(';').Distinct();
                    foreach (var p in paths)
                    {
                        var searchpath = Path.GetDirectoryName(p);
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {searchpath}");
                        xamlCResolver.AddSearchDirectory(searchpath);
                    }
                }
            }
            else
            {
                LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Ignoring dependency and reference paths due to an unsupported resolver");
            }

            var debug = DebugSymbols || (!string.IsNullOrEmpty(DebugType) && DebugType.ToLowerInvariant() != "none");

            var readerParameters = new ReaderParameters {
                AssemblyResolver = resolver,
                ReadWrite        = !ReadOnly,
                ReadSymbols      = debug,
            };

            using (var assemblyDefinition = AssemblyDefinition.ReadAssembly(Path.GetFullPath(Assembly), readerParameters)) {
                CustomAttribute xamlcAttr;
                if (assemblyDefinition.HasCustomAttributes &&
                    (xamlcAttr =
                         assemblyDefinition.CustomAttributes.FirstOrDefault(
                             ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
                {
                    var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
                    if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
                    {
                        skipassembly = true;
                    }
                    if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
                    {
                        skipassembly = false;
                    }
                }

                foreach (var module in assemblyDefinition.Modules)
                {
                    var skipmodule = skipassembly;
                    if (module.HasCustomAttributes &&
                        (xamlcAttr =
                             module.CustomAttributes.FirstOrDefault(
                                 ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
                    {
                        var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
                        if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
                        {
                            skipmodule = true;
                        }
                        if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
                        {
                            skipmodule = false;
                        }
                    }

                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Module: {module.Name}");
                    var resourcesToPrune = new List <EmbeddedResource>();
                    foreach (var resource in module.Resources.OfType <EmbeddedResource>())
                    {
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Resource: {resource.Name}");
                        string classname;
                        if (!resource.IsXaml(module, out classname))
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}skipped.");
                            continue;
                        }
                        TypeDefinition typeDef = module.GetType(classname);
                        if (typeDef == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no type found... skipped.");
                            continue;
                        }
                        var skiptype = skipmodule;
                        if (typeDef.HasCustomAttributes &&
                            (xamlcAttr =
                                 typeDef.CustomAttributes.FirstOrDefault(
                                     ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
                        {
                            var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
                            if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
                            {
                                skiptype = true;
                            }
                            if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
                            {
                                skiptype = false;
                            }
                        }

                        if (Type != null)
                        {
                            skiptype = !(Type == classname);
                        }

                        if (skiptype && !ForceCompile)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}has XamlCompilationAttribute set to Skip and not Compile... skipped.");
                            continue;
                        }

                        var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
                        if (initComp == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no InitializeComponent found... skipped.");
                            continue;
                        }

                        CustomAttribute xamlFilePathAttr;
                        var             xamlFilePath = typeDef.HasCustomAttributes && (xamlFilePathAttr = typeDef.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlFilePathAttribute")) != null ?
                                                       (string)xamlFilePathAttr.ConstructorArguments[0].Value :
                                                       resource.Name;

                        var initCompRuntime = typeDef.Methods.FirstOrDefault(md => md.Name == "__InitComponentRuntime");
                        if (initCompRuntime != null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}__InitComponentRuntime already exists... not creating");
                        }
                        else
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Creating empty {typeDef.Name}.__InitComponentRuntime");
                            initCompRuntime = new MethodDefinition("__InitComponentRuntime", initComp.Attributes, initComp.ReturnType);
                            initCompRuntime.Body.InitLocals = true;
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Copying body of InitializeComponent to __InitComponentRuntime");
                            initCompRuntime.Body = new MethodBody(initCompRuntime);
                            var iCRIl = initCompRuntime.Body.GetILProcessor();
                            foreach (var instr in initComp.Body.Instructions)
                            {
                                iCRIl.Append(instr);
                            }
                            initComp.Body.Instructions.Clear();
                            initComp.Body.GetILProcessor().Emit(OpCodes.Ret);
                            initComp.Body.InitLocals = true;
                            typeDef.Methods.Add(initCompRuntime);
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                        }

                        LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Parsing Xaml");
                        var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
                        if (rootnode == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
                            continue;
                        }
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");

                        hasCompiledXamlResources = true;

                        LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing {0}.InitializeComponent ()");
                        Exception e;
                        if (!TryCoreCompile(initComp, initCompRuntime, rootnode, out e))
                        {
                            success = false;
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}failed.");
                            (thrownExceptions = thrownExceptions ?? new List <Exception>()).Add(e);
                            if (e is XamlParseException xpe)
                            {
                                LoggingHelper.LogError(null, null, null, xamlFilePath, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source);
                            }
                            else if (e is XmlException xe)
                            {
                                LoggingHelper.LogError(null, null, null, xamlFilePath, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
                            }
                            else
                            {
                                LoggingHelper.LogError(null, null, null, xamlFilePath, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
                            }
                            LoggingHelper.LogMessage(Low, e.StackTrace);
                            continue;
                        }
                        if (Type != null)
                        {
                            InitCompForType = initComp;
                        }

                        LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");

                        if (OptimizeIL)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Optimizing IL");
                            initComp.Body.Optimize();
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                        }

#pragma warning disable 0618
                        if (OutputGeneratedILAsCode)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Decompiling option has been removed. Use a 3rd party decompiler to admire the beauty of the IL generated");
                        }
#pragma warning restore 0618
                        resourcesToPrune.Add(resource);
                    }
                    if (hasCompiledXamlResources)
                    {
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Changing the module MVID");
                        module.Mvid = Guid.NewGuid();
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}done.");
                    }
                    if (!KeepXamlResources)
                    {
                        if (resourcesToPrune.Any())
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Removing compiled xaml resources");
                        }
                        foreach (var resource in resourcesToPrune)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Removing {resource.Name}");
                            module.Resources.Remove(resource);
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                        }
                    }
                }

                if (!hasCompiledXamlResources)
                {
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}No compiled resources. Skipping writing assembly.");
                    return(success);
                }

                if (ReadOnly)
                {
                    return(success);
                }

                LoggingHelper.LogMessage(Low, $"{new string(' ', 0)}Writing the assembly");
                try {
                    assemblyDefinition.Write(new WriterParameters {
                        WriteSymbols = debug,
                    });
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}done.");
                } catch (Exception e) {
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}failed.");
                    LoggingHelper.LogErrorFromException(e);
                    (thrownExceptions = thrownExceptions ?? new List <Exception>()).Add(e);
                    LoggingHelper.LogMessage(Low, e.StackTrace);
                    success = false;
                }
            }
            return(success);
        }
Пример #27
0
 public static Value NewArray(DebugType type, uint length, uint?lowerBound)
 {
     return(AsyncNewArray(type, length, lowerBound).WaitForResult());
 }
Пример #28
0
        public static void HandleDebugGLMessage(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            StringBuilder errorString = new StringBuilder();

            switch (source)
            {
            case DebugSource.DebugSourceApi: {
                errorString.Append("[API]");
                break;
            }

            case DebugSource.DebugSourceApplication: {
                errorString.Append("[APP]");
                break;
            }

            case DebugSource.DebugSourceOther: {
                errorString.Append("[Other]");
                break;
            }

            case DebugSource.DebugSourceShaderCompiler: {
                errorString.Append("[Shader]");
                break;
            }

            case DebugSource.DebugSourceThirdParty: {
                errorString.Append("[3RD]");
                break;
            }

            case DebugSource.DebugSourceWindowSystem: {
                errorString.Append("[Window]");
                break;
            }
            }

            switch (type)
            {
            case DebugType.DebugTypeDeprecatedBehavior: {
                errorString.Append("[DEPRECATED]");
                break;
            }

            case DebugType.DebugTypeError: {
                errorString.Append("[ERROR]");
                break;
            }

            case DebugType.DebugTypeMarker: {
                errorString.Append("[MARKER]");
                break;
            }

            case DebugType.DebugTypeOther: {
                errorString.Append("[OTHER]");
                break;
            }

            case DebugType.DebugTypePerformance: {
                errorString.Append("[PERF]");
                break;
            }

            case DebugType.DebugTypePopGroup: {
                errorString.Append("[POPGROUP]");
                break;
            }

            case DebugType.DebugTypePortability: {
                errorString.Append("[PORTABILITY]");
                break;
            }

            case DebugType.DebugTypePushGroup: {
                errorString.Append("[PUSHGROUP]");
                break;
            }

            case DebugType.DebugTypeUndefinedBehavior: {
                errorString.Append("[BEHAVIOR]");
                break;
            }
            }

            errorString.Append(Marshal.PtrToStringAnsi(message));

            switch (severity)
            {
            case DebugSeverity.DebugSeverityHigh: {
                Logger.Error(errorString.ToString());
                //if (type == DebugType.DebugTypeError) throw new InvalidOperationException("ARB_debug_output found an error.");
                break;
            }

            case DebugSeverity.DebugSeverityMedium: {
                Logger.Warning(errorString.ToString());
                break;
            }

            case DebugSeverity.DebugSeverityLow: {
                errorString.Insert(0, "[Low]");
                Logger.Info(errorString.ToString());
                break;
            }

            case DebugSeverity.DebugSeverityNotification: {
                errorString.Insert(0, "[Notice]");
                Logger.Info(errorString.ToString());
                break;
            }

            default: {
                break;
            }
            }
        }
Пример #29
0
 public static void LogWarning(DebugType debugType, object message, params object[] arguments)
 {
     if(EnumExtensions.IsFlagSet(DebugType.Warning, debugType)) {
         Debug.LogWarning(string.Format(message.ToString(), arguments));
     }
 }
Пример #30
0
 public Operation SetDebug(string file, int line, int col, DebugType type, string data)
 {
     this.Debug = string.Format("{0}:{1}.{2}:{3}:{4}", file, line, col, type, data);
     return this;
 }
Пример #31
0
 public void SetDebugCallback(DebugType theFunc)
 {
     debugFunc = theFunc;
 }
Пример #32
0
        public static IEnumerable <TreeNode> LazyGetChildNodesOfObject(Expression targetObject, DebugType shownType)
        {
            MemberInfo[] publicStatic      = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] publicInstance    = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicStatic   = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicInstance = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            DebugType baseType = (DebugType)shownType.BaseType;

            if (baseType != null)
            {
                yield return(new TreeNode(
                                 ImageCache.GetIcon(TypeIcon.Class, BackgroundType.DebuggerToolTip),
                                 "BaseClass",
                                 baseType.Name,
                                 baseType.FullName,
                                 baseType.FullName == "System.Object" ? null : Utils.LazyGetChildNodesOfObject(targetObject, baseType)
                                 ));
            }

            if (nonPublicInstance.Length > 0)
            {
                yield return(new TreeNode(
                                 null,
                                 "NonPublicMembers",
                                 string.Empty,
                                 string.Empty,
                                 Utils.LazyGetMembersOfObject(targetObject, nonPublicInstance)
                                 ));
            }

            if (publicStatic.Length > 0 || nonPublicStatic.Length > 0)
            {
                IEnumerable <TreeNode> childs = Utils.LazyGetMembersOfObject(targetObject, publicStatic);
                if (nonPublicStatic.Length > 0)
                {
                    TreeNode nonPublicStaticNode = new TreeNode(
                        null,
                        "NonPublicStaticMembers",
                        string.Empty,
                        string.Empty,
                        Utils.LazyGetMembersOfObject(targetObject, nonPublicStatic)
                        );
                    childs = Utils.PrependNode(nonPublicStaticNode, childs);
                }
                yield return(new TreeNode(
                                 null,
                                 "StaticMembers",
                                 string.Empty,
                                 string.Empty,
                                 childs
                                 ));
            }

            DebugType iListType = (DebugType)shownType.GetInterface(typeof(IList).FullName);

            if (iListType != null)
            {
                yield return(new IListNode(targetObject));
            }
            else
            {
                DebugType iEnumerableType, itemType;
                if (shownType.ResolveIEnumerableImplementation(out iEnumerableType, out itemType))
                {
                    yield return(new IEnumerableNode(targetObject, itemType));
                }
            }

            foreach (TreeNode node in LazyGetMembersOfObject(targetObject, publicInstance))
            {
                yield return(node);
            }
        }
Пример #33
0
 protected void OnDebugFps(bool enabled)
 {
     _debugType = enabled ? DebugType.Fps : DebugType.None;
 }
Пример #34
0
		public static Eval AsyncNewArray(DebugType type, uint length, uint? lowerBound)
		{
			lowerBound = lowerBound ?? 0;
			return new Eval(
				type.AppDomain,
				"New array: " + type + "[" + length + "]",
				delegate(Eval eval) {
					// Multi-dimensional arrays not supported in .NET 2.0
					eval.CorEval2.NewParameterizedArray(type.CorType, 1, new uint[] { length }, new uint[] { lowerBound.Value });
				}
			);
		}
Пример #35
0
 public static void D(DebugType type, string msg)
 {
     D(String.Format("<color=#00ffff>[{0}]</color>{1}", type.ToString(), msg));
 }
Пример #36
0
        public override bool Execute(out IList <Exception> thrownExceptions)
        {
            thrownExceptions = null;
            LoggingHelper.LogMessage(Normal, $"{new string(' ', 0)}Preparing debug code for xamlc, assembly: {Assembly}");

            var resolver = new DefaultAssemblyResolver();

            if (!string.IsNullOrEmpty(DependencyPaths))
            {
                foreach (var dep in DependencyPaths.Split(';'))
                {
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {dep}");
                    resolver.AddSearchDirectory(dep);
                }
            }
            if (!string.IsNullOrEmpty(ReferencePath))
            {
                var paths = ReferencePath.Replace("//", "/").Split(';');
                foreach (var p in paths)
                {
                    var searchpath = Path.GetDirectoryName(p);
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Adding searchpath {searchpath}");
                    resolver.AddSearchDirectory(searchpath);
                }
            }

            var debug = DebugSymbols || (!string.IsNullOrEmpty(DebugType) && DebugType.ToLowerInvariant() != "none");

            using (var assemblyDefinition = AssemblyDefinition.ReadAssembly(Assembly, new ReaderParameters {
                ReadWrite = true,
                ReadSymbols = debug,
                AssemblyResolver = resolver
            })) {
                foreach (var module in assemblyDefinition.Modules)
                {
                    LoggingHelper.LogMessage(Low, $"{new string(' ', 2)}Module: {module.Name}");
                    foreach (var resource in module.Resources.OfType <EmbeddedResource>())
                    {
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 4)}Resource: {resource.Name}");
                        if (!resource.IsXaml(module, out var classname))
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}skipped.");
                            continue;
                        }
                        TypeDefinition typeDef = module.GetType(classname);
                        if (typeDef == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no type found... skipped.");
                            continue;
                        }

                        var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
                        if (initComp == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}no InitializeComponent found... skipped.");
                            continue;
                        }
                        var initCompRuntime = typeDef.Methods.FirstOrDefault(md => md.Name == "__InitComponentRuntime");
                        if (initCompRuntime == null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Creating empty {typeDef.Name}.__InitComponentRuntime");
                            initCompRuntime = new MethodDefinition("__InitComponentRuntime", initComp.Attributes, initComp.ReturnType);
                            initCompRuntime.Body.InitLocals = true;
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Copying body of InitializeComponent to __InitComponentRuntime");
                            initCompRuntime.Body = new MethodBody(initCompRuntime);
                            var iCRIl = initCompRuntime.Body.GetILProcessor();
                            foreach (var instr in initComp.Body.Instructions)
                            {
                                iCRIl.Append(instr);
                            }
                            initComp.Body.Instructions.Clear();
                            initComp.Body.GetILProcessor().Emit(OpCodes.Ret);
                            typeDef.Methods.Add(initCompRuntime);
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                        }

//						IL_0000:  ldarg.0
//						IL_0001:  callvirt instance void class [Xamarin.Forms.Core]Xamarin.Forms.ContentPage::'.ctor'()
//
//						IL_0006:  nop
//						IL_0007:  ldarg.1
//						IL_0008:  brfalse IL_0018
//
//						IL_000d:  ldarg.0
//						IL_000e:  callvirt instance void class Xamarin.Forms.Xaml.XamlcTests.MyPage::InitializeComponent()
//						IL_0013:  br IL_001e
//
//						IL_0018:  ldarg.0
//						IL_0019:  callvirt instance void class Xamarin.Forms.Xaml.XamlcTests.MyPage::__InitComponentRuntime()
//						IL_001e:  ret

                        var altCtor = typeDef.Methods.FirstOrDefault(md => md.IsConstructor &&
                                                                     md.Parameters.Count == 1 &&
                                                                     md.Parameters[0].ParameterType == module.TypeSystem.Boolean);
                        if (altCtor != null)
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Replacing body of {typeDef.Name}.{typeDef.Name} (bool {altCtor.Parameters[0].Name})");
                        }
                        else
                        {
                            LoggingHelper.LogMessage(Low, $"{new string(' ', 6)}Adding {typeDef.Name}.{typeDef.Name} (bool useCompiledXaml)");
                            altCtor = new MethodDefinition(".ctor",
                                                           MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                                           MethodAttributes.RTSpecialName, module.TypeSystem.Void);
                            altCtor.Parameters.Add(new ParameterDefinition("useCompiledXaml", ParameterAttributes.None,
                                                                           module.TypeSystem.Boolean));
                        }

                        var body = new MethodBody(altCtor)
                        {
                            InitLocals = true
                        };
                        var il  = body.GetILProcessor();
                        var br2 = Instruction.Create(OpCodes.Ldarg_0);
                        var ret = Instruction.Create(OpCodes.Ret);
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Callvirt,
                                module.ImportReference(typeDef.BaseType.Resolve().GetConstructors().First(c => c.HasParameters == false)));

                        il.Emit(OpCodes.Nop);
                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Brfalse, br2);

                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Callvirt, initComp);
                        il.Emit(OpCodes.Br, ret);

                        il.Append(br2);
                        il.Emit(OpCodes.Callvirt, initCompRuntime);
                        il.Append(ret);

                        altCtor.Body = body;
                        if (!typeDef.Methods.Contains(altCtor))
                        {
                            typeDef.Methods.Add(altCtor);
                        }
                        LoggingHelper.LogMessage(Low, $"{new string(' ', 8)}done.");
                    }
                }
                LoggingHelper.LogMessage(Normal, $"{new string(' ', 0)}Writing the assembly.");
                assemblyDefinition.Write(new WriterParameters {
                    WriteSymbols = debug
                });
            }
            LoggingHelper.LogMessage(Normal, $"{new string(' ', 2)}done.");

            return(true);
        }
Пример #37
0
        void EvaluateExpression()
        {
            evaluated = true;

            Value val;

            try {
                var process = WindowsDebugger.DebuggedProcess;
                if (process == null)
                {
                    return;
                }
                StackFrame frame = process.GetCurrentExecutingFrame();
                if (frame == null)
                {
                    return;
                }
                var    debugger = (WindowsDebugger)DebuggerService.CurrentDebugger;
                object data     = debugger.debuggerDecompilerService.GetLocalVariableIndex(frame.MethodInfo.DeclaringType.MetadataToken,
                                                                                           frame.MethodInfo.MetadataToken,
                                                                                           Name);

                if (expression is MemberReferenceExpression)
                {
                    var memberExpression = (MemberReferenceExpression)expression;
                    memberExpression.TargetObject.UserData = data;
                }
                else
                {
                    expression.UserData = data;
                }
                // evaluate expression
                val = expression.Evaluate(process);
            } catch (GetValueException e) {
                error     = e;
                this.Text = e.Message;
                return;
            }

            this.canSetText = val.Type.IsPrimitive;

            this.expressionType = val.Type;
            this.Type           = val.Type.Name;
            this.valueIsNull    = val.IsNull;

            // Note that these return enumerators so they are lazy-evaluated
            if (val.IsNull)
            {
            }
            else if (val.Type.IsPrimitive || val.Type.FullName == typeof(string).FullName)                 // Must be before IsClass
            {
            }
            else if (val.Type.IsArray)                 // Must be before IsClass
            {
                if (val.ArrayLength > 0)
                {
                    this.childNodes = Utils.LazyGetChildNodesOfArray(this, this.Expression, val.ArrayDimensions);
                }
            }
            else if (val.Type.IsClass || val.Type.IsValueType)
            {
                if (val.Type.FullNameWithoutGenericArguments == typeof(List <>).FullName)
                {
                    if ((int)val.GetMemberValue("_size").PrimitiveValue > 0)
                    {
                        this.childNodes = Utils.LazyGetItemsOfIList(this, this.expression);
                    }
                }
                else
                {
                    this.childNodes = Utils.LazyGetChildNodesOfObject(this, this.Expression, val.Type);
                }
            }
            else if (val.Type.IsPointer)
            {
                Value deRef = val.Dereference();
                if (deRef != null)
                {
                    this.childNodes = new ExpressionNode [] { new ExpressionNode(this, this.IconImage, "*" + this.Name, this.Expression.AppendDereference()) };
                }
            }

            if (DebuggingOptions.Instance.ICorDebugVisualizerEnabled)
            {
                TreeNode info = ICorDebug.GetDebugInfoRoot(val.AppDomain, val.CorValue);
                this.childNodes = Utils.PrependNode(info, this.ChildNodes);
            }

            // Do last since it may expire the object
            if (val.Type.IsInteger)
            {
                fullText = FormatInteger(val.PrimitiveValue);
            }
            else if (val.Type.IsPointer)
            {
                fullText = String.Format("0x{0:X}", val.PointerAddress);
            }
            else if ((val.Type.FullName == typeof(string).FullName ||
                      val.Type.FullName == typeof(char).FullName) && !val.IsNull)
            {
                try {
                    fullText = '"' + Escape(val.InvokeToString()) + '"';
                } catch (GetValueException e) {
                    error    = e;
                    fullText = e.Message;
                    return;
                }
            }
            else if ((val.Type.IsClass || val.Type.IsValueType) && !val.IsNull)
            {
                try {
                    fullText = val.InvokeToString();
                } catch (GetValueException e) {
                    error    = e;
                    fullText = e.Message;
                    return;
                }
            }
            else
            {
                fullText = val.AsString();
            }

            this.Text = (fullText.Length > 256) ? fullText.Substring(0, 256) + "..." : fullText;
        }
Пример #38
0
        private void DebugMessageCallback(DebugSource source, DebugType type, int id, DebugSeverity severity,
                                          int length, IntPtr message, IntPtr userParam)
        {
            var contents = $"{source}: " + Marshal.PtrToStringAnsi(message, length);

            var category = "ogl.debug";

            switch (type)
            {
            case DebugType.DebugTypePerformance:
                category += ".performance";
                break;

            case DebugType.DebugTypeOther:
                category += ".other";
                break;

            case DebugType.DebugTypeError:
                category += ".error";
                break;

            case DebugType.DebugTypeDeprecatedBehavior:
                category += ".deprecated";
                break;

            case DebugType.DebugTypeUndefinedBehavior:
                category += ".ub";
                break;

            case DebugType.DebugTypePortability:
                category += ".portability";
                break;

            case DebugType.DebugTypeMarker:
            case DebugType.DebugTypePushGroup:
            case DebugType.DebugTypePopGroup:
                // These are inserted by our own code so I imagine they're not necessary to log?
                return;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            var sawmill = _logManager.GetSawmill(category);

            switch (severity)
            {
            case DebugSeverity.DontCare:
                sawmill.Info(contents);
                break;

            case DebugSeverity.DebugSeverityNotification:
                sawmill.Info(contents);
                break;

            case DebugSeverity.DebugSeverityHigh:
                sawmill.Error(contents);
                break;

            case DebugSeverity.DebugSeverityMedium:
                sawmill.Error(contents);
                break;

            case DebugSeverity.DebugSeverityLow:
                sawmill.Warning(contents);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(severity), severity, null);
            }
        }
Пример #39
0
		public static Value NewArray(DebugType type, uint length, uint? lowerBound)
		{
			return AsyncNewArray(type, length, lowerBound).WaitForResult();
		}
Пример #40
0
 public abstract void DebugMessageControl([Flow(FlowDirection.In)] DebugSource source, [Flow(FlowDirection.In)] DebugType type, [Flow(FlowDirection.In)] DebugSeverity severity, [Flow(FlowDirection.In)] uint count, [Flow(FlowDirection.In)] Span <uint> ids, [Flow(FlowDirection.In)] bool enabled);
Пример #41
0
		public static Eval AsyncNewObjectNoConstructor(DebugType debugType)
		{
			return new Eval(
				debugType.AppDomain,
				"New object: " + debugType.FullName,
				delegate(Eval eval) {
					eval.CorEval2.NewParameterizedObjectNoConstructor(debugType.CorType.GetClass(), (uint)debugType.GetGenericArguments().Length, debugType.GenericArgumentsAsCorDebugType);
				}
			);
		}
Пример #42
0
 public abstract void DebugMessageInsert([Flow(FlowDirection.In)] DebugSource source, [Flow(FlowDirection.In)] DebugType type, [Flow(FlowDirection.In)] uint id, [Flow(FlowDirection.In)] DebugSeverity severity, [Flow(FlowDirection.In)] uint length, [Flow(FlowDirection.In)] string buf);
Пример #43
0
 public static Value NewObjectNoConstructor(DebugType debugType)
 {
     return(AsyncNewObjectNoConstructor(debugType).WaitForResult());
 }
Пример #44
0
        private static void DebugCallback(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            string debugMessage = Marshal.PtrToStringAnsi(message, length);

            Debug.WriteLine($"{severity} {type} {debugMessage}");
        }
Пример #45
0
		public static Eval AsyncNewObjectNoConstructor(DebugType debugType)
		{
			return CreateEval(
				debugType.Process,
				"New object: " + debugType.FullName,
				delegate(Eval eval) {
					eval.CorEval.CastTo<ICorDebugEval2>().NewParameterizedObjectNoConstructor(debugType.CorType.Class, (uint)debugType.GenericArguments.Count, debugType.GenericArgumentsAsCorDebugType);
				}
			);
		}
Пример #46
0
        /// <summary>
        /// Retrives a number of messages from message log.
        /// How many retrives is determined by Math.Min([all arrays]) and availible messages.
        /// </summary>
        /// <param name="sources"></param>
        /// <param name="types"></param>
        /// <param name="ids"></param>
        /// <param name="severities"></param>
        /// <param name="lengths"></param>
        /// <param name="messageLog">A single preallocated stringbuilder with enough capacity to contain all the messages?</param>
        /// <returns></returns>
        public static uint GetDebugMessageLogARB(DebugSource[] sources, DebugType[] types, uint[] ids, DebugSeverity[] severities, int[] lengths, StringBuilder messageLog)
        {
            var count = Math.Min(sources.Length, Math.Min(types.Length, Math.Min(ids.Length, Math.Min(severities.Length, lengths.Length))));

            return Delegates.glGetDebugMessageLogARB((uint)count, messageLog.Capacity, ref sources[0], ref types[0], ref ids[0], ref severities[0], ref lengths[0], messageLog);
        }
Пример #47
0
		TypedValue EvaluateAs(INode expression, DebugType type)
		{
			TypedValue val = Evaluate(expression);
			if (val.Type == type)
				return val;
			if (!val.Type.CanImplicitelyConvertTo(type))
				throw new EvaluateException(expression, "Can not implicitely cast {0} to {1}", val.Type.FullName, type.FullName);
			if (type.IsPrimitive) {
				object oldVal = val.PrimitiveValue;
				object newVal;
				try {
					newVal = Convert.ChangeType(oldVal, type.PrimitiveType);
				} catch (InvalidCastException) {
					throw new EvaluateException(expression, "Can not cast {0} to {1}", val.GetType().FullName, type.FullName);
				} catch (OverflowException) {
					throw new EvaluateException(expression, "Overflow");
				}
				return CreateValue(newVal);
			} else {
				return new TypedValue(val.Value, type);
			}
		}
Пример #48
0
 /// <summary>
 /// Insert a new debug message in the debug message log array.
 /// </summary>
 /// <param name="source">Source of inserted message.</param>
 /// <param name="type">type of inserted message.</param>
 /// <param name="id">id of inserted message. Userid has own range of ids.</param>
 /// <param name="severity">Severity of inserted message.</param>
 /// <param name="Text">The text of inserted message.</param>
 public static void DebugMessageInsertARB(DebugSource source, DebugType type, uint id, DebugSeverity severity, string Text)
 {
     Delegates.glDebugMessageInsertARB(source, type, id, severity, Text.Length, Text);
 }
        /// <summary>
        /// Bind properties.
        /// </summary>
        protected override void BindProperties()
        {
            if (this.ProjectMgr == null)
            {
                return;
            }
            string type = "";
            type= getCfgString(nameof(DebugType), DebugType.none.ToString());
            if (type != null && type.Length > 0)
            {
                try
                {
                    this.debugtype = (DebugType)Enum.Parse(typeof(DebugType), type);
                }
                catch (ArgumentException)
                {
                    this.debugtype = DebugType.none;
                }
            }
            debuggercommand = getCfgString(nameof(DebuggerCommand), "$(TargetPath)");
            debuggercommandarguments = getCfgString(nameof(DebuggerCommandArguments),  "");
            debuggerworkingdirectory= getCfgString(nameof(DebuggerWorkingDirectory),  "");
            debuggerattach= getCfgLogic(nameof(DebuggerAttach),  false);
            enableunmanageddebugging = getCfgLogic(nameof(EnableUnmanagedDebugging),  true);
            usevshostingprocess = getCfgLogic(nameof(UseVSHostingProcess),  true);

        }
Пример #50
0
 public static void LogError(DebugType debugType, object message)
 {
     if(EnumExtensions.IsFlagSet(DebugType.Error, debugType)) {
         Debug.LogError(message);
     }
 }
Пример #51
0
		public static IEnumerable<TreeNode> LazyGetChildNodesOfObject(Expression targetObject, DebugType shownType)
		{
			MemberInfo[] publicStatic      = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public    | BindingFlags.Static   | BindingFlags.DeclaredOnly);
			MemberInfo[] publicInstance    = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public    | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			MemberInfo[] nonPublicStatic   = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Static   | BindingFlags.DeclaredOnly);
			MemberInfo[] nonPublicInstance = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			
			DebugType baseType = (DebugType)shownType.BaseType;
			if (baseType != null) {
				yield return new TreeNode(
					ImageService.GetImage("Icons.16x16.Class"),
					"BaseClass",
					baseType.Name,
					baseType.FullName,
					baseType.FullName == "System.Object" ? null : Utils.LazyGetChildNodesOfObject(targetObject, baseType)
				);
			}
			
			if (nonPublicInstance.Length > 0) {
				yield return new TreeNode(
					null,
					"NonPublicMembers",
					string.Empty,
					string.Empty,
					Utils.LazyGetMembersOfObject(targetObject, nonPublicInstance)
				);
			}
			
			if (publicStatic.Length > 0 || nonPublicStatic.Length > 0) {
				IEnumerable<TreeNode> childs = Utils.LazyGetMembersOfObject(targetObject, publicStatic);
				if (nonPublicStatic.Length > 0) {
					TreeNode nonPublicStaticNode = new TreeNode(
						null,
						"NonPublicStaticMembers",
						string.Empty,
						string.Empty,
						Utils.LazyGetMembersOfObject(targetObject, nonPublicStatic)
					);
					childs = Utils.PrependNode(nonPublicStaticNode, childs);
				}
				yield return new TreeNode(
					null,
					"StaticMembers",
					string.Empty,
					string.Empty,
					childs
				);
			}
			
			DebugType iListType = (DebugType)shownType.GetInterface(typeof(IList).FullName);
			if (iListType != null) {
				yield return new IListNode(targetObject);
			} else {
				DebugType iEnumerableType, itemType;
				if (shownType.ResolveIEnumerableImplementation(out iEnumerableType, out itemType)) {
					yield return new IEnumerableNode(targetObject, itemType);
				}
			}
			
			foreach(TreeNode node in LazyGetMembersOfObject(targetObject, publicInstance)) {
				yield return node;
			}
		}
Пример #52
0
 private void uDebugLogAdd(string _log, DebugType debugType = DebugType.INFO, [CallerMemberName] string caller = "")
 {
     Toolbox.uAddDebugLog(_log, debugType, caller);
 }
Пример #53
0
 /// <summary>
 /// Changes the properties of an array of debug message ids.
 /// This might be source, type, severity or just enable/disable them.
 /// Enables or Disables an array of Debug Messages ids
 /// </summary>
 /// <param name="source">Source of ids.</param>
 /// <param name="type">Type of ids</param>
 /// <param name="severity">Severity of ids.</param>
 /// <param name="ids">array of ids to change.</param>
 /// <param name="Enabled">Enables or disables the ids.</param>
 public static void DebugMessageControlARB(DebugSource source, DebugType type, DebugSeverity severity, uint[] ids, bool Enabled)
 {
     Delegates.glDebugMessageControlARB(source, type, severity, ids.Length, ref ids[0], Enabled);
 }
Пример #54
0
        public static List <TreeNode> GetDebugInfo(AppDomain appDomain, ICorDebugValue corValue)
        {
            List <TreeNode> items = new List <TreeNode>();

            if (corValue is ICorDebugValue)
            {
                InfoNode info = new InfoNode("ICorDebugValue", "");
                info.AddChild("Address", corValue.GetAddress().ToString("X8"));
                info.AddChild("Type", ((CorElementType)corValue.GetTheType()).ToString());
                info.AddChild("Size", corValue.GetSize().ToString());
                items.Add(info);
            }
            if (corValue is ICorDebugValue2)
            {
                InfoNode        info      = new InfoNode("ICorDebugValue2", "");
                ICorDebugValue2 corValue2 = (ICorDebugValue2)corValue;
                string          fullname;
                try {
                    fullname = DebugType.CreateFromCorType(appDomain, corValue2.GetExactType()).FullName;
                } catch (DebuggerException e) {
                    fullname = e.Message;
                }
                info.AddChild("ExactType", fullname);
                items.Add(info);
            }
            if (corValue is ICorDebugGenericValue)
            {
                InfoNode info = new InfoNode("ICorDebugGenericValue", "");
                try {
                    byte[] bytes = ((ICorDebugGenericValue)corValue).GetRawValue();
                    for (int i = 0; i < bytes.Length; i += 8)
                    {
                        string val = "";
                        for (int j = i; j < bytes.Length && j < i + 8; j++)
                        {
                            val += bytes[j].ToString("X2") + " ";
                        }
                        info.AddChild("Value" + i.ToString("X2"), val);
                    }
                } catch (System.ArgumentException) {
                    info.AddChild("Value", "N/A");
                }
                items.Add(info);
            }
            if (corValue is ICorDebugReferenceValue)
            {
                InfoNode info = new InfoNode("ICorDebugReferenceValue", "");
                ICorDebugReferenceValue refValue = (ICorDebugReferenceValue)corValue;
                info.AddChild("IsNull", (refValue.IsNull() != 0).ToString());
                if (refValue.IsNull() == 0)
                {
                    info.AddChild("Value", refValue.GetValue().ToString("X8"));
                    if (refValue.Dereference() != null)
                    {
                        info.AddChild("Dereference", "", GetDebugInfo(appDomain, refValue.Dereference()));
                    }
                    else
                    {
                        info.AddChild("Dereference", "N/A");
                    }
                }
                items.Add(info);
            }
            if (corValue is ICorDebugHeapValue)
            {
                InfoNode info = new InfoNode("ICorDebugHeapValue", "");
                items.Add(info);
            }
            if (corValue is ICorDebugHeapValue2)
            {
                InfoNode info = new InfoNode("ICorDebugHeapValue2", "");
                items.Add(info);
            }
            if (corValue is ICorDebugObjectValue)
            {
                InfoNode             info     = new InfoNode("ICorDebugObjectValue", "");
                ICorDebugObjectValue objValue = (ICorDebugObjectValue)corValue;
                info.AddChild("Class", objValue.GetClass().GetToken().ToString("X8"));
                info.AddChild("IsValueClass", (objValue.IsValueClass() != 0).ToString());
                items.Add(info);
            }
            if (corValue is ICorDebugObjectValue2)
            {
                InfoNode info = new InfoNode("ICorDebugObjectValue2", "");
                items.Add(info);
            }
            if (corValue is ICorDebugBoxValue)
            {
                InfoNode          info     = new InfoNode("ICorDebugBoxValue", "");
                ICorDebugBoxValue boxValue = (ICorDebugBoxValue)corValue;
                info.AddChild("Object", "", GetDebugInfo(appDomain, boxValue.GetObject()));
                items.Add(info);
            }
            if (corValue is ICorDebugStringValue)
            {
                InfoNode             info        = new InfoNode("ICorDebugStringValue", "");
                ICorDebugStringValue stringValue = (ICorDebugStringValue)corValue;
                info.AddChild("Length", stringValue.GetLength().ToString());
                info.AddChild("String", stringValue.GetString());
                items.Add(info);
            }
            if (corValue is ICorDebugArrayValue)
            {
                InfoNode info = new InfoNode("ICorDebugArrayValue", "");
                info.AddChild("…", "…");
                items.Add(info);
            }
            if (corValue is ICorDebugHandleValue)
            {
                InfoNode             info        = new InfoNode("ICorDebugHandleValue", "");
                ICorDebugHandleValue handleValue = (ICorDebugHandleValue)corValue;
                info.AddChild("HandleType", handleValue.GetHandleType().ToString());
                items.Add(info);
            }

            return(items);
        }
Пример #55
0
        void EvaluateExpression()
        {
            evaluated = true;

            Value val;
            try {
                var frame = WindowsDebugger.DebuggedProcess.SelectedThread.MostRecentStackFrame;
                var key = frame.MethodInfo.ToMethodKey();
                // get the target name
                int index = Name.IndexOf('.');
                string targetName = Name;
                if (index != -1) {
                    targetName = Name.Substring(0, index);
                }

                // get local variable index
                MemberMapping mapping;
                var textView = MainWindow.Instance.ActiveTextView;
                var cm = textView == null ? null : textView.CodeMappings;
                if (cm != null && cm.TryGetValue(key, out mapping)) {
                    var variable = mapping.LocalVariables == null ? null : mapping.LocalVariables.FirstOrDefault(v => v.Name == targetName);
                    if (variable != null && variable.OriginalVariable != null) {
                        if (expression is MemberReferenceExpression) {
                            var memberExpression = (MemberReferenceExpression)expression;
                            memberExpression.Target.AddAnnotation(new [] { variable.OriginalVariable.Index });
                        } else {
                            expression.AddAnnotation(new [] { variable.OriginalVariable.Index });
                        }
                    }
                }

                // evaluate expression
                val = expression.Evaluate(WindowsDebugger.DebuggedProcess);
            } catch (GetValueException e) {
                error = e;
                this.Text = e.Message;
                return;
            }

            this.canSetText = val.Type.IsPrimitive || val.Type.FullName == typeof(string).FullName;

            this.expressionType = val.Type;
            this.Type = val.Type.Name;
            this.valueIsNull = val.IsNull;

            // Note that these return enumerators so they are lazy-evaluated
            if (val.IsNull) {
            } else if (val.Type.IsPrimitive || val.Type.FullName == typeof(string).FullName) { // Must be before IsClass
            } else if (val.Type.IsArray) { // Must be before IsClass
                if (val.ArrayLength > 0)
                    this.ChildNodes = Utils.LazyGetChildNodesOfArray(this.Expression, val.ArrayDimensions);
            } else if (val.Type.IsClass || val.Type.IsValueType) {
                if (val.Type.FullNameWithoutGenericArguments == typeof(List<>).FullName) {
                    if ((int)val.GetMemberValue("_size").PrimitiveValue > 0)
                        this.ChildNodes = Utils.LazyGetItemsOfIList(this.expression);
                } else {
                    this.ChildNodes = Utils.LazyGetChildNodesOfObject(this.Expression, val.Type);
                }
            } else if (val.Type.IsPointer) {
                Value deRef = val.Dereference();
                if (deRef != null) {
                    this.ChildNodes = new ExpressionNode [] { new ExpressionNode(this.ImageSource, "*" + this.Name, this.Expression.AppendDereference()) };
                }
            }

            //			if (DebuggingOptions.Instance.ICorDebugVisualizerEnabled) {
            //				TreeNode info = ICorDebug.GetDebugInfoRoot(val.AppDomain, val.CorValue);
            //				this.ChildNodes = Utils.PrependNode(info, this.ChildNodes);
            //			}

            // Do last since it may expire the object
            if (val.Type.IsInteger) {
                fullText = FormatInteger(val.PrimitiveValue);
            } else if (val.Type.IsPointer) {
                fullText = String.Format("0x{0:X}", val.PointerAddress);
            } else if ((val.Type.FullName == typeof(string).FullName ||
                        val.Type.FullName == typeof(char).FullName) && !val.IsNull) {
                try {
                    fullText = '"' + Escape(val.InvokeToString()) + '"';
                } catch (GetValueException e) {
                    error = e;
                    fullText = e.Message;
                    return;
                }
            } else if ((val.Type.IsClass || val.Type.IsValueType) && !val.IsNull) {
                try {
                    fullText = val.InvokeToString();
                } catch (GetValueException e) {
                    error = e;
                    fullText = e.Message;
                    return;
                }
            } else {
                fullText = val.AsString();
            }

            this.Text = (fullText.Length > 256) ? fullText.Substring(0, 256) + "…" : fullText;
        }
Пример #56
0
        public static IEnumerable <TreeNode> LazyGetChildNodesOfObject(Expression targetObject, DebugType shownType)
        {
            MemberInfo[] publicStatic      = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] publicInstance    = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicStatic   = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicInstance = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            DebugType baseType = (DebugType)shownType.BaseType;

            if (baseType != null)
            {
                if (Variables.Langue == "en")
                {
                    yield return(new TreeNode(
                                     Properties.Resources._namespace,
                                     StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_BaseClass_EN),
                                     baseType.Name,
                                     baseType.FullName,
                                     baseType.FullName == "System.Object" ? null : Utils.LazyGetChildNodesOfObject(targetObject, baseType)
                                     ));
                }
                else
                {
                    yield return(new TreeNode(
                                     Properties.Resources._namespace,
                                     StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_BaseClass),
                                     baseType.Name,
                                     baseType.FullName,
                                     baseType.FullName == "System.Object" ? null : Utils.LazyGetChildNodesOfObject(targetObject, baseType)
                                     ));
                }
            }

            // if (nonPublicInstance.Length > 0) {
            //     if (Variables.Langue == "en")
            //     {
            //         yield return new TreeNode(
            //             null,
            //             StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_NonPublicMembers_EN),
            //             string.Empty,
            //             string.Empty,
            //             Utils.LazyGetMembersOfObject(targetObject, nonPublicInstance)
            //         );
            //     }
            //     else
            //     {
            //         yield return new TreeNode(
            //             null,
            //             StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_NonPublicMembers),
            //             string.Empty,
            //             string.Empty,
            //             Utils.LazyGetMembersOfObject(targetObject, nonPublicInstance)
            //         );
            //     }
            // }
            //
            // if (publicStatic.Length > 0 || nonPublicStatic.Length > 0) {
            //  IEnumerable<TreeNode> childs = Utils.LazyGetMembersOfObject(targetObject, publicStatic);
            //  if (nonPublicStatic.Length > 0) {
            //         if (Variables.Langue == "en")
            //         {
            //             TreeNode nonPublicStaticNode = new TreeNode(
            //                 null,
            //                 StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_NonPublicStaticMembers_EN),
            //                 string.Empty,
            //                 string.Empty,
            //                 Utils.LazyGetMembersOfObject(targetObject, nonPublicStatic)
            //             );
            //             childs = Utils.PrependNode(nonPublicStaticNode, childs);
            //         }
            //         else
            //         {
            //             TreeNode nonPublicStaticNode = new TreeNode(
            //                 null,
            //                 StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_NonPublicStaticMembers),
            //                 string.Empty,
            //                 string.Empty,
            //                 Utils.LazyGetMembersOfObject(targetObject, nonPublicStatic)
            //             );
            //             childs = Utils.PrependNode(nonPublicStaticNode, childs);
            //         }
            //  }
            //     if (Variables.Langue == "en")
            //     {
            //         yield return new TreeNode(
            //             null,
            //             StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_StaticMembers_EN),
            //             string.Empty,
            //             string.Empty,
            //             childs
            //         );
            //     }
            //     else
            //     {
            //         yield return new TreeNode(
            //             null,
            //             StringParser.Parse(VelerSoftware.SZC.Properties.Resources.MainWindow_Windows_Debug_LocalVariables_StaticMembers),
            //             string.Empty,
            //             string.Empty,
            //             childs
            //         );
            //     }
            // }

            DebugType iListType = (DebugType)shownType.GetInterface(typeof(IList).FullName);

            if (iListType != null)
            {
                yield return(new IListNode(targetObject));
            }
            else
            {
                DebugType iEnumerableType, itemType;
                if (shownType.ResolveIEnumerableImplementation(out iEnumerableType, out itemType))
                {
                    yield return(new IEnumerableNode(targetObject, itemType));
                }
            }

            foreach (TreeNode node in LazyGetMembersOfObject(targetObject, publicInstance))
            {
                yield return(node);
            }
        }
Пример #57
0
 public static void LogWarning(DebugType debugType, object message)
 {
     if(EnumExtensions.IsFlagSet(DebugType.Warning, debugType)) {
         Debug.LogWarning(message);
     }
 }
    private void ExpansionGUIWindow(int windowId)
    {
        GUI.DragWindow(new Rect(0, 0, 10000, 20));

        #region title
        GUILayout.BeginHorizontal();
        GUI.contentColor = _fpsColor;
        if (GUILayout.Button("FPS:" + _fps, GUILayout.Height(30)))
        {
            _expansion         = false;
            _windowRect.width  = 100;
            _windowRect.height = 60;
        }
        GUI.contentColor = (_debugType == DebugType.Console ? Color.white : Color.gray);
        if (GUILayout.Button("Console", GUILayout.Height(30)))
        {
            _debugType = DebugType.Console;
        }
        GUI.contentColor = (_debugType == DebugType.Memory ? Color.white : Color.gray);
        if (GUILayout.Button("Memory", GUILayout.Height(30)))
        {
            _debugType = DebugType.Memory;
        }
        GUI.contentColor = (_debugType == DebugType.System ? Color.white : Color.gray);
        if (GUILayout.Button("System", GUILayout.Height(30)))
        {
            _debugType = DebugType.System;
        }
        GUI.contentColor = (_debugType == DebugType.Screen ? Color.white : Color.gray);
        if (GUILayout.Button("Screen", GUILayout.Height(30)))
        {
            _debugType = DebugType.Screen;
        }
        GUI.contentColor = (_debugType == DebugType.Quality ? Color.white : Color.gray);
        if (GUILayout.Button("Quality", GUILayout.Height(30)))
        {
            _debugType = DebugType.Quality;
        }
        GUI.contentColor = (_debugType == DebugType.Environment ? Color.white : Color.gray);
        if (GUILayout.Button("Environment", GUILayout.Height(30)))
        {
            _debugType = DebugType.Environment;
        }
        GUI.contentColor = Color.white;
        GUILayout.EndHorizontal();
        #endregion

        #region console
        if (_debugType == DebugType.Console)
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Clear"))
            {
                _logInformations.Clear();
                _fatalLogCount   = 0;
                _warningLogCount = 0;
                _errorLogCount   = 0;
                _infoLogCount    = 0;
                _currentLogIndex = -1;
                _fpsColor        = Color.white;
            }
            GUI.contentColor = (_showInfoLog ? Color.white : Color.gray);
            _showInfoLog     = GUILayout.Toggle(_showInfoLog, "Info [" + _infoLogCount + "]");
            GUI.contentColor = (_showWarningLog ? Color.white : Color.gray);
            _showWarningLog  = GUILayout.Toggle(_showWarningLog, "Warning [" + _warningLogCount + "]");
            GUI.contentColor = (_showErrorLog ? Color.white : Color.gray);
            _showErrorLog    = GUILayout.Toggle(_showErrorLog, "Error [" + _errorLogCount + "]");
            GUI.contentColor = (_showFatalLog ? Color.white : Color.gray);
            _showFatalLog    = GUILayout.Toggle(_showFatalLog, "Fatal [" + _fatalLogCount + "]");
            GUI.contentColor = Color.white;
            GUILayout.EndHorizontal();

            _scrollLogView = GUILayout.BeginScrollView(_scrollLogView, "Box", GUILayout.Height(165));
            for (int i = 0; i < _logInformations.Count; i++)
            {
                bool  show  = false;
                Color color = Color.white;
                switch (_logInformations[i].type)
                {
                case "Fatal":
                    show  = _showFatalLog;
                    color = Color.red;
                    break;

                case "Error":
                    show  = _showErrorLog;
                    color = Color.red;
                    break;

                case "Info":
                    show  = _showInfoLog;
                    color = Color.white;
                    break;

                case "Warning":
                    show  = _showWarningLog;
                    color = Color.yellow;
                    break;

                default:
                    break;
                }

                if (show)
                {
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Toggle(_currentLogIndex == i, ""))
                    {
                        _currentLogIndex = i;
                    }
                    GUI.contentColor = color;
                    GUILayout.Label("[" + _logInformations[i].type + "] ");
                    GUILayout.Label("[" + _logInformations[i].time + "] ");
                    GUILayout.Label(_logInformations[i].message);
                    GUILayout.FlexibleSpace();
                    GUI.contentColor = Color.white;
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.EndScrollView();

            _scrollCurrentLogView = GUILayout.BeginScrollView(_scrollCurrentLogView, "Box", GUILayout.Height(100));
            if (_currentLogIndex != -1)
            {
                GUILayout.Label(_logInformations[_currentLogIndex].message + "\r\n\r\n" + _logInformations[_currentLogIndex].stackTrace);
            }
            GUILayout.EndScrollView();
        }
        #endregion

        #region memory
        else if (_debugType == DebugType.Memory)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("Memory Information");
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical("Box");
#if UNITY_5
            GUILayout.Label("总内存:" + Profiler.GetTotalReservedMemory() / 1000000 + "MB");
            GUILayout.Label("已占用内存:" + Profiler.GetTotalAllocatedMemory() / 1000000 + "MB");
            GUILayout.Label("空闲中内存:" + Profiler.GetTotalUnusedReservedMemory() / 1000000 + "MB");
            GUILayout.Label("总Mono堆内存:" + Profiler.GetMonoHeapSize() / 1000000 + "MB");
            GUILayout.Label("已占用Mono堆内存:" + Profiler.GetMonoUsedSize() / 1000000 + "MB");
#endif
#if UNITY_7
            GUILayout.Label("总内存:" + Profiler.GetTotalReservedMemoryLong() / 1000000 + "MB");
            GUILayout.Label("已占用内存:" + Profiler.GetTotalAllocatedMemoryLong() / 1000000 + "MB");
            GUILayout.Label("空闲中内存:" + Profiler.GetTotalUnusedReservedMemoryLong() / 1000000 + "MB");
            GUILayout.Label("总Mono堆内存:" + Profiler.GetMonoHeapSizeLong() / 1000000 + "MB");
            GUILayout.Label("已占用Mono堆内存:" + Profiler.GetMonoUsedSizeLong() / 1000000 + "MB");
#endif
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("卸载未使用的资源"))
            {
                Resources.UnloadUnusedAssets();
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("使用GC垃圾回收"))
            {
                GC.Collect();
            }
            GUILayout.EndHorizontal();
        }
        #endregion

        #region system
        else if (_debugType == DebugType.System)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("System Information");
            GUILayout.EndHorizontal();

            _scrollSystemView = GUILayout.BeginScrollView(_scrollSystemView, "Box");
            GUILayout.Label("操作系统:" + SystemInfo.operatingSystem);
            GUILayout.Label("系统内存:" + SystemInfo.systemMemorySize + "MB");
            GUILayout.Label("处理器:" + SystemInfo.processorType);
            GUILayout.Label("处理器数量:" + SystemInfo.processorCount);
            GUILayout.Label("显卡:" + SystemInfo.graphicsDeviceName);
            GUILayout.Label("显卡类型:" + SystemInfo.graphicsDeviceType);
            GUILayout.Label("显存:" + SystemInfo.graphicsMemorySize + "MB");
            GUILayout.Label("显卡标识:" + SystemInfo.graphicsDeviceID);
            GUILayout.Label("显卡供应商:" + SystemInfo.graphicsDeviceVendor);
            GUILayout.Label("显卡供应商标识码:" + SystemInfo.graphicsDeviceVendorID);
            GUILayout.Label("设备模式:" + SystemInfo.deviceModel);
            GUILayout.Label("设备名称:" + SystemInfo.deviceName);
            GUILayout.Label("设备类型:" + SystemInfo.deviceType);
            GUILayout.Label("设备标识:" + SystemInfo.deviceUniqueIdentifier);
            GUILayout.EndScrollView();
        }
        #endregion

        #region screen
        else if (_debugType == DebugType.Screen)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("Screen Information");
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical("Box");
            GUILayout.Label("DPI:" + Screen.dpi);
            GUILayout.Label("分辨率:" + Screen.currentResolution.ToString());
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("全屏"))
            {
                Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, !Screen.fullScreen);
            }
            GUILayout.EndHorizontal();
        }
        #endregion

        #region Quality
        else if (_debugType == DebugType.Quality)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("Quality Information");
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical("Box");
            string value = "";
            if (QualitySettings.GetQualityLevel() == 0)
            {
                value = " [最低]";
            }
            else if (QualitySettings.GetQualityLevel() == QualitySettings.names.Length - 1)
            {
                value = " [最高]";
            }

            GUILayout.Label("图形质量:" + QualitySettings.names[QualitySettings.GetQualityLevel()] + value);
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("降低一级图形质量"))
            {
                QualitySettings.DecreaseLevel();
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("提升一级图形质量"))
            {
                QualitySettings.IncreaseLevel();
            }
            GUILayout.EndHorizontal();
        }
        #endregion

        #region Environment
        else if (_debugType == DebugType.Environment)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("Environment Information");
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical("Box");
            GUILayout.Label("项目名称:" + Application.productName);
#if UNITY_5
            GUILayout.Label("项目ID:" + Application.bundleIdentifier);
#endif
#if UNITY_7
            GUILayout.Label("项目ID:" + Application.identifier);
#endif
            GUILayout.Label("项目版本:" + Application.version);
            GUILayout.Label("Unity版本:" + Application.unityVersion);
            GUILayout.Label("公司名称:" + Application.companyName);
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("退出程序"))
            {
                Application.Quit();
            }
            GUILayout.EndHorizontal();
        }
        #endregion
    }
Пример #59
0
        public static IEnumerable <TreeNode> LazyGetChildNodesOfObject(Expression targetObject, DebugType shownType)
        {
            MemberInfo[] publicStatic      = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] publicInstance    = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicStatic   = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
            MemberInfo[] nonPublicInstance = shownType.GetFieldsAndNonIndexedProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            DebugType baseType = (DebugType)shownType.BaseType;

            if (baseType != null)
            {
                yield return(new TreeNode(
                                 DebuggerResourceService.GetImage("Icons.16x16.Class"),
                                 StringParser.Parse("${res:MainWindow.Windows.Debug.LocalVariables.BaseClass}"),
                                 baseType.Name,
                                 baseType.FullName,
                                 baseType.FullName == "System.Object" ? null : Utils.LazyGetChildNodesOfObject(targetObject, baseType)
                                 ));
            }

            if (nonPublicInstance.Length > 0)
            {
                yield return(new TreeNode(
                                 null,
                                 StringParser.Parse("${res:MainWindow.Windows.Debug.LocalVariables.NonPublicMembers}"),
                                 string.Empty,
                                 string.Empty,
                                 Utils.LazyGetMembersOfObject(targetObject, nonPublicInstance)
                                 ));
            }

            if (publicStatic.Length > 0 || nonPublicStatic.Length > 0)
            {
                IEnumerable <TreeNode> childs = Utils.LazyGetMembersOfObject(targetObject, publicStatic);
                if (nonPublicStatic.Length > 0)
                {
                    TreeNode nonPublicStaticNode = new TreeNode(
                        null,
                        StringParser.Parse("${res:MainWindow.Windows.Debug.LocalVariables.NonPublicStaticMembers}"),
                        string.Empty,
                        string.Empty,
                        Utils.LazyGetMembersOfObject(targetObject, nonPublicStatic)
                        );
                    childs = Utils.PrependNode(nonPublicStaticNode, childs);
                }
                yield return(new TreeNode(
                                 null,
                                 StringParser.Parse("${res:MainWindow.Windows.Debug.LocalVariables.StaticMembers}"),
                                 string.Empty,
                                 string.Empty,
                                 childs
                                 ));
            }

            DebugType iListType = (DebugType)shownType.GetInterface(typeof(IList).FullName);

            if (iListType != null)
            {
                yield return(new IListNode(targetObject));
            }
            else
            {
                DebugType iEnumerableType, itemType;
                if (shownType.ResolveIEnumerableImplementation(out iEnumerableType, out itemType))
                {
                    yield return(new IEnumerableNode(targetObject, itemType));
                }
            }

            foreach (TreeNode node in LazyGetMembersOfObject(targetObject, publicInstance))
            {
                yield return(node);
            }
        }
Пример #60
0
 public static bool SystemDebugEnabled(AOSystems system, DebugType debugType, IFaction faction)
 {
     return(SystemDebugEnabled(system, debugType) && FactionInScope(faction, Settings.Instance.DebugFactionScope));
 }