//This is a Knuth-Morris-Pratt string-matching algorithm, but applied to //Mono.Cecil.Cil.Instruction instead of characters, and a //InstructionCollection instead of string. I think it's a nice //metaphor :) internal static bool Match(Pattern pattern, IList<Instruction> target) { int instructionsMatched = 0; pattern.ComputePrefixes (Current); for (int index = 0; index < target.Count; index++) { while (instructionsMatched > 0 && !AreEquivalent (pattern[instructionsMatched], target[index])) instructionsMatched = pattern.Prefixes[instructionsMatched - 1]; if (AreEquivalent (pattern[instructionsMatched], target[index])) instructionsMatched++; if (instructionsMatched == pattern.Count) return true; } return false; }
void WriteToOutput (MethodDefinition current, MethodDefinition target, Pattern found) { Log.WriteLine (this, "Found pattern in {0} and {1}", current, target); Log.WriteLine (this, "\t Pattern"); for (int index = 0; index < found.Count; index++) Log.WriteLine (this, "\t\t{0} - {1}", found[index].OpCode.Code, found[index].Operand != null? found[index].Operand : "No operator"); }