59
Reversed Engineering approach for converting legacy TurboC Application to 64 bit application Abstract The aim of the project is to convert convetional legacy turbo c programs, which are meant to run in 16 bit operating system and can not be executed in modern operating systems to C# programs which can be executed in 64 bit operating system architecture. Many legacuy applications are developed using C. Usch applications find no takers as the Time passes by. Therefore making such programs obsolete and it requires such programs to be rewritten in new environment. Hence it is wise to always develop a tool that can automatically perform such step. In this project we develop a unique mechanism of transforming the c project to c# solutions such that automatically it can get executed. Dept. of Computer Science, HKEPT, Gulbarga Page 1

Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Embed Size (px)

Citation preview

Page 1: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Abstract

The aim of the project is to convert convetional legacy turbo c programs, which are

meant to run in 16 bit operating system and can not be executed in modern operating

systems to C# programs which can be executed in 64 bit operating system architecture.

Many legacuy applications are developed using C. Usch applications find no takers as

the Time passes by. Therefore making such programs obsolete and it requires such

programs to be rewritten in new environment. Hence it is wise to always develop a tool

that can automatically perform such step. In this project we develop a unique

mechanism of transforming the c project to c# solutions such that automatically it can

get executed.

Dept. of Computer Science, HKEPT, Gulbarga Page 1

Page 2: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Chapter 1

Introduction

Reverse engineering is the process of discovering the technological principles of a

human made device, object or system through analysis of its structure, function and

operation. It often involves taking something (e.g., a mechanical device, electronic

component, or software program) apart and analyzing its workings in detail to be used

in maintenance, or to try to make a new device or program that does the same thing

without using or simply duplicating (without understanding) the original.

Reverse engineering has its origins in the analysis of hardware for commercial or

military advantage. The purpose is to deduce design decisions from end products with

little or no additional knowledge about the procedures involved in the original

production. The same techniques are subsequently being researched for application to

legacy software systems, not for industrial or defence ends, but rather to replace

incorrect, incomplete, or otherwise unavailable documentation.

Reverse engineering of software

The term reverse engineering as applied to software means different things to different

people, prompting Chikofsky and Cross to write a paper researching the various uses

and defining a taxonomy. From their paper, they state, "Reverse engineering is the

process of analyzing a subject system to create representations of the system at a

higher level of abstraction."[6] It can also be seen as "going backwards through the

development cycle". In this model, the output of the implementation phase (in source

code form) is reverse-engineered back to the analysis phase, in an inversion of the

traditional waterfall model. Reverse engineering is a process of examination only: the

software system under consideration is not modified (which would make it re-

engineering). Software anti-tamper technology is used to deter both reverse engineering

and re-engineering of proprietary software and software-powered systems. In practice,

two main types of reverse engineering emerge. In the first case, source code is already

available for the software, but higher-level aspects of the program, perhaps poorly

Dept. of Computer Science, HKEPT, Gulbarga Page 2

Page 3: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

documented or documented but no longer valid, are discovered. In the second case,

there is no source code available for the software, and any efforts towards discovering

one possible source code for the software are regarded as reverse engineering. This

second usage of the term is the one most people are familiar with. Reverse engineering

of software can make use of the clean room design technique to avoid copyright

infringement.

On a related note, black box testing in software engineering has a lot in common with

reverse engineering. The tester usually has the API, but their goals are to find bugs and

undocumented features by bashing the product from outside.

Other purposes of reverse engineering include security auditing, removal of copy

protection ("cracking"), circumvention of access restrictions often present in consumer

electronics, customization of embedded systems (such as engine management

systems), in-house repairs or retrofits, enabling of additional features on low-cost

"crippled" hardware (such as some graphics card chip-sets), or even mere satisfaction

of curiosity.

The Certified Reverse Engineering Analyst (CREA) is a certification provided by the

IACRB that certifies candidates are proficient in reverse engineering software.

Objective

The aim of the project is to convert conventional legacy TURBO C programs, which are

meant to run in 16 bit operating system and can not be executed in modern operating

systems to C# programs which can be executed in 64 bit operating system

architecture.

Chapter 2

Dept. of Computer Science, HKEPT, Gulbarga Page 3

Page 4: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

System Analysis

2.1 Existing System

There are several Legacy applications written in languages like C, Pascal, Cobal which

were used successfully over a long time. With the advancement of technology and the

computer hardware and software these applications are abandoned and new

applications are written. As the legacy applications become obsolete, it is difficult to

maintain them due to poor documentation and other issues like cost of maintenance.

Therefore it makes a real sense of extract the underneath business logic from these

applications and extend the logic to the more modern operating environment. There are

several proposed techniques for the same:

1) Rewriting the whole application to the modern environment using manual code

mapping

2) Extracting the underneath business logic of the legacy applications and expose

them over the web using web services.

3) Using inter-process communication to call the business logic from high end

applications and so on.

The approaches can be roughly categorized into two major ways: top down approach

and bottom up approach. In all these approaches the logic becomes rigid. i.e. the

business logic present in the legacy applications are reserved and any changes in the

application needs to be redesigned. But in a real time business scenario, it might be

required that the business logic may be changed or there may be other sub logic that

needs to be associated with them. Now consider the following scenario:

Let us assume for a case study that we have a banking application that supports

transactions like opening an account in the bank, deposit, withdraw and also to view the

transaction. But the new business logic may require third party transfer, i.e. transfer of

the amount from one bank account to another, case based transaction: for example

prohibiting the withdraw in case of insufficient balance or not allowing a certain

transaction if the number of transaction exceeds predefined logic, then using the legacy

bank system to meet the new challenges requires rewriting of the core component or

Dept. of Computer Science, HKEPT, Gulbarga Page 4

Page 5: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

the coding of the legacy application and do not transform the code automatically to suite

the new business logic.

In short the Mapping of legacy applications to the new environment requires following

1) A method to identify key Business logic embedded in the applications

2) Extraction of these logics and expose it to Web through GSOAP which generates

a service description based on the logic exposure

3) Introduction of a middle ware such that any change in the core logic can be

accomplished without having to change the coding

4) Capability of new services written in other languages or coding environment to be

flawlessly integrated to the existing business model.

5) Analysis of the resources in the existing resources such that speed and memory

requirement can be analyzed.

2.2 Proposed System

Existing System is time consuming and do take a lot of tedious effort. Therefore in this

project we develop a simple solution to achieve the prerequisite of the mapping of c

code to c# Code. The features of the codes are:

* It takes a C program as input from the user

* The program is scanned for tokens and the comments are replaced

* The program blocks like loops and variables are identified along with their positions

* Functions along with the return type and parameters are extracted.

* The system implements mapping of some of the common functions like printf and

scanf.

* New code is generated by embedding the entire code inside a namespace and by

including the mapped functions.

Main Modules of the project is

Login.

Dept. of Computer Science, HKEPT, Gulbarga Page 5

Page 6: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Scanning the file.

Dividing the files into token.

Detecting the following:

Single line comments.

Multi line comments.

Function declaration.

Function calling.

Variable, Array, Pointer.

Assignment statements.

Control statements.

Looping statements.

Header file.

Mapping.

2.3 Feasibility Study

It is proposed to establish a proper and secure channel of communication

between the company persons via the internet channel domain. Feasibility of

proposed system is evaluated in three dimensions i.e., Operational feasibility,

Economical feasibility and technical feasibility.

Operational feasibility

Since the user presumed to use this system are qualified so it is believed that

they have proper knowledge of computers and Internet and hence they will be able to

operate it in a fair manner.

Economical feasibility

Since we assume that the network on which our system will operate will support

TCP/IP protocol, hence the software needed are mainly C#.NET Web Server 1.1 and

the Internet Explorer which can be got very easily.

Technical feasibility

Dept. of Computer Science, HKEPT, Gulbarga Page 6

Page 7: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

As mentioned before the organization is assumed to have well equipped

technical persons who are capable of operating the system also have necessary

hardware and can download the software from the internet. Hence proposed solution

is technically feasible.

Chapter 3

System Design

3.1 Flow Chart

Dept. of Computer Science, HKEPT, Gulbarga Page 7

Start

Page 8: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

3.2 Class Diagram

Dept. of Computer Science, HKEPT, Gulbarga Page 8

Read a Program

Strip Comments

Remove Blank Space

Extract variables, Arrays and Pointers along with their initialized values

Extract Functions

Mapping

Stop

Page 9: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

CHAPTER 4 

Dept. of Computer Science, HKEPT, Gulbarga Page 9

Page 10: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

System Requirement

Software and Hardware Requirement

4.1 Software Requirement

1) Operating System :Windows 7,Windows Vista

2) Front End:Visual Studio 2010(Editor)

3) Language:Visual C#2010

4.2 Hardware Requirement

1)Processor: Dual Core,Core 2 Duo

2)Hard Disk:80 GB

3)RAM:1 GB

Chapter 5

Dept. of Computer Science, HKEPT, Gulbarga Page 10

Page 11: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Source Code

string[] progA ;

List<ProgramBlocks> EachToken;

void ProgScan()

{

OpenFileDialog ofd = new OpenFileDialog();

DialogResult dr = ofd.ShowDialog();

if (dr.Equals(DialogResult.OK))

{

if (ofd.FileName != null)

{

progA = File.ReadAllLines(ofd.FileName);

foreach (string s in progA)

{

lstProgram.Items.Add(s);

}

}

}

}

private void button1_Click(object sender, EventArgs e)

{

lstProgram.Items.Clear();

ProgScan();

}

private void button2_Click(object sender, EventArgs e)

{

Dept. of Computer Science, HKEPT, Gulbarga Page 11

Page 12: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Analyze anz = new Analyze();

anz.Lines = progA;

anz.CommentStrip();

anz.CommentStripMultiLine();

progA = anz.Lines;

lstProgram.Items.Clear();

for (int i = 0; i < progA.Length; i++)

{

lstProgram.Items.Add(progA[i]);

}

this.Text = anz.msg;

}

private void button3_Click(object sender, EventArgs e)

{

Analyze anz = new Analyze();

anz.Lines = progA;

System.Collections.ArrayList al = anz.RemoveBlank();

lstProgram.Items.Clear();

progA = new string[al.Count];

for (int i = 0; i < al.Count; i++)

{

lstProgram.Items.Add(al[i].ToString());

progA[i] = al[i].ToString();

}

}

private void button4_Click(object sender, EventArgs e)

{

Analyze anz = new Analyze();

Dept. of Computer Science, HKEPT, Gulbarga Page 12

Page 13: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

anz.Lines = progA;

List<ProgramBlocks> pinclude = new List<ProgramBlocks>();

pinclude = anz.SearchInclude();

lstInclude.Items.Clear();

for (int i = 0; i < pinclude.Count; i++)

{

EachToken.Add(pinclude[i]);

lstInclude.Items.Add(pinclude[i].Contents);

}

}

private void button5_Click(object sender, EventArgs e)

{

Func<string, bool> SearchKw =

delegate(string pat)

{

ProgramBlocks pb = new ProgramBlocks();

string[] kw = pb.DataTypeString;

foreach (string s in kw)

{

if (s == pat)

{

return true;

}

}

return false;

};

lvVariable.Items.Clear();

ProgramBlocks pgm=new ProgramBlocks();

SearchPatternsDelegate spd = new SearchPatternsDelegate(pgm.MainSearch);

List<ProgramBlocks> pinclude = new List<ProgramBlocks>();

Dept. of Computer Science, HKEPT, Gulbarga Page 13

Page 14: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

bool anyValue;

pinclude = spd(progA, pgm.DataTypeString,out anyValue);

if (anyValue)

{

for (int i = 0; i < pinclude.Count; i++)

{

if (pinclude[i].Contents.Length > 0 &&

(SearchKw(pinclude[i].Contents)==false))

{

if (pinclude[i].Type == TokTypes.ARRAY)

{

EachToken.Add(pinclude[i]);

ListViewItem lvm = new ListViewItem(new string[]

{ pinclude[i].Contents, pinclude[i].VariableDataType.ToString(),

pinclude[i].StartLine.ToString(), pinclude[i].InitialValue,

pinclude[i].ArraySize.ToString() });

lvm.Tag = new string[] { pinclude[i].Contents,

pinclude[i].VariableDataType.ToString(), pinclude[i].StartLine.ToString(),

pinclude[i].InitialValue, pinclude[i].ArraySize.ToString() };

lvArray.Items.Add(lvm);

}

else if (pinclude[i].Type != TokTypes.POINTER)

{

EachToken.Add(pinclude[i]);

ListViewItem lvm = new ListViewItem(new string[]

{ pinclude[i].Contents, pinclude[i].VariableDataType.ToString(),

pinclude[i].StartLine.ToString(), pinclude[i].InitialValue });

Dept. of Computer Science, HKEPT, Gulbarga Page 14

Page 15: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

lvm.Tag = new string[] { pinclude[i].Contents,

pinclude[i].VariableDataType.ToString(), pinclude[i].StartLine.ToString(),

pinclude[i].InitialValue };

lvVariable.Items.Add(lvm);

}

else

{

EachToken.Add(pinclude[i]);

ListViewItem lvm = new ListViewItem(new string[]

{ pinclude[i].Contents, pinclude[i].VariableDataType.ToString(),

pinclude[i].StartLine.ToString(), pinclude[i].InitialValue });

lvm.Tag = new string[] { pinclude[i].Contents,

pinclude[i].VariableDataType.ToString(), pinclude[i].StartLine.ToString(),

pinclude[i].InitialValue };

lvPointers.Items.Add(lvm);

}

}

}

}

}

private void button6_Click(object sender, EventArgs e)

{

Analyze anz = new Analyze();

anz.Lines = progA;

List<ProgramBlocks> pinclude = anz.LoopStructure();

lvLoops.Items.Clear();

Dept. of Computer Science, HKEPT, Gulbarga Page 15

Page 16: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

for (int i = 0; i < pinclude.Count; i++)

{

EachToken.Add(pinclude[i]);

ListViewItem lvm = new ListViewItem(new string[]

{ pinclude[i].Contents,pinclude[i].StartLine.ToString(), pinclude[i].EndLine.ToString() });

lvm.Tag = new string[] { pinclude[i].Contents, pinclude[i].StartLine.ToString(),

pinclude[i].EndLine.ToString() } ;

lvLoops.Items.Add(lvm);

}

}

private void button7_Click(object sender, EventArgs e)

{

Analyze anz = new Analyze();

anz.Lines = this.progA;

List<ProgramBlocks> functions=anz.Functions();

Func<List<DataTypes>, string> Arguments =

delegate(List<DataTypes>args)

{

string s = "";

try

{

foreach (var f in args)

{

s = s + " "+f.ToString();

}

}

catch (Exception ex) { }

return s;

Dept. of Computer Science, HKEPT, Gulbarga Page 16

Page 17: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

};

foreach (ProgramBlocks p in functions)

{

try

{

MessageBox.Show("G**"+p.Arguments[0].ToString());

}

catch (Exception ex) { }

ListViewItem lvm = new ListViewItem(new string[]

{p.Contents,p.StartLine.ToString(),p.EndLine.ToString(),p.Return.ToString(),

Arguments(p.Arguments)});

lvm.Tag = new string[] { p.Contents, p.StartLine.ToString(),

p.EndLine.ToString(), p.Return.ToString(), Arguments(p.Arguments) };

lvFunctions.Items.Add(lvm);

}

}

private void button8_Click(object sender, EventArgs e)

{

Analyze anz = new Analyze();

anz.Lines = this.progA;

string [] assgn=anz.Assignments();

foreach (string s in assgn)

{

lstAssgn.Items.Add(s);

}

}

private void button9_Click(object sender, EventArgs e)

{

Dept. of Computer Science, HKEPT, Gulbarga Page 17

Page 18: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Analyze anz = new Analyze();

anz.Lines = this.progA;

List<string>fc=anz.FunctionCalls();

foreach (string s in fc)

{

lstFunctionCalls.Items.Add(s);

}

}

void AddCSharpHeaders()

{

lstConverted.Items.Add("using System;");

lstConverted.Items.Add("using System.Collections;");

lstConverted.Items.Add("using System.Collections.Generic;");

lstConverted.Items.Add("using System.Text;");

}

string FindArrayLine(int ln)

{

string form = "";

for (int j = 0; j < lvArray.Items.Count; j++)

{

string [] line = (string [])lvArray.Items[j].Tag;

if (int.Parse(line[2]) == ln)

{

string[] an = line[0].Split(new char[] { '[' });

form = line[1].ToLower() + " []" + an[0] + "=new " + line[1].ToLower() + "[" +

line[4] + "];";

}

}

Dept. of Computer Science, HKEPT, Gulbarga Page 18

Page 19: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

return form;

}

string FindFunction(int ln)

{

string form = "";

for (int j = 0; j < lvFunctions.Items.Count; j++)

{

string[] line = (string[])lvFunctions.Items[j].Tag;

if (int.Parse(line[1]) == ln)

{

form = "static ";

}

}

return form;

}

string FindPointers(int ln)

{

string form = "";

for (int j = 0; j < lvPointers.Items.Count; j++)

{

string[] line = (string[])lvPointers.Items[j].Tag;

if (int.Parse(line[2]) == ln)

{

form = "ref " + line[1].ToLower() + " " + line[0].Replace('*', ' ');

if (line[3]!=null)

{

form = form + "=" + line[3] + ";";

Dept. of Computer Science, HKEPT, Gulbarga Page 19

Page 20: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

}

else

{

form = form + ";";

}

}

}

form = "";

return form;

}

private void button10_Click(object sender, EventArgs e)

{

//lstConverted.Items.Clear();

int i = Analyze.IncludeEnds+1;

AddCSharpHeaders();

lstConverted.Items.Add("public class SampleClass{");

int ci=lstConverted.Items.Count-1;

for (; i < Analyze.MainLocation; i++)

{

lstConverted.Items.Add(lstProgram.Items[i]);

}

lstConverted.Items.Add("public static void Main()");

i++;

for (; i < lstProgram.Items.Count; i++)

{

string form = FindArrayLine(i);

if (form.Length < 2)

Dept. of Computer Science, HKEPT, Gulbarga Page 20

Page 21: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

{

string form1 = FindFunction(i);

if (form1.Length > 2)

{

MessageBox.Show(form1 + lstProgram.Items[i].ToString().Replace("&",

"out "));

lstConverted.Items.Add(form1 +

lstProgram.Items[i].ToString().Replace("&", "out "));

}

else

{

string form2 = FindPointers(i);

if (form2.Length > 1)

{

lstConverted.Items.Add(form2);

}

else

{

lstConverted.Items.Add(lstProgram.Items[i].ToString().Replace("&",

"out "));

}

}

}

else

{

lstConverted.Items.Add(form);

}

Dept. of Computer Science, HKEPT, Gulbarga Page 21

Page 22: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

}

string[] print = File.ReadAllLines("printf.txt");

foreach (string s in print)

{

lstConverted.Items.Add(s);

}

print = File.ReadAllLines("scanf.txt");

foreach (string s in print)

{

lstConverted.Items.Add(s);

}

lstConverted.Items.Add("}");

string[] conv = new string[lstConverted.Items.Count];

for (int j = 0; j < lstConverted.Items.Count; j++)

{

conv[j] = lstConverted.Items[j].ToString();

}

for (int j = 0; j < lstConverted.Items.Count; j++)

{

lstConverted.Items[j] = lstConverted.Items[j].ToString().Replace("*", " ");

}

File.WriteAllLines("converted.cs", conv);

}

private void btnClose_Click(object sender, EventArgs e)

{

Dept. of Computer Science, HKEPT, Gulbarga Page 22

Page 23: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

DialogResult dr = MessageBox.Show("Are you sure you want to close the

application", "Closing Message", MessageBoxButtons.YesNo,

MessageBoxIcon.Question);

if (dr.Equals(DialogResult.Yes))

{

Application.Exit();

}

else

{

return;

}

}

namespace HunkMatrix

{

class Analyze

{

public string[] Lines;

public string msg;

public Analyze()

{

}

//<summery>

/// <summary>

/// This function removes single line comment

/// </summary>

public void CommentStrip()

{

int i = 0;

while (i < Lines.Length)

{

Dept. of Computer Science, HKEPT, Gulbarga Page 23

Page 24: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

try

{

#region single line Comment

bool SingleProcessed=false;

// check if the comment is at the begining or not

// If line has some code then comment, following will be executed

string[] nn = Lines[i].Split(new string[] { "//" }, StringSplitOptions.None);

if (nn.Length > 0)

{

SingleProcessed=true;

Lines[i] = nn[0];

}

#endregion

}

catch (Exception ex)

{

}

i++;

}

}

/// <summary>

/// This function scans for /* and */ and removes the lines

Dept. of Computer Science, HKEPT, Gulbarga Page 24

Page 25: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

/// </summary>

public void CommentStripMultiLine()

{

int i = 0;

while (i < Lines.Length)

{

try

{

#region multi line comment

if (true)

{

char[] nn1 = Lines[i].ToCharArray();

bool commentFound = false;

for (int t = 0; t < nn1.Length - 1; t++)

{

if (nn1[t] == '/' && nn1[t + 1] == '*')

{

commentFound = true;

}

}

if (commentFound)

{

msg = msg + "comment @" + i.ToString();

bool CommentOver = false;

Dept. of Computer Science, HKEPT, Gulbarga Page 25

Page 26: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

int start = i;

i++;

while (!CommentOver)

{

nn1 = Lines[i].ToCharArray();

for (int t = 0; t < nn1.Length - 1; t++)

{

if (nn1[t] == '*' && nn1[t + 1] == '/')

{

CommentOver = true;

i++;

break;

}

}

i++;

}

i--;

msg = msg + " END LINE=" + i.ToString();

for (int j = start; j < i ; j++)

{

Lines[j] = "";

}

}

}

#endregion

}

catch (Exception ex)

{

}

i++;

}

Dept. of Computer Science, HKEPT, Gulbarga Page 26

Page 27: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

}

/// <summary>

/// Removes the blank codes by comparing each line with "" and removing them

/// </summary>

/// <returns></returns>

public ArrayList RemoveBlank()

{

ArrayList al = new ArrayList();

foreach (string s in Lines)

{

if (s != "")

{

al.Add(s);

}

}

return al;

}

public static int IncludeEnds=0;

/// <summary>

/// It searches for the include statement

/// 1. the reule is: it searches for #include statement, then

/// 2. from < to > is extracted as Contents

/// 3. Type=INCLUDE, start and end Line are same, the line where it is found

/// </summary>

public List<ProgramBlocks> SearchInclude()

{

Dept. of Computer Science, HKEPT, Gulbarga Page 27

Page 28: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

List<ProgramBlocks> Nl=new List<ProgramBlocks>();

int i = 0;

ProgramBlocks p = new ProgramBlocks();

while (i < Lines.Length)

{

if (Lines[i].Contains("#include"))

{

p = new ProgramBlocks();

string[] ss = Lines[i].Split(new char[] { '<','>'});

p.Contents = ss[1];

p.StartLine = p.EndLine = i;

p.Type = TokTypes.INCLUDE;

Nl.Add(p);

IncludeEnds = i;

}

i++;

}

return Nl;

}

/// <summary>

/// this program extracts the loops and their inner values

/// first divide the program into an array of characters

/// Loop in the characters, search for {

/// push the data in the stack

/// search for } pop from stack

/// </summary>

public List<ProgramBlocks> LoopStructure()

{

Stack<ControlBlock> st = new Stack<ControlBlock>();

Dept. of Computer Science, HKEPT, Gulbarga Page 28

Page 29: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

ControlBlock cb = new ControlBlock();

List<ProgramBlocks> AllLoops = new List<ProgramBlocks>();

ProgramBlocks pb = new ProgramBlocks();

string total_pgm="";

foreach (string s in Lines)

{

total_pgm = total_pgm + s+"\n";

}

char[] PROGTOK = total_pgm.ToCharArray();

string CUR="", PREV = "";

int ind = 0;

int last_ind = -1;

int line_count = 0;

bool found = false;

int start=-1;

int end=-1;

char ch=' ';

while (ind < PROGTOK.Length)

{

ch=PROGTOK[ind];

if(ch=='\n')

{

line_count++;

PREV = "";

// CUR = "";

last_ind = ind;

CUR = "";

}

//CONDITION FOR CHECKING IF LOOP

if((ch=='i')&&(PROGTOK[ind+1]=='f')&&(PROGTOK[ind+2]=='('))

Dept. of Computer Science, HKEPT, Gulbarga Page 29

Page 30: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

{

start=line_count;

ind=ind+2;

string s="";

#region if found bypass whole stuud and get hold of opening brace

while(ch!='{')

{

ind++;

ch=PROGTOK[ind];

if(ch=='\n')

{

line_count++;

}

else

{

s=s+ch.ToString();

}

}

#endregion

Chapter 6

Dept. of Computer Science, HKEPT, Gulbarga Page 30

Page 31: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Implementation

6.1 C#2010 programming language

C# is Microsoft’s latest object oriented programming language developed for .NET platform

& .NET is Microsoft’s latest platform technology for creating web services. C# is a C++ based

language & was developed to provide portability for distributed applications over network &

Internet. Application development in .NET platform can be done in multiple languages including

C#, C++ & visual basic. Programmers developed in all these languages are complied to

Microsoft’s intermediate language (IL) & executed within common language run time (CLR) .We

explain the core elements of .NET & how web applications are developed & run with this

technology. NET is not a programming language it is a virtual machine technology (similar to

Java virtual machine technology) with a framework that provides capability to run a verity of web

applications. The .NET framework class library provides set of classes that provides essential

functionality for applications build within the .NET environment. Web functionality, XML support,

database support, threading & distributed computing support is provided by the .NET framework

class library. All .NET code is translated to Microsoft intermediate language & run with

CLR .CLR is similar to Java virtual machine (JVM) .The IL code is language independent &

similar to Java byte code .A single .NET application may consist of several different

languages .Two very important features of CLR are language interoperability & language

independence.

Introduction to C#

C# is a modern, object oriented language that enables programmers to quickly build a wide

range of applications for the new Microsoft .NET platform, which provides tools & services that

fully exploit both computing & communication. Because of its elegant object oriented design .C#

is a great choice for architecting a wide range of components from high level business objects to

system level applications using simple C# language constructs, these component can be

converted into XML web services, allowing them to be invoked across the internet, from any

language running on any operating system. More than any thing else, C# is designed to bring

rapid development to the C++ programmer without sacrificing the power & control that have

been a hallmark of C & C++. Because of this heritage C# has a high degree of fidelity with C &

C++. Developers familiar with these languages can quickly become productive in C#

C# Features

Dept. of Computer Science, HKEPT, Gulbarga Page 31

Page 32: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

C# is the new language with the power of C++ & the slickness of visual basic. It cleans

up many of the syntactic peculiarities of C++ without diluting much of its flavor (thereby

enabling C++ developers to transition to it with little difficulty). And its superiority over

VB6 in facilitating powerful OO implementation is without question. C# with clean OO

syntax & large class library (in conjunction with .NET & the base class libraries) could

be the ‘most productive mainstream language’ & it is an ECMA standard language that

offers the potential of being available across many platform .For the serious developer

wanting Microsoft’s most productive & mainstream .NET language, C# is the choice.

Properties:

Properties will be a familiar concept to Delphi & Visual basic users. The motivation is for the

language to formalize the concept of getter/ setter methods, which is an extensively used

pattern, particularly in RAD (Rapid Application developments) tools.

This is a typical code you must write in Java or C++:

Outsize (get size () +1);

Label.getfont (). Set bold (true);

The same code you would rite like this in C#:

Outsize;

Label.font.bold=true;

The code is immediately more readable by those who are using foot & label . There is similar

simplicity when implementing properties:

Java/C++ :

Public int get size (){

Return size;

}

public void set size(int value){

Size=value;

Dept. of Computer Science, HKEPT, Gulbarga Page 32

Page 33: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

}

C#:

Public int size {

Get {return size;

}

Set {size = value;

}

}

Particularly for read/write properties, C# provides a cleaner way of handling this concept .the

relationship between a get & set method is inherent in C#, while has to be maintained in Java or

C++. There are many benefits of this approach. It encourages programmers to think in terms of

properties, whether that property is more natural as read/write Vs read only, or whether it really

a shouldn’t be a property at all. If you wish to change the name of your property, you only have

one place to look (I’ve seen getters & setters several lines away from each other). Comments

only have to be made once, & won’t get out of sync with each other .it is feasible that an IDE

could help out here (& in fact I suggest they do), but one should remember an essential principle

in programming is to try to make abstractions model our problem well space well. A language,

which supports properties, will reap the benefits of that better abstraction.

Indexers :

C# provides indexers allow objects to be treated like array, except that like properties, each

element is exposed with a get and/ or set method.

Public class Skyscraper

{

Story [] stories;

Public story this [int index] {

Get {

Dept. of Computer Science, HKEPT, Gulbarga Page 33

Page 34: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Return stories [index];

}

Set {

if (value !=null ) {

Stories [index]=value;

}

}

}

Skyscraper empire State = new Skyscraper (…);

Empire State [102] = new story (“The top one”…);

Pointer arithmetic:

Pointer arithmetic can be performed in C# within methods marked with the unsafe modifier.

When pointer point to garbage collected objects, the complier enforces the use of fixed word to

pin the object. This is because garbage collectors relay on moving objects around to reclaim

memory, but if this happens when you are dealing with raw pointers you will be pointing to

garbage. The choice of the word “unsafe “will be chosen since it discourages developers from

using pointers unless they really need to.

Rectangular Arrays:

C# allows both jagged & rectangular arrays to be created. Jagged arrays are pretty much the

same as Java arrays. Rectangular arrays allow a more efficient and accurate representation for

certain problems .An example of such an array would be:

Int [,] array = new int [3, 4, 5];

Int [1, 1, 1] =5;

Using jagged arrays;

Int [][][] array=new int [3][4][5];

Dept. of Computer Science, HKEPT, Gulbarga Page 34

Page 35: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Int [1][1][1];

In combination with struts, C# can provide a level of efficiency making it a good choice for areas

such as graphics & mathematics.

A sample C# program:

Hello world

File Hello .Cs

Using system;

Class Hello {

Static void Main (){

Console. Write Line (“Hello world “);

}

}

Uses the namespace System

Entry point must be called Main

O/p goes to the console

File name & class name need not be identical

Compilation (in the console window)

Csc Hellow .cs

Execution

Hello

C# Advantages:

XML documentation generated from source code comments. (This is coming in

VB.NET with Whidbey (the code name for the next version of Visual Studio &. NET),

and there are tools which will do it with existing VB.NET code already.)

Dept. of Computer Science, HKEPT, Gulbarga Page 35

Page 36: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Operator overloading = again, coming to VB.NET in Whidbey.

Language support for unsigned types (you can use them from VB.NET, but they

aren’t in the language itself).

Again support for these is coming to VB.NET in Whidbey.

The using statement, which makes unmanaged resource disposal simple

Explicit interface in a base class can be re implemented separately in a derived

class. Arguably this makes the class harder to understand in the same way that

member hiding normally does.

C# Applications:

Builder design pattern: The builder pattern allows a client object to construct a complex

object by specifying only its type & content. The client is shielded from the details of the

objects construction.

Remoting in C#.

C# component based development.

Chapter 7

Results

Dept. of Computer Science, HKEPT, Gulbarga Page 36

Page 37: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Here we scaned turbo c program

Here we stripping single line and multiline comment

Dept. of Computer Science, HKEPT, Gulbarga Page 37

Page 38: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

After removing the blank we detect the include statements

Dept. of Computer Science, HKEPT, Gulbarga Page 38

Page 39: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Here we convert Turbo C Program to C Sharp Program

Dept. of Computer Science, HKEPT, Gulbarga Page 39

Page 40: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Run the CSharp program in the Visual Studio 2010 Command Prompt

Dept. of Computer Science, HKEPT, Gulbarga Page 40

Page 41: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Here we compiled the C Sharp program

Dept. of Computer Science, HKEPT, Gulbarga Page 41

Page 42: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Run it and we get the proper output according to the proper input

Dept. of Computer Science, HKEPT, Gulbarga Page 42

Page 43: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Chapter 8

Advantage of the Project

Advantage of the Project

Reasons for reverse engineering:

Interoperability.

Lost documentation: Reverse engineering often is done because the

documentation of a particular device has been lost (or was never written), and

the person who built it is no longer available. Integrated circuits often seem to

have been designed on obsolete, proprietary systems, which means that the only

way to incorporate the functionality into new technology is to reverse-engineer

the existing chip and then re-design it.

Product analysis. To examine how a product works, what components it consists

of, estimate costs, and identify potential patent infringement.

Digital update/correction. To update the digital version (e.g. CAD model) of an

object to match an "as-built" condition.

Security auditing.

Acquiring sensitive data by disassembling and analysing the design of a system

component.

Military or commercial espionage. Learning about an enemy's or competitor's

latest research by stealing or capturing a prototype and dismantling it.

Removal of copy protection, circumvention of access restrictions.

Creation of unlicensed/unapproved duplicates.

Materials harvesting, sorting, or scrapping.

Academic/learning purposes.

Curiosity.

Competitive technical intelligence (understand what your competitor is actually

doing versus what they say they are doing).

Dept. of Computer Science, HKEPT, Gulbarga Page 43

Page 44: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Learning: learn from others' mistakes. Do not make the same mistakes that

others have already made and subsequently corrected.

Dept. of Computer Science, HKEPT, Gulbarga Page 44

Page 45: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

Chapter 9

Conclusion and Future Scope

No tool box is commercially available that can transfer the c code to c# code. In large

organizations such operations are manually performed. In this project we have

developed a unique mechanism of automatically converting the c code to c# code by

first extracting the program blocks and then by mapping the code into new coding

environment. The project is tested with different source files and the system generates

proper output for arrays and functions. We did not map the pointers as it requires further

complicated system. The project can be improved by incorporating a pointer conversion

Bibliography

Dept. of Computer Science, HKEPT, Gulbarga Page 45

Page 46: Reversed Engineering Approach for Converting Legacy TurboC Application to 64 Bit Application_final Report

Reversed Engineering approach for converting legacy TurboC Application to 64 bit application

C# and .Net platform by Andrew Troelsen.

Inside C# by Tom Archer.

Fundamentals of database Systems by Ramez Elmasri ans S. B. Navathe

Software Engineering-Roger S. Pressman

An Introduction to database system –C.J.Date

The Unified modeling language user guide-G.Booch,J.Rambough and I

Jacobson.

Dept. of Computer Science, HKEPT, Gulbarga Page 46