Vlad Ioan Topan

My playground

Karaoke songs & free player

with one comment

Karaoke is one of my more enjoyable means of killing time (and music itself, some might argue, as I’m a rather untalented singer). A while ago I’ve found a free karaoke player (far from perfect, as it BSODs my new laptop, but pretty usable otherwise), which together with some fun .kar songs I’ve gathered over time make for a ~20 MB pack of (potentially) great fun.

The player – Karafun

You can get a player called Karafun here (if you know of any other, preferably better, free karaoke player, lemme know). You don’t have to buy the songs from that site too; there are plenty of free karaoke (.kar) songs on the web. It’s also portable, meaning you can copy the installed folder (c:\Program Files\KaraFun by default) on a USB stick and carry it around.

The songs (.kar files)

The most commonly used song files for karaoke are .kar files, and there’s plenty of them online. The .kar format, for the inquisitive(ly?)-natured, is a MIDI (instrumental music) file with synchronized lyrics strapped on. This is relevant because some of the files you’ll find won’t have the .kar extension, but a .mid extension; they most likely will still work (the lyrics could be missing from such files, so try playing them to make sure they’re there).

Google for “free kar songs” or something similar and you’ll find many searchable databases of such songs. To find the .kar file of a particular song, google for it’s name + kar (e.g.: “sinatra my way kar”). In Opera, clicking links pointing to .kar files will play them instead of prompting to download them, so simply right click & “Save Linked Content As” to save them.

I’ve found a nice and well-organized collection on karaokebash.com, and a good .kar search engine on vanbasco.com.

Personal selection

As I’ve already mentioned, I’ve put together a collection of .kar songs, split in two “tiers”: “the most frequently played” and “other good karaoke songs”, plus a huge folder called “unsorted” which occasionally feeds the two categories above when I have enough time to plow through the pile.

Songs I (and my friends) most often sing along to (download link the whole pack from easy-share.com or wikiupload.com):
ABBA – Chiquitita.kar, ABBA – Fernando.kar, ABBA – Thank You For The Music.kar, Ace of Base – All That She Wants.kar, Aerosmith – Cryin’.kar, Afroman – Cause I Got High.kar, Andrea Bocelli – Con te partiro.kar, Andrea Bocelli – Vivo per lei.kar, Animals – House Of The Rising Sun.kar, Aqua – Barbie Girl.kar, Bangles – Manic monday.kar, Beach Boys – Kokomo.kar, Beatles – Hey Jude.kar, Beatles – Yesterday.kar, Bee Gees – Tragedy.kar, Berlin – Take My Breath Away.kar, Billy Joel – We Didn’t Start the Fire.kar, Blondie – Heart of Glass.kar, Bobby McFerrin – Don’t Worry, Be Happy.kar, Bon Jovi – Always.kar, Bon Jovi – Bed of Roses.kar, Bon Jovi – Blaze Of Glory.kar, Bon Jovi – Livin’ On A Prayer.kar, Bon Jovi – This Aint a Love Song.kar, Bonnie Tyler – It’s a Heartache.kar, Bonnie Tyler – Sometimes when we touch.kar, Bonnie Tyler – Total Eclipse Of The Heart.kar, Boyzone – Father and Son.kar, Boyzone – Words.kar, Brian May – Too much love will kill you.kar, Bryan Adams – Cloud number 9.kar, Bryan Adams – Everything I do, I do it for you.kar, Celine Dion – Beauty And The Beast.kar, Coolio – Gangstas Paradise.kar, Cranberries – Zombie.kar, Crash Test Dummies – Mmm.kar, Dean Martin – Sway.kar, Dean Martin – That’s Amore.kar, Disney’s Jungle Book (Terry Gilkyson) – Bare Necessities.kar, Don McLean – American Pie.kar, Eagles – Hotel California.kar, Eddy Grant – Gimme Hope Joanna.kar, Edith Piaf – Ne me quitte pas.kar, Elvis Presley – Are You Lonesome Tonight.kar, Elvis Presley – Can’t Help Falling In Love.kar, Elvis Presley – Love Me Tender.kar, Elvis Presley – Suspicious Minds.kar, Eric Clapton – Tears In Heaven.kar, Extreme – More Than Words.kar, Frank Sinatra – My Way.kar, Frank Sinatra – Something Stupid.kar, Frank Sinatra – Strangers In The Night.kar, G. Capurro – O sole mio.kar, Gerry & The Pacemakers – You’ll Never Walk Alone.kar, Gerry Rafferty – Baker Street.kar, Gloria Gaynor – I Will Survive.kar, Gordon Lightfoot – If You Could Read My Mind.kar, Guns’n’Roses – Sweet Child Of Mine.kar, Harry Belafonte – Banana Boat Song (Day-O).kar, Jim Croce – Operator.kar, Jimmy Buffett – Margaritaville.kar, Joe Cocker – You Are So Beautiful.kar, Joe Dassin – Et si tu n’existais pas.kar, Julio Iglesias – A veces si, a veces no.kar, Led Zeppelin – Stairway To Heaven.kar, Louis Armstrong – What A Wonderful World.kar, Lucio Dalla – Caruso.kar, Mariah Carey – Without you.kar, Meat Loaf – I’d Do Anything For Love.kar, Monty Python – Always Look On The Bright Side Of Life.kar, Mungo Jerry – In The Summertime.kar, Pet Shop Boys – Go West.kar, Phil Collins – Groovy kind of love.kar, Queen – Bohemian Rhapsody.kar, Queen – Love Of My Life.kar, Queen – Too Much Love Will Kill You.kar, Ray Charles – Hit the road Jack.kar, Richard Marx – Hazard.kar, Robbie Williams – Supreme.kar, Rod Stewart – Sailing.kar, Rolling Stones – Satisfaction.kar, Scorpions – Wind of change.kar, Smokie – Alice.kar, Soul Asylum – Runaway train.kar, Status Quo – In the army now.kar, Sting – Englishman in New York.kar, Supertramp – The Logical Song.kar, Suzanne Vega – Tom’s Diner.kar, The Carpenters – Close To You.kar, The Righteous Brothers – You’ve Lost That Lovin Feelin.kar, Tina Turner – The best.kar, Tom Jones – Delilah.kar, Tony Braxton – Unbreak My Heart.kar, Ugly Kid Joe – Cats In The Cradle.kar, Westlife – Seasons in the sun.kar, Whitesnake – Here I go again.kar, Whitney Houston – I will always love you.kar.

Advertisements

Written by vtopan

October 6, 2009 at 12:51 AM

Posted in karaoke, Music

Tagged with , , , , , ,

Listing the modules (DLLs) of the current process without API functions

with one comment

There is a simple way to walk the list of loaded modules (DLLs) of the current Windows process without calling any API functions. It also works with other processes, but it obviously involves reading the respective process’ memory space, which in turn involves using the aptly-named ReadProcessMemory function, defeating the whole purpose of not using APIs.

The PEB and the TIB

The PEB (Process Enviroment Block), briefly documented here (the page which passes as “documentation” on MSDN just… isn’t) is a structure (stored for each process in it’s own memory space) which holds various process parameters used by the OS such as the PID, a flag set if the process is being debugged, some localization information etc. The PEB is pointed to by the TIB (Thread Information Block), which is always located at FS:[0] (if that sounds like black magic, either pick up a book on assembly language and/or x86 processor architecture, or ignore that piece of information and use the code below to get to it).

One of the PEB entries is a list of, well, the loaded modules of the process. Actually, a PEB member points to a structure called LoaderData (it’s type being PEB_LDR_DATA), again “almost documented” by MS, which points to the list we’re interested in, looking something like this:

typedef struct LDR_DATA_ENTRY {
  LIST_ENTRY              InMemoryOrderModuleList;
  PVOID                   BaseAddress;
  PVOID                   EntryPoint;
  ULONG                   SizeOfImage;
  UNICODE_STRING          FullDllName;
  UNICODE_STRING          BaseDllName;
  ULONG                   Flags;
  SHORT                   LoadCount;
  SHORT                   TlsIndex;
  LIST_ENTRY              HashTableEntry;
  ULONG                   TimeDateStamp;
  } LDR_DATA_ENTRY, *PLDR_DATA_ENTRY;

It’s a linked list (the LIST_ENTRY structure contains the forward pointer called Flink) which contains serveral useful pieces of information about each module, among which it’s image base (BaseAddress), virtual address of the entrypoint (EntryPoint) (NOT the RVA you find in the PE header, but the actual computed VA) and DLL name with (FullDllName) and without (BaseDllName) the path, as UNICODE_STRINGs. The list is circularly linked and has a sentinel element with the BaseAddress member set to 0.

The list entries should be of the LDR_DATA_TABLE_ENTRY data type described by MS here, but the actual structure found in-memory doesn’t have the first member (BYTE Reserved1[2]). An alternative (and more complete) definition of the structure can be found here, but it has three LIST_ENTRY members at the beginning instead of just one.

Getting a pointer to the list

We retrieve the pointer to the list from the PEB using inline assembly from the C source code:

__declspec(naked)
PLDR_DATA_ENTRY firstLdrDataEntry() {
   __asm {
      mov eax, fs:[0x30]  // PEB
      mov eax, [eax+0x0C] // PEB_LDR_DATA
      mov eax, [eax+0x1C] // InInitializationOrderModuleList
      retn
      }
   }

There are actually three lists of modules, sorted by three different criterias; the one we’re using is sorted by the order in which the modules were loaded.

Example

Using the structure defined above and the firstLdrDataEntry function, it becomes trivial to walk the list of loaded modules:

void main() {
   PLDR_DATA_ENTRY cursor;
   cursor = firstLdrDataEntry();
   while (cursor->BaseAddress) {
      printf( "Module [%S] loaded at [%p] with entrypoint at [%p]\n",
              cursor->BaseDllName.Buffer, cursor->BaseAddress,
              cursor->EntryPoint);
      cursor = (PLDR_DATA_ENTRY)cursor->InMemoryOrderModuleList.Flink;
      }
   }

Written by vtopan

May 27, 2009 at 11:22 PM

Using NtDeleteFile from Delphi

with 2 comments

The NtDeleteFile API

The native API NtDeleteFile performs the same task as the user-mode API DeleteFile, but interrestingly enough, the user-mode API does not call the native API to perform it’s task. As explained here, normally files are deleted through calls to NtSetInformationFile. The main difference in behavior comes from the fact that NtDeleteFile does not wait for handles on the file to close before deleting it (note that if the file is “open for normal I/O or as a memory-mapped file”, it still can’t be deleted, so only read-only handles will be ignored).

Data structures

The required structures (not defined in Delphi) are UNICODE_STRING and OBJECT_ATTRIBUTES.

Steps

The steps to remove the file are:

  • convert the “DOS” path name to an “NT” path name (basically prepend “\??\” to whatever the plain path is) using RtlDosPathNameToNtPathName_U;
  • fill in the OBJECT_ATTRIBUTES structure;
  • call NtDeleteFile.

Importing the APIs

Using the afore-linked-to type definitions, we still need to import the native APIs:

function NtDeleteFile(ObjectAttributes:POBJECT_ATTRIBUTES):DWORD; stdcall; external 'ntdll.dll';
function RtlDosPathNameToNtPathName_U(DosName:PWChar; var NtName:UNICODE_STRING; DosFilePath:PPChar; NtFilePath:PUNICODE_STRING):BOOL; stdcall; external 'ntdll.dll';

Do note that this statically links the imported functions, making the whole application unable to load if the undocumented APIs are not present on the system (at least for Windows 2000 and XP they should be).

Converting DOS paths to native paths using RtlDosPathNameToNtPathName_U

Converting the DOS path name to a native path is done by the RtlDosPathNameToNtPathName_U API, which takes in a PWChar argument containing the DOS path and a pre-allocated UNICODE_STRING structure of MAX_PATH WideChars and returns True if it has successfully converted the path.

Source code

The code looks something like this:

function _DeleteFile(fileName:string):DWORD;
var
   oa:OBJECT_ATTRIBUTES;
   ws1, ws2:WideString;
   us:UNICODE_STRING;
begin
   Result := $C0000001; // STATUS_UNSUCCESSFUL, "generic" error 
   ws1 := fileName; // automatic String -> WideString conversion
   SetLength(ws2, MAX_PATH);
   us.Length := MAX_PATH;
   us.MaximumLength := MAX_PATH;
   us.Buffer := @ws2[1];
   if not RtlDosPathNameToNtPathName_U(@ws1[1], us, nil, nil)
      then Exit;
   oa.Length := SizeOf(OBJECT_ATTRIBUTES);
   oa.RootDirectory := 0;
   oa.ObjectName := @us;
   oa.Attributes := $40; // case insensitive
   oa.SecurityDescriptor := nil;
   oa.SecurityQualityOfService := nil;
   Result := NtDeleteFile(@oa); // pass on the NTSTATUS
end;

Written by vtopan

May 26, 2009 at 3:43 PM

Posted in Delphi, Snippets

Tagged with , ,

How to check if a thread/process is suspended (get thread state)

with 4 comments

The basic steps to get to a thread’s status information is the following (knowing of course both the process ID (hence forth PID) and the thread ID (TID)):

  1. call NtQuerySystemInformation with SystemInformation set to SystemProcessInformation (5)
  2. iterate over the array of SYSTEM_PROCESS_INFORMATION structures (the structure contents is (wrongfully) explained here; correct version here) to find your PID (ProcessId member) of interest
  3. iterate over the array of SYSTEM_THREAD structures (detailed below) to find the desired TID (UniqueThread member) and check the State and WaitReason members; both must be set to 5 if the thread is suspended, any other values otherwise

As it’s probably obvious to most people keen on system-level programming, a process is suspended when all it’s threads are suspended, so all of them must be checked for the suspended status.

Step one: calling NtQuerySystemInformation

The required structures are defined here (for Delphi). The function isn’t defined in any headers, so we must declare it’s prototype ourselves:

function NtQuerySystemInformation(SystemInformationClass:DWORD; SystemInformation:pointer; SystemInformationLength:DWORD; ReturnLength:PDWORD):cardinal; stdcall; external 'ntdll';

Example usage:

var 
   spi:PSYSTEM_PROCESS_INFORMATION;
   size:DWORD;
begin
if (NtQuerySystemInformation(5, nil, 0, @size) = STATUS_INFO_LENGTH_MISMATCH) // SystemProcessInformation
   and (size > 0)
   then begin
        GetMem(spi, size);
        if NtQuerySystemInformation(5, spi, size, @size) = 0
           then begin
                [...] // do something with spi
                end
           else HandleError; // failed listing processes!
        FreeMem(spi);
        end
    else HandleError; // failed listing processes!
end;

HandleError is a fictional function (which you’ll most likely skip, ’cause you’re in a hurry to get things done, right? 🙂 ).

Step two: iterating the process list

The structure only looks like a linked list item; the NextEntryOffset member is an actual offset from the beginning of the current structure to the beginning of the next one. This is needed because of the variable size of the structure (given by the variable number of threads for each process). We need an extra crt:PSYSTEM_PROCESS_INFORMATION variable to walk the pseudo-linked list because we must keep the original psi pointer to free it’s memory.
The outline of the code which iterates the processes looking for a PID (given the spi:PSYSTEM_PROCESS_INFORMATION pointer from above) would look like this:

var 
    crt:PSYSTEM_PROCESS_INFORMATION; 
[...]
    crt := spi;
    repeat
        if crt^.ProcessID = PID
           then begin
                [...] // do something with crt^
                break;
                end;
        crt := Pointer(DWORD(crt) + crt^.NextEntryOffset);
    until crt^.NextEntryOffset = 0;

Step three: find the appropriate thread

Given the ThreadInfo array in the structure located at the previous step, we iterate through it and test the State and WaitReason members for the item matching our TID:

var
    j:integer;
[...]
    for j := 0 to crt^.NumberOfThreads-1 do
        begin
        if crt^.ThreadInfo[j].UniqueThread = TID
           then begin
                if crt^.ThreadInfo[j].WaitReason = 5
                   then [...] // the thread is suspended
                   else [...]; // the thread is not suspended
                break; 
                end;
        end;

The State member must also be set to 5 (“waiting”), but if the WaitReason is non-null, the State must be 5 (and vice-versa), so there’s little point in checking it explicitly.

Additional info: thread starting address, priority etc.

If you’ve paid any attention while reading the structures, you might have noticed additional interesting information about threads and processes, such as the creation time, image path, priority, handle count and memory and I/O usage/history for processes (this is how Process Explorer gets, for example, the WorkingSet/PeakWorkingSet and ReadBytes/WriteBytes/OtherBytes information) and starting address, priority/base priority and various timing information for threads. The starting address is particularly interesting, because the NtQueryInformationThread API with ThreadInformationClass set to ThreadQuerySetWin32StartAddress (9) only works (on Windows pre-Vista) “before the thread starts running” (quoted from MSDN), which seems to me rather pointless in the first place.

The NtQuerySystemInformation API is also a useful replacement for the CreateToolhelp32Snapshot suite, yielding more information about processes and threads.

Written by vtopan

April 15, 2009 at 1:07 AM

Posted in Delphi, Snippets

Top ten striptease songs

leave a comment »

Some while ago, when the opportunity arose to put them to good use, I realised I had rather few striptease songs sorted out. The very next day (my memories are rather foggy given circumstances, but it most likely was the next day, so we’ll work with that assumption) I set on a quest for the web’s favorite striptease songs. The results, however, were somewhat disappointing; mostly redundant and not as insightful as I had hoped. But plowing through them I also found some good (enough) ones, and managed to collect sufficient songs to tire out even some of the most dedicated strippers out there (not that that would be the purpose of the whole thing).

Stumbling over the sorted-out-music folder and running into them again, I decided to share them with the world, if only to spare other don quixotesque music fans out there from the pain of having to go thorough endless pages of search results only to find (mostly) the folowing songs listed over and over.

Top ten strip songs

Note: the order is mostly a matter of personal taste & current state of mind. The purpose is to provide you with a list of good striptease songs, rather than to make statements about the songs’ quality when compared to one another, as I find judging taste to be pointless.

#10. Kylie Minogue – Chocolate [watch]
Not much surprise in Kylie showing up in this list, now is there?

#9. Tina Turner – Private Dancer [watch]
Striptease 101.

#8. Pussycat Dolls & Busta Rhymes – Don’t Cha [watch]
Excellent rythm; rap & hip hop fans will appreciate it.

#7. Def Leppard – Pour Some Sugar on Me [watch]
Rock.

#6. Right Said Fred – I’m Too Sexy [watch]
Funny rather than sexy, but still a good song to drop clothes to.

#5. Joe Cocker – You Can Leave Your Hat On [watch]
Synonymous with “striptease song”; would be higher in the top if it weren’t so damn everywhere.

#4. Alannah Myles – Black Velvet [watch]
Another classic, slower & more sensual than most in this top.

#3. Prince – Cream [watch]
I’m not that much into Prince, but this song is by far among the best strip songs I’ve heard so far.

#2. Patricia Kaas – Mademoiselle chante le blues [watch]
French strip song. ’nuff said.

#1. En Vogue – Beat of Love [listen]
The bass drum rythm on this song is simply amazing, earning it a #1.

Bonus song

Instrumental music is excellent for striptease, and one of the best ones at that is the theme song from A Shot in the Dark (1964; the second Pink Panther movie, featuring Peter Sellers – a “dark” comedy which you may also enjoy) by Henry Mancini. If you need further proof, check out Ursula Martinez’ Hanky Panky (strip) show. The sax, as on Mademoiselle chante le blues, is excellent. On the instrumental topic, half funny-half sexy is also The Stripper from Joe Loss.

Runners up

As with most tops, some runners up got left out. In alphabetical order:

  • Ella Fitzgerald – I Just Wanna Make Love to You
  • Firefox – Sex Shooter
  • Ginuwine – Pony
  • Lovage – Sex (I’m A)
  • Paula Cole – Feelin’ Love
  • Queen – Fat Bottomed Girls
  • Sam Brown – Stop
  • Santana & Rob Thomas – Smooth
  • Shaggy – Hey Sexy Lady
  • The Sugababes – Push the Button
  • Tom Jones – Sex Bomb
  • Tom Jones – You Don’t Have to Be Rich
  • Touch & Go – Tango in Harlem
  • Zuchero – Baila Sexy Thing

You can sample most of them on imeem.com [later edit: imeem is now defunct; changed links to point to Google video searches], on youtube or simply googling/yahoo(ing?) for them.

Written by vtopan

April 6, 2009 at 1:36 AM

Posted in Music, Tops

Translating headers: struct / record field alignment in C / Delphi

with 4 comments

If you’ve ever taken a shot at porting headers from C to Delphi, you may have noticed the different way in which the struct/record fields are aligned, but most likely you havent. And if you had the bad luck of stumbling over a struct that gets aligned differently when ported to Delphi, even though the data types were translated correctly, you’re probably interested in what happens behind the scenes and how to fix it. Well, here it goes.

Why variable addresses are aligned in memory

As explained in depth here, because of it’s internal structure, the time required by the CPU to access data from the RAM depends on the alignment of the address it requests (the “aligned” memory addresses being accessed faster). Aligned means that the address should be a multiple of the CPU’s memory word (not to be confused with the WORD data type in C/Delphi, which is always 2 bytes), which is the least amount of memory the CPU can get from RAM at one time. It’s also the size of the general purpose registers on the CPU, and it represents the “chunk” of data the CPU is most “comfortable” working with. On x86 architectures it’s 32 bits, which means 4 bytes (on 64 bit architectures it’s… well, 64 bits = 8 bytes). So, the memory addresses should be multiples of 4 on x86 systems for faster access.

Nitpicking corner: why is the WORD type 2 bytes long then, if the memory word on x86 is 4 bytes? Well, it’s not actually *all* the x86 architectures that have a 4 byte memory word, just the 386-and-higher ones (the aptly-named 32-bit architectures). But back when dinosaurs still roamed the Earth and “640K of memory were enough for anybody” (to paraphrase (?) one of the foremost computer visionaries), the computer word was just 16 bits, or 2 bytes, and that’s when the WORD data type was coined (without very much foresight, truth be told).

Struct field alignment in C

According to this paragraph on Wikipedia, struct member fields are aligned based on their size by padding them with, basically, their size in bytes. So, assuming we declare the structure:

typedef struct {
BYTE a;
WORD b;
BYTE c;
DWORD d;
} foo;

you might be tempted to assume it will take 8 bytes of memory. But, due to the afore-mentioned alignment, b will be aligned on a 2-byte boundary, and c on a 4-byte boundary, so that structure will actually be equivalent to this one:

typedef struct {
BYTE a;
BYTE padding_for_b[1]; // 1-byte padding to align .b
WORD b;
BYTE c;
BYTE padding_for_d[3]; // 3-byte padding to align .d
DWORD d;
} foo;

and take precisely 12 bytes. You can force C’s hand not to align the members using the #pragma pack(1) directive, but (a) the code will be slower and (b) you can’t do that to standard structures in the Windows API for obvious reasons.

Record field alignment in Delphi

As explained in the “align fields compiler directive” help entry, in Delphi the record field alignment is not based on the field’s data type size, but on a constant specified by the ALIGN (A) directive (which can also be set for the entire project from Project->Options->Compiler->Record field alignment.
The default is {$ALIGN 8} (short: {$A8}), which means alignment to an 8-byte boundary. However, that’s how things work only in theory. In practice, for some mysterious reason, Delphi does exactly what C does: unless the alignment is set to 1 (eg. by {$A1}), it aligns record fields based on their size.

The difference

But if Delphi behaves just like C, why do things sometimes still crash? They do because of one exception to the rule: enumerations are treated differently. In C, they are 4 bytes in size by default (this can be changed using the #pragma enum directive). In Delphi, the enumeration size is controlled by the $Z directive, and by default it’s set to 1. Therefore, in order to get the proper translation of API structures from C to Delphi, you should use the {$Z4} directive.

Written by vtopan

March 10, 2009 at 11:37 PM

Posted in Delphi

Tagged with , , , , ,

Converting C structs to Delphi

leave a comment »

In the process of writing a Process Explorer meets HijackThis one-size-fits-all monster app, I faced the rather tedious task of porting Windows SDK headers (some less documented than others) to Delphi. As expected, I ran into annoying gotchas; here are some of them.

Boolean type in C / Windows SDK

The C specs didn’t define a boolean type up until C99 (which introduced the bool data type), which led to a variety of “standards”. The SDK uses the BOOLEAN type, which is actually a BYTE, and should be mapped to the Boolean type in Delphi, not BOOL/LongBool (yes, I am well aware that this may be a “duh!” for some).

Other type mappings

UCHAR is unsigned char, not “unicode char” as some might expect, so it translates to BYTE, not WORD.

Struct to record mappings

See this post.

[to be continued]

Written by vtopan

March 10, 2009 at 2:49 AM

Posted in Delphi

Tagged with , , ,