stringwindbg

How to determine length of null-terminated string in WinDbg


There is a null-terminated ASCII string existing in the address space of the target process under debugging. I want to write a WinDbg script to print out the length of this string. Assuming I know the address of the starting character of the string, how do I calculate its length?


Solution

  • IMHO it's not convenient in WinDbg and I tried finding a solution involving s, .foreach and .if for more than 15 minutes but the result was frustrating. In such a case I use a real programming language like Python with PyKD.

    Save the following into a file strlen.py:

    from pykd import *
    import sys
    
    addr = int(sys.argv[1], 16)
    length = 0
    while(0 != loadBytes(addr+length, 1)[0]):
        length += 1
    dprintln(str(length))
    

    Then run it with the address as argument:

    0:022> !py c:\tmp\strlen.py 773a004e
    43
    0:022> db 773a004e L0n44
    773a004e  54 68 69 73 20 70 72 6f-67 72 61 6d 20 63 61 6e  This program can
    773a005e  6e 6f 74 20 62 65 20 72-75 6e 20 69 6e 20 44 4f  not be run in DO
    773a006e  53 20 6d 6f 64 65 2e 0d-0d 0a 24 00              S mode....$.
    

    Note that PyKd does not automatically convert named symbols to addresses (e.g. you can't pass ntdll as an address)