AddExceptionHandling.cs :  » Aspect-Oriented-Frameworks » Runtime-Assembly-Instrumentation-Library » rail » Transformation » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Aspect Oriented Frameworks » Runtime Assembly Instrumentation Library 
Runtime Assembly Instrumentation Library » rail » Transformation » AddExceptionHandling.cs
/*
  The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
  you may not use this file except in compliance with the License. You may obtain a copy of the License at 
  http://www.mozilla.org/MPL/ 
  Software distributed under the License is distributed on an "AS IS" basis, 
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language 
  governing rights and limitations under the License. 

  The Original Code is RAIL(Runtime Assembly Instrumentation Library) Alpha Version.
  The Initial Developer of the Original Code is University of Coimbra,
  Computer Science Department, Dependable Systems Group. Copyright (C) University of Coimbra. 
  All Rights Reserved.  
*/
using System;
using Rail.Reflect;
using Rail.Exceptions;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Text;
using System.Xml;

namespace Rail.Transformation{

  public class AddExceptionHandling : EmptyVisitor
  {
    /// <summary>
    /// 
    /// </summary>
    private readonly HandlerCode handlerCode;
    /// <summary>
    /// 
    /// </summary>
    private readonly RType exceptionType;

    private readonly bool removeRelatedAttributes;

    private readonly bool IsXmlVersion;

    private readonly string xmlReportFile;

    private Hashtable MethodsAndExceptions;

    private struct Delimiter
    {
      public int StartIndex;
      public int EndIndex;

      public Delimiter(int start, int end)
      {
        this.StartIndex = start;
        this.EndIndex = end;
      }
    }
    
    /// <summary>
    /// Created an object for Adding Exception Handling to marked methods
    /// The methods should be marked with ExceptionAttribute Custom attributes
    /// and the code to be handled must be delimited by the static methods
    /// Marker.Start() and Marker.End(). If more then one pair of this methods exist,
    /// there must be an equal number of ExceptionAttribute attributes, if not, the 
    /// first attribute will caracterize all the handlers. If there are no methods
    /// delimiters, the all code in the method is insert in the handler
    /// </summary>
    /// <param name="ExceptionType">The type of the exception to treat</param>
    /// <param name="CodeHandlingType">The code and the kind of handlers to insert</param>
    /// <param name="RemoveRelatedAttributes">If true all the used attributes are removed from
    /// the method because they already acomplished there function</param>
    public AddExceptionHandling(RType ExceptionType,HandlerCode CodeHandlingType,bool RemoveRelatedAttributes)
    {
      this.handlerCode = CodeHandlingType;
      this.exceptionType = ExceptionType;
      this.removeRelatedAttributes = RemoveRelatedAttributes;
      this.IsXmlVersion = false;
    }
        

    public AddExceptionHandling(RType ExceptionType,HandlerCode CodeHandlingType,string XmlReportFile)
    {
      this.IsXmlVersion = true;
      this.exceptionType = ExceptionType;
      this.handlerCode = CodeHandlingType;
      this.xmlReportFile = XmlReportFile;
      this.MethodsAndExceptions = new Hashtable();      
      XmlTextReader reader = new XmlTextReader(xmlReportFile);
      StringBuilder keyBldr = null;
      StringBuilder exceptName = null;
      StringBuilder exceptLine = null;
      string className = null;
      string methodName = null;
      char [] buffer = new char[1];
      Delimiter currentDelimiter = new Delimiter(-1,-1);
      while (reader.Read())
      {
        switch (reader.NodeType)
        {
          case XmlNodeType.Element:
            if (reader.Name.Equals("class"))
              if (reader.HasAttributes)
              {
                keyBldr = new StringBuilder(reader.GetAttribute("name"));
                className = keyBldr.ToString();
              }
            if (reader.Name.Equals("method"))
            {
              if (reader.HasAttributes)
              {
                keyBldr = new StringBuilder(className);
                keyBldr.Append(reader.GetAttribute("name"));
                keyBldr.Append(reader.GetAttribute("return"));
                keyBldr.Append(reader.GetAttribute("args"));
                methodName = keyBldr.ToString();
                currentDelimiter = new Delimiter(-1,-1);
              }
            }
            if (reader.Name.Equals("name"))
            {
              exceptName = new StringBuilder();
              while( 0 != reader.ReadChars(buffer, 0, 1))
              {
                exceptName.Append(buffer); 
              }
            }
            if (reader.Name.Equals("code_line"))
            {
              exceptLine = new StringBuilder();
              while( 0 != reader.ReadChars(buffer, 0, 1))
              {
                exceptLine.Append(buffer); 
              }
            }
            if (exceptLine!=null && 
              exceptName.ToString().Equals(this.exceptionType.NameWithNameSpace))
            {
              int currLine = System.Int32.Parse(exceptLine.ToString());
              if (currentDelimiter.StartIndex < 0)
              {
                currentDelimiter.StartIndex = currLine;
                currentDelimiter.EndIndex = currLine + 1;
              }
              else if (currentDelimiter.EndIndex < currLine)
              {
                currentDelimiter.EndIndex = currLine;
              }
              //This is wrong, but I don not have a mean to know if the stactk is empty
              //The stack must be empty before entering a try...catch block
              currentDelimiter.StartIndex = 0;
              if (this.MethodsAndExceptions.ContainsKey(methodName))
                this.MethodsAndExceptions[methodName] = currentDelimiter;
              else
                this.MethodsAndExceptions.Add(methodName,currentDelimiter);
            }
            exceptLine = null;
            break;
        }      
      }
      
    }

    /// <summary>
    /// Method used to instrument the code of <code>RMethodDef</code> and 
    /// <code>RConstructorDef</code> 
    /// </summary>
    /// <param name="method">The method which method body is to be instrumented</param>
    private void VisitMethodBodyCustomAttrib(RMethodBase method)
    {
      
      #region Changes the body of the method
      RCustomAttrib [] customAttribs = method.GetCustomAttributes("Rail.Exceptions.ExceptionAttribute",false);
      if (customAttribs == null)
        return;      
      bool ExceptionTypeExists = false;
      RCustomAttrib [] customAttribsTemp = new RCustomAttrib[customAttribs.Length];
      int maxAttribsNum = 0;
      foreach(RCustomAttrib r in customAttribs)
      {
        Object [] args = r.GetAttributeConstructorArguments();
        if (args!=null &&
          args.Length == 1)
          if (args[0] is RType)
            if (((RType)args[0]).NameWithNameSpace==this.exceptionType.NameWithNameSpace)
            {
              customAttribsTemp[maxAttribsNum] = r;
              ++maxAttribsNum;
              ExceptionTypeExists = true;
            }
      }
      if (!ExceptionTypeExists)
        return;
      customAttribs = new RCustomAttrib[maxAttribsNum];
      while (maxAttribsNum > 0)
      {
        --maxAttribsNum;
        customAttribs[maxAttribsNum] = customAttribsTemp[maxAttribsNum];
      }

      if (customAttribs.Length==0)
        return;

      MSIL.MethodBody mb = null;
      if (method is RConstructor)
        mb = ((RConstructorDef)method).MethodBody;
      else if (method is RMethod)
        mb = ((RMethodDef)method).MethodBody;

      MSIL.Code code = null;
      if (mb!=null)
        code = mb.GetCode();

      if (code!=null)
      {
        code.updateInstructionIndex();
        if (customAttribs.Length==1)
        {
          if (this.handlerCode == HandlerCode.CatchAndLog)
          {
            if (!CheckIfHasMarkers(code))
            {
              Type markerType = Type.GetType("Rail.Exceptions.Marker");
              Type [] paramsType = new Type[0];
              MethodInfo StartMethod = markerType.GetMethod("Start",paramsType);
              MethodInfo EndMethod = markerType.GetMethod("End",paramsType);
              RMethodRef StartMethodR = new RMethodRef(StartMethod,(RAssemblyDef)mb.parent.DeclaringType.Assembly);
              RMethodRef EndMethodR = new RMethodRef(EndMethod,(RAssemblyDef)mb.parent.DeclaringType.Assembly);
              code.Insert(0,MSIL.ILFactory.Call(false,StartMethodR));
              code.updateInstructionIndex();
              int endIndex = code.InstructionCount-1;
              if (mb.excpTable!=null)
                if (mb.excpTable.Count()>0)
                {
                  MSIL.ExceptionBlock exB = mb.excpTable[mb.excpTable.Count()-1] as MSIL.ExceptionBlock;
                  endIndex = exB.EndOfProtectedScope.index + 1;
                }
              //TODO: this is a workaround
              endIndex = code.InstructionCount-1;
              code.Insert(endIndex,MSIL.ILFactory.Call(false,EndMethodR));
              code.updateInstructionIndex();
              OneExceptionCatchAndLog(null,code);
            }
            else
            {
              OneExceptionCatchAndLog(null,code);
            }
            if (this.removeRelatedAttributes)
            {
              if (method is RConstructor)
                ((RConstructorDef)method).RemoveCustomAttribute(customAttribs[0]);
              else if (method is RMethod)
                ((RMethodDef)method).RemoveCustomAttribute(customAttribs[0]);
            }
            return;
          }else
            throw new NotImplementedException();
        }
        else
        {
          if (this.handlerCode == HandlerCode.CatchAndLog)
          {

            return;
          }
          else
            throw new NotImplementedException();
        }
        
      }
        
      #endregion  
    }


    /// <summary>
    /// Method used to instrument the code of <code>RMethodDef</code> and 
    /// <code>RConstructorDef</code> 
    /// </summary>
    /// <param name="method">The method which method body is to be instrumented</param>
    private void VisitMethodBodyXml(RMethodBase method)
    {
      
      #region Changes the body of the method

      MSIL.MethodBody mb = null;
      if (method is RConstructor)
        mb = ((RConstructorDef)method).MethodBody;
      else if (method is RMethod)
        mb = ((RMethodDef)method).MethodBody;

      MSIL.Code code = null;
      if (mb!=null)
        code = mb.GetCode();

      if (code!=null)
      {
        code.updateInstructionIndex();
        if (this.handlerCode == HandlerCode.CatchAndLog)
        {
          Type markerType = Type.GetType("Rail.Exceptions.Marker");
          Type [] paramsType = new Type[0];
          MethodInfo StartMethod = markerType.GetMethod("Start",paramsType);
          MethodInfo EndMethod = markerType.GetMethod("End",paramsType);
          RMethodRef StartMethodR = new RMethodRef(StartMethod,(RAssemblyDef)mb.parent.DeclaringType.Assembly);
          RMethodRef EndMethodR = new RMethodRef(EndMethod,(RAssemblyDef)mb.parent.DeclaringType.Assembly);
            
          StringBuilder methodName = new StringBuilder(mb.parent.DeclaringType.NameWithNameSpace);
          methodName.Append(mb.parent.Name);
          if (mb.parent is RMethod)
            methodName.Append(((RMethodDef)mb.parent).ReturnType.ReturnType.NameWithNameSpace);
          for (int i = 1; i <= mb.parent.ParametersCount; i++)
          {
            if (i==mb.parent.ParametersCount)
              methodName.Append(mb.parent.GetParameter(i).ParameterType.NameWithNameSpace);
            else
              methodName.Append(mb.parent.GetParameter(i).ParameterType.NameWithNameSpace + " ");
          }
          Delimiter currDelimiter = (Delimiter)this.MethodsAndExceptions[methodName.ToString()];
          MSIL.ExceptionBlock exBlockEnd = null;

          if (mb.excpTable!=null)
          {
            int exIndex = mb.excpTable.Count();
            while (exIndex>0)
            {
              --exIndex;
              MSIL.ExceptionBlock exBlock = mb.excpTable[exIndex] as MSIL.ExceptionBlock;
              if (exBlock.start.index<=currDelimiter.StartIndex &&
                exBlock.start.index<=currDelimiter.EndIndex &&
                exBlock.end.index>=currDelimiter.EndIndex)
              {
                currDelimiter.EndIndex = exBlock.LastInstruction();                
                exBlockEnd = exBlock;
              }
              else if (exBlock.start.index<=currDelimiter.StartIndex &&
                exBlock.end.index>=currDelimiter.StartIndex &&
                exBlock.end.index<=currDelimiter.EndIndex)
              {
                currDelimiter.StartIndex = exBlock.start.index;
                currDelimiter.EndIndex = exBlock.LastInstruction();
                exBlockEnd = exBlock;
              }
              else if (exBlock.start.index>=currDelimiter.StartIndex &&
                exBlock.end.index<=currDelimiter.EndIndex &&
                exBlock.LastInstruction()>=currDelimiter.EndIndex)
              {
                currDelimiter.EndIndex = exBlock.LastInstruction();
                exBlockEnd = exBlock;
              }
            }
          }
          code.Insert(currDelimiter.StartIndex,MSIL.ILFactory.Call(false,StartMethodR));
          //          if (code[currDelimiter.EndIndex].OpCode.Equals(OpCodes.Endfinally))
          //            currDelimiter.EndIndex +=1; 
          //TODO: this is a work around, I'm not giving
          //the right end index for the try... catch block
          currDelimiter.EndIndex = code.InstructionCount-2;
          code.Insert(++currDelimiter.EndIndex,MSIL.ILFactory.Call(false,EndMethodR));
          code.updateInstructionIndex();
          if (exBlockEnd!=null)
          {
            exBlockEnd.GetLastHandler().EndInstruction = code[currDelimiter.EndIndex];
            if (code.InstructionCount>currDelimiter.EndIndex+1)
            {
              MSIL.Instruction instr = code[currDelimiter.EndIndex+1];
              IEnumerator targets = instr.GetTargeters();
              ArrayList currTargets = new ArrayList();
              if (targets!=null)
              while (targets.MoveNext())
              {
                MSIL.Instruction currInstr = (MSIL.Instruction)targets.Current;
                if (currInstr.index>exBlockEnd.start.index &&
                  currInstr.index<exBlockEnd.LastInstruction())
                {
                  currTargets.Add(currInstr);
                }
              }
              foreach(MSIL.Instruction currInstr in currTargets)
                instr.RemoveTargeter(currInstr);
              foreach(MSIL.Instruction currInstr in currTargets)
                code[currDelimiter.EndIndex].AddTargeter((MSIL.ITargeter)currInstr);
            }
          }

          
          OneExceptionCatchAndLog(null,code);
          return;
        }
        else
          throw new NotImplementedException();
      }
      #endregion  
    }


    private bool CheckIfHasMarkers(MSIL.Code code)
    {
      foreach (MSIL.Instruction i in code)
      {
        if (i is MSIL.ILMethod)
        {
          MSIL.ILMethod ii = i as MSIL.ILMethod;
          if (ii.Method!=null)
            if ((ii.Method.Name.Equals("Start") &&
              ii.Method.DeclaringType.NameWithNameSpace.Equals("Rail.Exceptions.Marker")) ||
              (ii.Method.Name.Equals("End") &&
              ii.Method.DeclaringType.NameWithNameSpace.Equals("Rail.Exceptions.Marker")))
            {
              return true;
            }
        }
      }
      return false;
      
    }

    private void OneExceptionCatchAndLog(Stack exceptionBlocks,MSIL.Code code)
    {
      if (exceptionBlocks==null)
      {
        exceptionBlocks = new Stack();
      }
      if (code.MethodBody.excpTable==null)
      {
        code.MethodBody.excpTable = new MSIL.ExceptionTable();
      }
      int instIndex = 0;
      foreach (MSIL.Instruction i in code)
      {
        if (i is MSIL.ILMethod)
        {
          MSIL.ILMethod ii = i as MSIL.ILMethod;
          if (ii.Method!=null &&
            ii.Method.Name.Equals("Start") &&
            ii.Method.DeclaringType.NameWithNameSpace.Equals("Rail.Exceptions.Marker"))
          {
            MSIL.ExceptionBlock exB = new MSIL.ExceptionBlock(code[instIndex+1],null);
            exceptionBlocks.Push(exB);
            code.Remove(instIndex);
            OneExceptionCatchAndLog(exceptionBlocks,code);
            return;
          }
          else if (ii.Method!=null &&
            ii.Method.Name.Equals("End") &&
            ii.Method.DeclaringType.NameWithNameSpace.Equals("Rail.Exceptions.Marker"))
          {
            MSIL.ExceptionBlock exB = exceptionBlocks.Pop() as MSIL.ExceptionBlock;
            exB.catchHandlers = new ArrayList();
            code.updateInstructionIndex();
            exB.EndOfProtectedScope = code[instIndex-1];
            bool AlreadyContains = false;
            bool ChangeMade = false;
            MSIL.LocalVariable local = code.MethodBody.DefineLocalVariable(this.exceptionType);
            ArrayList currTargets = new ArrayList();
            MSIL.Instruction instr = code[instIndex];
            IEnumerator targets = instr.GetTargeters();
            if (targets!=null)
            while (targets.MoveNext())
            {
              MSIL.Instruction currInstr = (MSIL.Instruction)targets.Current;
              currTargets.Add(currInstr);
            }
            if (code.MethodBody.excpTable.Count()>0)
            {
              for(int exIndex = 0; exIndex < code.MethodBody.excpTable.Count(); exIndex++)
              {
                MSIL.ExceptionBlock lastBlock = code.MethodBody.excpTable[exIndex] as MSIL.ExceptionBlock;
                if (lastBlock.start.index == exB.start.index &&
                  lastBlock.end.index == exB.end.index)
                {
                  AlreadyContains = true;
                  instIndex = lastBlock.LastInstruction();
                  exB = lastBlock;
                  break;
                }
                else if (lastBlock.LastInstruction()==exB.end.index+1)
                {                  
                  code.Remove(instIndex);
                  code.Insert(instIndex++,MSIL.ILFactory.Stloc(local));                  
                  lastBlock.GetLastHandler().EndInstruction = code[instIndex-2];
                  exB.EndOfProtectedScope = code[instIndex-1];
                  ChangeMade = true;
                  break;
                
                }
              }
            }
            if (!ChangeMade)
            {
              code.Remove(instIndex);          
              code.Insert(instIndex++,MSIL.ILFactory.Stloc(local));
            }

            exB.catchHandlers.Add(new MSIL.ExceptionHandler(code[instIndex-1],null,exceptionType));
            code.Insert(instIndex++,MSIL.ILFactory.Ldloc(local));
            
            Type exType = Type.GetType(this.exceptionType.NameWithNameSpace);
            Type [] paramsType = new Type[0];
            MethodInfo getStackTraceMethod = exType.GetMethod("get_StackTrace",paramsType);
            RMethodRef methodToCall = new RMethodRef(getStackTraceMethod,(RAssemblyDef)code.MethodBody.parent.DeclaringType.Assembly);

            code.Insert(instIndex++,new MSIL.ILMethod(OpCodes.Callvirt,  methodToCall));

            Type consoleType = Type.GetType("System.Console");
            paramsType = new Type[1];
            paramsType[0] = Type.GetType("System.String");
            MethodInfo writeLineMethod = consoleType.GetMethod("WriteLine",paramsType);
            RMethodRef methodToCallWrite = new RMethodRef(writeLineMethod,(RAssemblyDef)code.MethodBody.parent.DeclaringType.Assembly);
            
            code.Insert(instIndex++,MSIL.ILFactory.Call(false,methodToCallWrite));
            code.updateInstructionIndex();
            foreach(MSIL.Instruction currInstr in currTargets)
              code[instIndex].AddTargeter((MSIL.ITargeter)currInstr);

            ((MSIL.ExceptionHandler)exB.catchHandlers[exB.catchHandlers.Count-1]).EndInstruction = code[instIndex];
            if (!AlreadyContains)
              code.MethodBody.excpTable.Add(exB);
            OneExceptionCatchAndLog(exceptionBlocks,code);
            return;
          }
          ++instIndex;
        }
        else
          ++instIndex;
            
      }
    
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="method"></param>
    public override void VisitMethod(RMethodDef method) 
    {
      //check the method body
      if (this.IsXmlVersion)
      {
        StringBuilder methodName = new StringBuilder(method.DeclaringType.NameWithNameSpace);
        methodName.Append(method.Name);
        methodName.Append(method.ReturnType.ReturnType.NameWithNameSpace);
        for (int i = 1; i <= method.ParametersCount; i++)
        {
          if (i==method.ParametersCount)
            methodName.Append(method.GetParameter(i).ParameterType.NameWithNameSpace);
          else
            methodName.Append(method.GetParameter(i).ParameterType.NameWithNameSpace + " ");
        }
        if (this.MethodsAndExceptions.ContainsKey(methodName.ToString()))
          VisitMethodBodyXml((RMethodBase)method);
      }
      else
        VisitMethodBodyCustomAttrib((RMethodBase)method);
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="method"></param>
    public override void VisitConstructor(RConstructorDef method) 
    {
      //Check the method body
      if (this.IsXmlVersion)
      {
        StringBuilder mName = new StringBuilder(method.DeclaringType.NameWithNameSpace);
        mName.Append(method.Name);
        for (int i = 1; i <= method.ParametersCount; i++)
        {
          if (i==method.ParametersCount)
            mName.Append(method.GetParameter(i).ParameterType.NameWithNameSpace);
          else
            mName.Append(method.GetParameter(i).ParameterType.NameWithNameSpace + " ");
        }
        if (this.MethodsAndExceptions.ContainsKey(mName.ToString()))
          VisitMethodBodyXml((RMethodBase)method);
      }
      else
        VisitMethodBodyCustomAttrib((RMethodBase)method);
    }


  }
}
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.