windbg help missing kernel32 function - windbg

I am trying to follow this tutorial here https://www.microsoftpressstore.com/articles/article.aspx?p=2201303 specifically the part where it mentions x kernel32!writeprocessmemory
I am unable to find the method kernel32!WriteProcessMemory = even though documentation mentions it but i can find
kernel32!_imp__WriteProcessMemory and kernel32!WriteProcessMemoryStub. I am new to windbg and trying to follow the tutorial so i am not sure if this method has been deprecated and if so, what is it's substitute and how do we achieve similar functionality.
Thanks

The exported WriteProcessMemory function in fact points to the kernel32!WriteProcessMemoryStub stub which itself jumps onto the kernel32!__imp_WriteProcessMemory which redirects to the kernelbase DLL which is the "real" location for this function.
Let's check with a link dump:
C:>link /dump /exports c:\windows\system32\kernel32.dll | findstr /I WriteProcess
1579 62A 00036C50 WriteProcessMemory
0x36C50 is the RVA where the function "WriteProcessMemory" resides in kernel32 (as given by the export table). Now in windbg:
0:007> ln kernel32 + 0x36c50
Browse module
Set bu breakpoint
(00007ff9`4a6e6c50) KERNEL32!WriteProcessMemoryStub | (00007ff9`4a6e6c60) KERNEL32!ZombifyActCtxStub
We have an exact match which is in fact the KERNEL32!WriteProcessMemoryStub function. If we look at it:
0:007> u KERNEL32!WriteProcessMemoryStub
KERNEL32!WriteProcessMemoryStub:
00007ff9`4a6e6c50 48ff2599150400 jmp qword ptr [KERNEL32!_imp_WriteProcessMemory (00007ff9`4a7281f0)]
00007ff9`4a6e6c57 cc int 3
We can see it's just a jump to KERNEL32!_imp_WriteProcessMemory (located somewhere in the .idata section of kernel32).
Now if we look at what is contained at this location, we have a pointer:
0:007> dp KERNEL32!_imp_WriteProcessMemory L1
00007ff9`4a7281f0 00007ff9`496f0ca0
If we ask windbg what is this pointer:
0:007> ln 00007ff9`496f0ca0
Browse module
Set bu breakpoint
(00007ff9`496f0ca0) KERNELBASE!WriteProcessMemory | (00007ff9`496f0dc4) KERNELBASE!OpenWow64CrossProcessWorkConnection
Exact matches:
KERNELBASE!WriteProcessMemory (void)
We can see that in fact the "real" location for the WriteProcessMemory is in fact in kernelbase.dll.
note: you can actually do the last two commands in one with dps:
0:007> dps KERNEL32!_imp_WriteProcessMemory L1
00007ff9`4a7281f0 00007ff9`496f0ca0 KERNELBASE!WriteProcessMemory
Windbg command used:
ln (List Nearest Symbols): given an address, find the nearest symbol.
u (unassemble): used to disassemble a function
dp (display memory): display memory (pointer sized).
dps(Display Words and Symbols): as dp but with symbolic information.

Related

Ignore some locations in Windbg Conditional breakpoints

I'm trying to set a conditional hardware breakpoint on Windows Kernel-Mode in Windbg by using the following syntax :
ba w1 ffff802312345678 "j(#rip==ffff802387654321 || #rip==ffff802387654330) 'gc';''"
I used the above command in order to ignore every access to my target location (ffff802312345678) from ffff802387654321 or ffff802387654330, so everytime access from somewhere else is taken, then I would be notified.
But the problem is, it still breaks on ffff802387654321 or ffff802387654330 among the other locations.
I also read it's official documents about "Conditional Breakpoints and Register Sign Extension" and also test something like this:
ba w1 ffff802312345678 "j((#rip & 0xffffffffffffffff)=ffff802387654321 || (#rip & 0xffffffffffffffff)=ffff802387654330) 'gc';''"
But it still won't work.
So my question is:
What's wrong with the above command and how can I achieve the desired
result ?
There is no || MASM operator. It's or.
Use
ba w1 ffff802312345678 "j(#rip==ffff802387654321 or #rip==ffff802387654330) 'gc';''"
I have not reproduced your exact case, but a simpler example:
0:000> r rip
rip=0000000076db6fb0
0:000> j (#rip==0000000076db6fb0 || #rip==0) '.echo 5';'.echo 6"
Numeric expression missing from '| #rip==0) '.echo 5';'.echo 6"'
0:000> j (#rip==0000000076db6fb0 or #rip==0) '.echo 5';'.echo 6"
5

Get parameters of public symbols in WinDBG

I'm debugging an application with WinDBG and the PDB files contain only public symbols, so the "k" command shows only the function names in a call stack. How I can show parameters, too?
I already figured out that I can show decorated names by enabling ".symopt- 2",
so I can use the "undname.exe" that comes with Visual Studio to get the parameters from a decorated name. Essentially, I want that WinDBG does the same thing. Is that possible? Is there a plugin for this?
Many thanks in advance!
(PS: Visual Studio shows the parameters, so it probably does this by default)
the tool dbh.exe in windbg package has an undec command and a -d command line option which you can leverage by loading the exe in a sepearte cmd line window at the same base address as in windbg and examining like below this involves manual copy pasting of the decorated name
an example
dbh -d classmagic.exe
classmagic [1000000]: b 1350000 <-- base as loaded in windbg
classmagic [1350000]: a 1351000
?somecrap##YAHHMND#Z
name : ?somecrap##YAHHMND#Z
addr : 1351000
size : 0
flags : 400000
type : 0
modbase : 1350000
value : 0
reg : 0
scope : SymTagNull (0)
tag : SymTagPublicSymbol (a)
index : 1
classmagic [1350000]: undec ?somecrap##YAHHMND#Z
?somecrap##YAHHMND#Z =
int __cdecl somecrap(int,float,double,char)
classmagic [1350000]:
if you need automation and can accept or improve regex as approriate
1) you should have the gnuwin32 port of unix/linux sed.exe in path (to strip modname from k1 output )
2) instead of undname.exe you should have vc++filt in path
3) you should be able to run the windbg .shell command
4) redecorate the function name with .symopt- symopt_undname
5) run this one liner .shell -ci "k1" sed s/.*!//g | vc++filt
k1 use only one frame (top of stack)
.shell -ci takes a windbg command and passes the commands output to an external application
sed strips the module name and the bang character xxxxx! and pipes it to vc++filt
vc++filt de-mangles the symbol name and returns back the formal
function name to windbg screen
an example below
0:000> k1
ChildEBP RetAddr
001cf904 013513b5 classmagic!?somecrap##YAHHMND#Z
0:000> .shell -ci "k1" sed s/.*!//g | vc++filt
ChildEBP RetAddr
int __cdecl somecrap(int,float,double,char)
It depends on the type of symbols available.
Public symbols, don't contain information about formal parameters. This is explained to great length here (note: this page is also available in the windbg help file, search for "Public and Private Symbols").
Functions, on the other hand, are included both in the private symbol
data and public symbol table, but while the private symbol data
includes the function name, address, FPO records, input parameter
names and types, and output type, the public symbol table includes
just the function name, address, and FPO record.
x, ln (or some other commands like .fnent) should give you this kind of information.
Example with notepad:
0:004> x notepad!RestoreFmt
00007ff7`471251a8 notepad!RestoreFmt (<no parameter info>)
0:004> ln notepad!RestoreFmt
Browse module
Set bu breakpoint
(00007ff7`471251a8) notepad!RestoreFmt | (00007ff7`471251f8) notepad!SaveFile
Exact matches:
notepad!RestoreFmt (<no parameter info>)
Note that <no parameter info> clearly states that the symbols don't contain the required information.
The same applied to another program with private symbolic information:
C++ code:
bool DiskReaderWriter::ReadDisk(off_t offset, size_t size_to_read, std::vector<BYTE>& buffer)
Windbg :
0:001> x drive_rw!DiskReaderWriter::ReadDisk
00000000`00d202c0 drive_rw!DiskReaderWriter::ReadDisk (long, unsigned int, class std::vector<unsigned char,std::allocator<unsigned char> > *)
0:001> ln drive_rw!DiskReaderWriter::ReadDisk
Browse module
Set bu breakpoint
g:\app\cpp\drive_rw\diskreaderwriter.cpp(72)
(00000000`00d202c0) drive_rw!DiskReaderWriter::ReadDisk | (00000000`00d20410) drive_rw!std::_Iterator_base12::_Adopt
Exact matches:
drive_rw!DiskReaderWriter::ReadDisk (long, unsigned int, class std::vector<unsigned char,std::allocator<unsigned char> > *)

Matlab executables, passing variable [duplicate]

This question already has answers here:
How can I pass command line arguments to a standalone MATLAB executable running on Linux/Unix?
(3 answers)
Closed 9 years ago.
How do I use deploytool to get an executable file from a .m function and use it?
say, I have a .m names foo, here is the code:
function product = foo(array_a,array_b)
product = array_a.*array_b
end
now I use deploytool to generate a foo.exe, how can I use it with the same workspace vars, AKA array_a and array_b?
Regards
I got your code to work by just supplying the executable file with variables.
I first ran mbuild -setup. I have your file, called foo2.m:
function product = foo(array_a,array_b)
if ischar(array_a)
array_a = str2num(array_a);
end
if ischar(array_b)
array_b = str2num(array_b);
end
product = array_a.*array_b
end
The only difference is I ensured that the input are processed as numbers, not strings. Then, I compile:
mcc -mv -R -singleCompThread -N -p optim -p stats foo2.m
(A good explanation of this command is here: MCC example. I used the link to help me get it working.)
Then, just execute the function.
./run_foo2.sh /usr/local/MATLAB/R2011a/ 1 2
....
product =
2
Make sure you specify the location of the compiler libraries as the first argument, then array_a and array_b as the 2nd and 3rd arguments.
I first got an error when I tried to run the executable: error while loading shared libraries: libmwmclmcrrt.so.7.15: cannot open shared object file. I fixed this by finding the library file path (using find . -name "libmwmclmcrrt.so*"). I then corrected the library path I was supplying as the first argument when I called the executable.
You can use eval to convert strings to other data types, such as arrays. See here for more details.
Also, pcode could be another way, if you want to protect your source code.

How to use command line arguments in Fortran?

GCC version 4.6
The Problem: To find a way to feed in parameters to the executable, say a.out, from the command line - more specifically feed in an array of double precision numbers.
Attempt: Using the READ(*,*) command, which is older in the standard:
Program test.f -
PROGRAM MAIN
REAL(8) :: A,B
READ(*,*) A,B
PRINT*, A+B, COMMAND_ARGUMENT_COUNT()
END PROGRAM MAIN
The execution -
$ gfortran test.f
$ ./a.out 3.D0 1.D0
This did not work. On a bit of soul-searching, found that
$./a.out
3.d0,1.d0
4.0000000000000000 0
does work, but the second line is an input prompt, and the objective of getting this done in one-line is not achieved. Also the COMMAND_ARGUMENT_COUNT() shows that the numbers fed into the input prompt don't really count as 'command line arguments', unlike PERL.
If you want to get the arguments fed to your program on the command line, use the (since Fortran 2003) standard intrinsic subroutine GET_COMMAND_ARGUMENT. Something like this might work
PROGRAM MAIN
REAL(8) :: A,B
integer :: num_args, ix
character(len=12), dimension(:), allocatable :: args
num_args = command_argument_count()
allocate(args(num_args)) ! I've omitted checking the return status of the allocation
do ix = 1, num_args
call get_command_argument(ix,args(ix))
! now parse the argument as you wish
end do
PRINT*, A+B, COMMAND_ARGUMENT_COUNT()
END PROGRAM MAIN
Note:
The second argument to the subroutine get_command_argument is a character variable which you'll have to parse to turn into a real (or whatever). Note also that I've allowed only 12 characters in each element of the args array, you may want to fiddle around with that.
As you've already figured out read isn't used for reading command line arguments in Fortran programs.
Since you want to read an array of real numbers, you might be better off using the approach you've already figured out, that is reading them from the terminal after the program has started, it's up to you.
The easiest way is to use a library. There is FLAP or f90getopt available. Both are open source and licensed under free licenses.
The latter is written by Mark Gates and me, just one module and can be learned in minutes but contains all what is needed to parse GNU- and POSIX-like command-line options. The first is more sophisticated and can be used even in closed-source projects. Check them out.
Furthermore libraries at https://fortranwiki.org/fortran/show/Command-line+arguments
What READ (*,*) does is that it reads from the standard input. For example, the characters entered using the keyboard.
As the question shows COMMAND_ARGUMENT_COUNT() can be used to get the number of the command line arguments.
The accepted answer by High Performance Mark show how to retrieve the individual command line arguments separated by blanks as individual character strings using GET_COMMAND_ARGUMENT(). One can also get the whole command line using GET_COMMAND(). One then has to somehow parse that character-based information into the data in your program.
I very simple cases you just need the program requires, for example, two numbers, so you read one number from arg 1 and another form arg 2. That is simple. Or you can read a triplet of numbers from a single argument if they are comma-separated like 1,2,3 using a simple read(arg,*) nums(1:3).
For general complicated command line parsing one uses libraries such as those mentioned in the answer by Hani. You have set them up so that the library knows the expected syntax of the command line arguments and the data it should fill with the values.
There is a middle ground, that is still relatively simple, but one already have multiple arguments, that correspond to Fortran variables in the program, that may or may not be present. In that case one can use the namelist for the syntax and for the parsing.
Here is an example, the man point is the namelist /cmd/ name, point, flag:
implicit none
real :: point(3)
logical :: flag
character(256) :: name
character(1024) :: command_line
call read_command_line
call parse_command_line
print *, point
print *, "'",trim(name),"'"
print *, flag
contains
subroutine read_command_line
integer :: exenamelength
integer :: io, io2
command_line = ""
call get_command(command = command_line,status = io)
if (io==0) then
call get_command_argument(0,length = exenamelength,status = io2)
if (io2==0) then
command_line = "&cmd "//adjustl(trim(command_line(exenamelength+1:)))//" /"
else
command_line = "&cmd "//adjustl(trim(command_line))//" /"
end if
else
write(*,*) io,"Error getting command line."
end if
end subroutine
subroutine parse_command_line
character(256) :: msg
namelist /cmd/ name, point, flag
integer :: io
if (len_trim(command_line)>0) then
msg = ''
read(command_line,nml = cmd,iostat = io,iomsg = msg)
if (io/=0) then
error stop "Error parsing the command line or cmd.conf " // msg
end if
end if
end subroutine
end
Usage in bash:
> ./command flag=T name=\"data.txt\" point=1.0,2.0,3.0
1.00000000 2.00000000 3.00000000
'data.txt'
T
or
> ./command flag=T name='"data.txt"' point=1.0,2.0,3.0
1.00000000 2.00000000 3.00000000
'data.txt'
T
Escaping the quotes for the string is unfortunately necessary, because bash eats the first quotes.

How does symstore calculate the directory hash value

I am looking for the hash algorithm that symstore uses to create the directory name. I found this link Microsoft Symbol Server / Local Cache Hash Algorithm that describes the data elements that are used to generate the hash, but it does not go into any detail on how the hash value is calculated. I am interested to see how symstore generates the hash directory and if anyone has any sample code that they can show, that would be great!
symstore.exe calculates hash directory names as follows:
For PDB files, the GUID + Age, are used. Here is a python example:
pdb = pdbparse.parse("some.pdb")
pdb.STREAM_PDB.load()
guid = pdb.STREAM_PDB.GUID
guid_str = "%.8X%.4X%.4X%s" % (guid.Data1, guid.Data2, guid.Data3,
guid.Data4.encode("hex").upper())
symstore_hash = "%s%s" % (guid_str, pdb.STREAM_PDB.Age)
For PE (exe/dll) files, the TimeDateStamp (from IMAGE_FILE_HEADER) and SizeOfImage (from IMAGE_OPTIONAL_HEADER) are used. Here is a python example:
pe = pefile.PE("some.exe")
symstore_hash = "%X%X" % (pe.FILE_HEADER.TimeDateStamp,
pe.OPTIONAL_HEADER.SizeOfImage)
Here is an example python script that prints symstore hash values for PDB and PE files:
https://gist.github.com/lennartblanco/9a70961a5aa66fe49df6
Not sure if you have already reviewed this but it is the U.S. Patent describing the symbol store process. Its pretty dense as you can imagine but it does describe in quite a bit of detail how the symbol store directories are expanded and deleted (specifically in sections 6, 7, 8). Hope this helps or points you in the right direction.