コード例 #1
0
        static CodeAction HandleNegatedCase(BaseRefactoringContext ctx, IfElseStatement ifElseStatement, Match match, out IsExpression isExpression, out int foundCastCount)
        {
            foundCastCount = 0;
            var outerIs = match.Get <Expression>("isExpression").Single();

            isExpression = AlUtil.GetInnerMostExpression(outerIs) as IsExpression;
            var obj        = AlUtil.GetInnerMostExpression(isExpression.Expression);
            var castToType = isExpression.Type;

            var cast = new Choice {
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastTo(castToType.Clone())),
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastAs(castToType.Clone()))
            };

            var rr = ctx.Resolve(castToType);

            if (rr == null || rr.IsError || rr.Type.IsReferenceType == false)
            {
                return(null);
            }
            var foundCasts = ifElseStatement.GetParent <BlockStatement>().DescendantNodes(n => n.StartLocation >= ifElseStatement.StartLocation && !cast.IsMatch(n)).Where(n => cast.IsMatch(n)).ToList();

            foundCastCount = foundCasts.Count;

            return(new CodeAction(ctx.TranslateString("Use 'as' and check for null"), script => {
                var varName = ctx.GetNameProposal(CreateMethodDeclarationAction.GuessNameFromType(rr.Type), ifElseStatement.StartLocation);
                var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new AsExpression(obj.Clone(), castToType.Clone()));
                var binaryOperatorIdentifier = new IdentifierExpression(varName);
                var binaryOperatorExpression = new BinaryOperatorExpression(binaryOperatorIdentifier, BinaryOperatorType.Equality, new NullReferenceExpression());
                var linkedNodes = new List <AstNode>();
                linkedNodes.Add(varDec.Variables.First().NameToken);
                linkedNodes.Add(binaryOperatorIdentifier);
                if (IsEmbeddedStatement(ifElseStatement))
                {
                    var block = new BlockStatement();
                    block.Add(varDec);
                    var newIf = (IfElseStatement)ifElseStatement.Clone();
                    newIf.Condition = binaryOperatorExpression;
                    foreach (var node in newIf.DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => cast.IsMatch(n)))
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        node.ReplaceWith(id);
                    }
                    block.Add(newIf);
                    script.Replace(ifElseStatement, block);
                }
                else
                {
                    script.InsertBefore(ifElseStatement, varDec);
                    script.Replace(ifElseStatement.Condition, binaryOperatorExpression);
                    foreach (var c in foundCasts)
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        script.Replace(c, id);
                    }
                }
                script.Link(linkedNodes);
            }, isExpression.IsToken));
        }
コード例 #2
0
        protected override CodeAction GetAction(RefactoringContext ctx, IfElseStatement ifElseStatement)
        {
            var isExpr = ctx.GetNode <IsExpression>();

            if (isExpr == null || !isExpr.IsToken.Contains(ctx.Location))
            {
                return(null);
            }

            int foundCasts;
            var action = ScanIfElse(ctx, ifElseStatement, out isExpr, out foundCasts);

            if (action != null)
            {
                return(action);
            }

            isExpr = ctx.GetNode <IsExpression>();
            var node = isExpr.Parent;

            while (node is ParenthesizedExpression)
            {
                node = node.Parent;
            }
            var uOp = node as UnaryOperatorExpression;

            if (uOp != null && uOp.Operator == UnaryOperatorType.Not)
            {
                var rr = ctx.Resolve(isExpr.Type);
                if (rr == null || rr.IsError || rr.Type.IsReferenceType == false)
                {
                    return(null);
                }

                return(new CodeAction(ctx.TranslateString("Use 'as' and check for null"), script => {
                    var varName = ctx.GetNameProposal(CreateMethodDeclarationAction.GuessNameFromType(rr.Type), ifElseStatement.StartLocation);
                    var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new AsExpression(isExpr.Expression.Clone(), isExpr.Type.Clone()));
                    var binaryOperatorIdentifier = new IdentifierExpression(varName);
                    var binaryOperatorExpression = new BinaryOperatorExpression(binaryOperatorIdentifier, BinaryOperatorType.Equality, new NullReferenceExpression());
                    if (IsEmbeddedStatement(ifElseStatement))
                    {
                        var block = new BlockStatement();
                        block.Add(varDec);
                        var newIf = (IfElseStatement)ifElseStatement.Clone();
                        newIf.Condition = binaryOperatorExpression;
                        block.Add(newIf);
                        script.Replace(ifElseStatement, block);
                    }
                    else
                    {
                        script.InsertBefore(ifElseStatement, varDec);
                        script.Replace(uOp, binaryOperatorExpression);
                    }
                }, isExpr.IsToken));
            }

            var obj        = isExpr.Expression;
            var castToType = isExpr.Type;

            var cast = new Choice {
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastTo(castToType.Clone())),
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastAs(castToType.Clone()))
            };

            var rr2 = ctx.Resolve(castToType);

            if (rr2 == null || rr2.IsError || rr2.Type.IsReferenceType == false)
            {
                return(null);
            }
            var foundCasts2 = isExpr.GetParent <Statement>().DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => isExpr.StartLocation < n.StartLocation && cast.IsMatch(n)).ToList();

            return(new CodeAction(ctx.TranslateString("Use 'as' and check for null"), script => {
                var varName = ctx.GetNameProposal(CreateMethodDeclarationAction.GuessNameFromType(rr2.Type), ifElseStatement.StartLocation);
                var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new AsExpression(obj.Clone(), castToType.Clone()));
                var binaryOperatorIdentifier = new IdentifierExpression(varName);
                var binaryOperatorExpression = new BinaryOperatorExpression(binaryOperatorIdentifier, BinaryOperatorType.InEquality, new NullReferenceExpression());
                var linkedNodes = new List <AstNode>();
                linkedNodes.Add(varDec.Variables.First().NameToken);
                linkedNodes.Add(binaryOperatorIdentifier);
                if (IsEmbeddedStatement(ifElseStatement))
                {
                    var block = new BlockStatement();
                    block.Add(varDec);
                    var newIf = (IfElseStatement)ifElseStatement.Clone();
                    newIf.Condition = binaryOperatorExpression;
                    foreach (var node2 in newIf.DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => cast.IsMatch(n)))
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        node2.ReplaceWith(id);
                    }
                    block.Add(newIf);
                    script.Replace(ifElseStatement, block);
                }
                else
                {
                    script.InsertBefore(ifElseStatement, varDec);
                    script.Replace(isExpr, binaryOperatorExpression);
                    foreach (var c in foundCasts2)
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        script.Replace(c, id);
                    }
                }
                script.Link(linkedNodes);
            }, isExpr.IsToken));
        }
コード例 #3
0
        public void ProcessDirectory(BundleContext context, IncludeDirectoryData includeDirectoryData, string directoryPath, ref Dictionary <string, BundleFile> files)
        {
            IEnumerable <IFileInfo> directoryFiles;
            IDirectoryContents      directoryContent = context.FileProvider.GetDirectoryContents(directoryPath);

            if (directoryContent != null)
            {
                Regex regEx;
                switch (includeDirectoryData.PatternType)
                {
                // We used to be able to just call DirectoryInfo.GetFiles,
                // now we have to add support for * and {version} syntax on top of VPP
                case PatternType.Version:
                    regEx          = PatternHelper.BuildRegex(includeDirectoryData.SearchPattern);
                    directoryFiles = directoryContent.Where(file => regEx.IsMatch(file.Name) && !file.IsDirectory);
                    break;

                case PatternType.All:
                    directoryFiles = directoryContent.Where(file => !file.IsDirectory);
                    break;

                case PatternType.Exact:
                    directoryFiles = directoryContent.Where(file => String.Equals(file.Name, includeDirectoryData.SearchPattern, StringComparison.OrdinalIgnoreCase) && !file.IsDirectory);
                    break;

                case PatternType.Suffix:
                case PatternType.Prefix:
                default:
                    regEx          = PatternHelper.BuildWildcardRegex(includeDirectoryData.SearchPattern);
                    directoryFiles = directoryContent.Where(file => regEx.IsMatch(file.Name) && !file.IsDirectory);
                    break;
                }

                // Sort the directory files so we get deterministic order
                directoryFiles = directoryFiles.OrderBy(file => file, PhysicalFileComparer.Instance);

                //List<BundleFile> filterList = new List<BundleFile>();
                //foreach (IFileInfo file in directoryFiles)
                //{
                //    filterList.Add(new BundleFile());
                //}
                //files.AddRange(context.BundleCollection.DirectoryFilter.FilterIgnoredFiles(context, filterList));

                foreach (IFileInfo file in directoryFiles)
                {
                    files.Add(directoryPath + "/" + file.Name, new BundleFile(context.Parent)
                    {
                        PhysicalPath = file.PhysicalPath, VirtualPath = directoryPath + "/" + file.Name
                    });
                }

                // Need to recurse on subdirectories if requested
                if (includeDirectoryData.SearchSubdirectories)
                {
                    foreach (IFileInfo subDir in directoryContent.Where(file => file.IsDirectory))
                    {
                        ProcessDirectory(context, includeDirectoryData, directoryPath + "/" + subDir.Name, ref files);
                    }
                }
            }
        }
 public CheckNullVisitor(ParameterDeclaration parameter)
 {
     pattern = PatternHelper.CommutativeOperator(new IdentifierExpression(parameter.Name), BinaryOperatorType.Any, new NullReferenceExpression());
 }
コード例 #5
0
        public async Task <string> ApplyPatchesToProcessById(int processId)
        {
            Log.Info("Started patching process with ID: {0}", processId);
            var memory = new Memory(processId);

            await Task.Delay(500);

            Log.Info("Attempting to get module handle.");
            var moduleHandle = memory.GetProcessModuleHandle("client.exe");

            if (moduleHandle == IntPtr.Zero)
            {
                Log.Error("Patch Failed: Failed to get module handle");
                return("Patch failed! (Failed to get module handle)");
            }


            var moduleInfo = new MODULEINFO();
            var success    = Unmanaged.GetModuleInformation(memory.GetProcessHandle(), moduleHandle, out moduleInfo,
                                                            (uint)Marshal.SizeOf(moduleInfo));

            if (!success)
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                Log.Error("Patch Failed: Failed to get module info: {0}", error.Message);
                return(string.Format("Patch Failed: Failed to get module info: {0}", error.Message));
            }

            Log.Info("Attempting to apply patch: Enable MultiClient");

            var pattern = new short[]
            {
                0xE8, -1, -1, -1, -1, 0x84, 0xC0, 0x74, -1, 0x8B, 0x0D, -1, -1, -1, -1, 0x8D,
                0x45, 0xCC
            };
            var offset = 0x07;
            var edit   = new byte[] { 0x90, 0x90 };

            Log.Info("Pattern: {0}\r\nEdit Offset: {1}\r\nEdit: {2}", PatternHelper.ConvertToPatternString(pattern), offset, PatternHelper.ConvertToPatternString(edit));

            var address = IntPtr.Zero;

            if (_clientProfile.LastVersionForPatternSearch == _version)
            {
                Log.Info("Using last known address.");
                address = _clientProfile.LastAddressForPatterSearch;
            }

            if (address == IntPtr.Zero)
            {
                address = await memory.QuickSearch((uint)moduleInfo.lpBaseOfDll,
                                                   (uint)moduleInfo.lpBaseOfDll + moduleInfo.SizeOfImage, pattern);

                if (address == IntPtr.Zero)
                {
                    Log.Error("Patch Failed: No match for pattern.");
                    return("Patch Failed: No match for pattern.");
                }

                _clientProfile.LastVersionForPatternSearch = _version;
                _clientProfile.LastAddressForPatterSearch  = address;
            }

            Log.Info("Start Address: {0:x8} | Address of Pattern Match: {1:x8}", (int)moduleInfo.lpBaseOfDll, (int)address);

            memory.WriteProcMem(address + offset, edit);

            //foreach (var memoryPatch in MemoryPatches)
            //{
            //    Log.Info("Applying patch: {0}", memoryPatch.Name);

            //    foreach (var patch in memoryPatch.Patches)
            //    {
            //        Log.Info("Pattern: {0}\r\nEdit Offset: {1}\r\nEdit: {2}", string.Join(", ", patch.Pattern), patch.Offset, string.Join(", ", patch.Edit));
            //        var address = memory.QuickSearch((uint) moduleInfo.lpBaseOfDll,
            //            (uint) moduleInfo.lpBaseOfDll + moduleInfo.SizeOfImage, patch.Pattern);
            //        memory.WriteProcMem(address + patch.Offset, patch.Edit);
            //    }
            //}

            return(null);
        }