Sunday, June 29, 2008

Detours

Microsoft's Research team maintains a project that allows you to intercept any function call. The library does this by injecting code into the memory of that process. You then have the ability to do whatever you want and if you choose pass the call through. This can be very useful for instrumentation for example.

Here's a very simple example that isn't of much use since everything is in the same process, but it shows how I can intercept the call to Window's sleep function.


//////////////////////////////////////////////////////////////////////////////
//
// Detours Test Program (simple.cpp of simple.dll)
//
// Microsoft Research Detours Package, Version 2.1.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This DLL will detour the Windows Sleep API so that TimedSleep function
// gets called instead. TimedSleep records the before and after times, and
// calls the real Sleep API through the TrueSleep function pointer.
//
#include
#include
#include "detours.h"

static LONG dwSlept = 0;
static VOID (WINAPI * TrueSleep)(DWORD dwMilliseconds) = Sleep;

VOID WINAPI TimedSleep(DWORD dwMilliseconds)
{
DWORD dwBeg = GetTickCount();
TrueSleep(dwMilliseconds);
DWORD dwEnd = GetTickCount();

InterlockedExchangeAdd(&dwSlept, 3636);
}

//BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
int __cdecl main(int argc, char ** argv)
{
LONG error;


printf("simple.dll: Starting.\n");
fflush(stdout);

DetourRestoreAfterWith();

DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)TrueSleep, TimedSleep);
error = DetourTransactionCommit();

if (error == NO_ERROR) {
printf("dwslept %d",dwSlept);
printf("simple.dll: Detoured Sleep().\n");
printf("sleep5.exe: Starting.\n");

Sleep(5000);

printf("sleep5.exe: Done sleeping.\n");
printf("dwslept %d",dwSlept);
}
else {
printf("simple.dll: Error detouring Sleep(): %d\n", error);
}


DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)TrueSleep, TimedSleep);
error = DetourTransactionCommit();

printf("simple.dll: Removed Sleep() (result=%d), slept %d ticks.\n",
error, dwSlept);
fflush(stdout);

return 0;
}

//
///////////////////////////////////////////////////////////////// End of File.



In order for this to work you first need to download the detours package from http://research.microsoft.com/sn/detours/

Compile the source as a lib and link to it.

Give it a shot its pretty cool!

Enjoy...

c# using statement

The C# 'using' statement provides a convenient syntax that ensures the correct use of IDisposable objects.

Example:


using (BlackJackForm blackjackform = new BlackJackForm())
{
Hide();
blackjackform.ShowDialog();
Show();
}


The above is the equivalent of the following more verbose code:


BlackJackForm blackjackform = new BlackJackForm()
try {
Hide();
blackjackform.ShowDialog();
Show();
}
finally {
blackjackform.Dispose();
}


The using statement only works with items implementing the IDisposable interface.

Friday, June 27, 2008

C++ War Card Game

While reading Data Structures in C++: Using the Standard Template Library (STL)

The author brought up the War card game. I thought it would be interesting challenge to see how fast I could create the game. So just for fun here is the source in case anyone is interested.

The rules are simple. Each player has half the deck they flip over the top card each time. Whichever card is higher (2 being lowest Ace being the highest) that person gets both cards. On tie each player flips over three cards and the fourth determines who wins everything.



#include <iostream>
#include <vector>
#include <queue>
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
using namespace std;
struct Card {
Card(int value) {
this->value = value;
}
int getValue() {
return value;
}
private:
int value;
};
struct Player{
queue cards;
};
struct Deck {
vector cards;
Deck() {
for(int i=1;i<14;++i) j="1;j<5;++j)" j="0;j<10;++j)" i="0;i< cards.size();++i)" int="" r="(rand()" card="" temp="cards[i];" struct="" game="" void="" deck="" player="" cout=""><< "dealing" << i="0;i<<> undecided;
int count =0;
while(a.cards.size() >0 && b.cards.size() >0) {
cout << ++count << ": A cards: " << acard =" a.cards.front();" bcard =" b.cards.front();"> bCard.getValue()) {
int size = undecided.size();
for(int i=0;i< size =" undecided.size();" i="0;i< size;++i)" else="" were="" in="" take="" three="" more="" from="" each="" player="" int="" i="0;i<3;++i)" if=""> 0 ) {
undecided.push(a.cards.front());
a.cards.pop();
}
if (b.cards.size() > 0 ) {
undecided.push(b.cards.front());
b.cards.pop();
}
}
}
}
}
};
int main() {
Game g;
g.start();
return 0;
}

C++ get random number

#include // For time()
#include // For srand() and rand()
void foo() {
srand(time(0)); // Initialize random number generator.
int r = (rand() % 10) + 1;
}

c++ std::find algorithm example

C++ standard library has many useful features. One of which is the std::find algorithm.


Here is a simple example:
#include <iostream>
#include <algorithm>

int main() {
int data[100];
data[89] = 7;
int * where = std::find(data,data+100,7);
std::cout << *where << std::endl;
}


This will output '7'. The interesting part is the algorithm will work with any data structure not just arrays.

#include <iostream>
#include <algorithm>
#include <list>
int main() {
std::list<int> data;
data.push_back(3);
data.push_back(7);
data.push_back(9);
std::list<int>::iterator where = std::find(data.begin(),data.end(),7);
std::cout << *where << std::endl;
}


For more information I recommend the following book:
Data Structures in C++: Using the Standard Template Library (STL)

Thursday, June 26, 2008

Using java as a shell language

I've been trying to find what shell language I like better as the 'glue' needed between real applications. I've used perl a lot in the past, experimenting with python and ruby now. But I don't want an interpreted language. I really want a compile time language.

So today I figured why not use java.

The main problem is that most scripts are easy to modify and don't require compiling. For example you start your python script with

#!/usr/bin/python

It would be nice if I could do the same for Java. Well now you can.

Introducing the 'JavaLoader'


import java.io.*;
class JavaLoader {
public static void main(String[] args) throws Exception {
String pwd = System.getProperty("user.dir");
System.out.println( "Received argument " + args[0]);
String javaFile = args[0];
if (javaFile.startsWith("./"))
javaFile = javaFile.replace("./","");

// Find class file
String className = (javaFile.split("\\."))[0];

// Comment out the shebang line so we can compile it.
RandomAccessFile file = new RandomAccessFile(javaFile, "rw");
file.seek(0);
file.write("//".getBytes());
file.close();

// Compile it
executeCommand(String.format("javac -cp $CLASSPATH:%s %s",pwd,javaFile));

//Run
executeCommand(String.format("java -cp $CLASSPATH:%s %s",pwd,className));

// Put back #! line.
file = new RandomAccessFile(javaFile, "rw");
file.seek(0);
file.write("#!".getBytes());
file.close();
}
public static void executeCommand(String cmd) throws Exception {
System.out.println("Executing command: [" + cmd + "]");
Process p = Runtime.getRuntime().exec(cmd);
printStream(p.getInputStream());
printStream(p.getErrorStream());
}
public static void printStream(InputStream is) throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
}


By using this you can now write a script like so:


#!/usr/bin/java JavaLoader

class my {

public static void main(String[] args) {
System.out.println ("my: from here I am in java");
}
}


To execute you first need to make sure the JavaLoader is compiled and in your classpath. Then execute your script. My script was called my.java so I did:


[root@pioneer local]# ./my.java
Received argument ./my.java
Executing command: [javac -cp $CLASSPATH:/usr/local my.java]
Executing command: [java -cp $CLASSPATH:/usr/local my]
my: from here I am in java


This is great no more settling, I get to use Java everywhere now!

Start cygwin's x server without access control

To start cygwin's x server without access control use the following command from cygwin

xwin -multiwindow -ac &

You don't need multiwindow but I like it. The -ac is what disables access control