Dump out all Args to Child on a given stack - windbg

How do I dump out all Args to Child for my current thread stack e.g. I want to do a command like du on the args for every frame in the current stack. Like du ebp+<1st 4 args> on all frames.

IMHO it's not very easy to do in WinDbg itself, but I can recommend PyKd to solve this task. Make sure you have Python installed in the correct bitness (same bitness as WinDbg that you want to use).
0:000> .symfix
0:000> .reload
0:000> .load E:\...\pykd\0.3.0.27\x86\pykd.dll
Use pykd.pyd if there's no pykd.dll.
0:000> !py
>>> s = getStack()
>>> for f in s:
... for p in range(1,4):
... print("%016X" % (ptrPtr(f.sp + p*ptrSize())))
...
>>> exit()
s is the stack of the current thread.
for f in s loops over all frames.
p will be the parameters where 0 would be the return address and 1 to 4 are the parameters as displayed by kb.
p*ptrSize() calculates the correct offset with respect to the bitness
f.sp gives you the stack pointer of the current frame
ptrPtr() reads pointer-sized (bitness aware) data from memory
"%016X" % n formats the number in hex
exit() gets you out of the interactive console
Now that you have all the parameters, you can also dump their values as strings. You can try loadWStr() of PyKd. Here's a complete script:
from pykd import *
s = getStack()
for f in s:
for p in range(1,4):
paramaddr = f.sp + p*ptrSize()
string = loadWStr(paramaddr)
print(string)
If you want to apply it to all threads, run it like this:
0:000> ~*e !py string.py

Related

How to display the address of the function in WinDBG for .fnret command?

I need to get the address of the function required by .fnret command in WinDBG.
For example, I want to get the information about return value of apphelp!ApphelpCheckRunApp function.
First, I set a breakpoint on this function:
bp apphelp!ApphelpCheckRunApp
Then I'm continuing the execution, until it breaks on that function.
After breaking, I'm executing .fnret [Address] command.
I already tried to use the 77b345d5 address displayed on the breakpoint:
Breakpoint 0 hit
eax=77b345d5 ebx=7ed320f5 ecx=7ffac000 edx=7c886920 esi=7ffac000 edi=00000018
eip=77b345d5 esp=0378ce90 ebp=0378d108 iopl=0 nv up ei pl nz ac po cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000213
appHelp!ApphelpCheckRunApp:
77b345d5 8bff mov edi,edi
but that seems to be not what I need, because I get the following error:
^ Unknown or unsupported return type in '.fnret 77b345d5'
Also I used return address 7c818cdf of this function from call stack (got via kb command):
ChildEBP RetAddr Args to Child
0283ce8c 7c818cdf 00000474 046bb7d0 00000000 appHelp!ApphelpCheckRunApp
but it leads me to the same error.
Which WinDBG command I should use for that and which return address it will display (in case it isn't displayed yet on breakpoint)? Will it then properly work for .fnret or .fnret /s commands? Unfortunately, there are no any examples of using them on MSDN, only the documentation.
Hoping on your help. Thanks in advance.
.fnret is only useful if you have private pdb
it is not useful if you have public pdb because it needs to retrieve the type information
here is a sample usage on a compiled code with private pdb
0:000> x /t /v /f myst!towlower
prv func 00007ff6`74ba5f84 7 <function> myst!towlower (unsigned short)
0:000> x /t /v /f myst!toupper
prv func 00007ff6`74b91b10 2a <function> myst!toupper (int)
0:000> .fnret myst!towlower
myst!towlower (00007ff6`74ba5f84) = unsigned short 1
0:000> .fnret myst!toupper
myst!toupper (00007ff6`74b91b10) = int 0n1
error on a known function which returns a HANDLE using public stripped pdb
0:000> .fnret KERNELBASE!CreateFileA
^ Unknown or unsupported return type in '.fnret KERNELBASE!CreateFileA'
success on a system file with private pdb
it casts the forced return value dumped in #rax as a typed return with value of a function with type information
a system file with prrivate pdb
0:000> .printf "%y\n" , 0x00000001`800bace0 ; an arbitrary function
ole32!ToUnicode (00000001`800bace0)
0:000> .printf "%mu\n" , 00000001`8014c17a ; an arbitrary wide string
guageErrorPointerą“‚Š
0:000> r rax = 00000001`8014c17a the $retreg is populated with an address of wide string
0:000> .fnret 0x00000001`800bace0 << fnret casts the $retreg as wide string and prints the resulting widestring
ole32!ToUnicode (00000001`800bace0) = wchar_t * 0x00000001`8014c17a
"guageErrorPointer???"
OK, that command is indeed not helpful at all when using public PDBs.
I found better solution here: How to get return value from a function in windbg?.
It is possible to get the memory address of return value by viewing eax/rax register on x86/x64 appropriately, using r command (since it always is stored there). After breakpoint, I'm just typing r eax on x86 or r rax on x64. Output will be look like this:
eax=[Address]
Then, I'm displaying a value of received memory address via d* (dd, du etc. displaying data types commands), like this:
du [Address]
After looking at the output, it becomes understandable which data is returned, and its data type also (at least in most of cases).
But to understand first, which data type is used, I'm trying the different combinations of display memory commands and display referenced memory commands.

System Verilog to Specman E

What is the equivalent syntax in Specman E for $readmemh(file,array) and similar system tasks and functions in System verilog?
I am working in converting the existing System verilog code into Specman E ,I have converted and implemented most of the concepts except few system methods like below .Please help me to implement methods like below in Specman E.
$readmemh(file_s,data_2d_i);//For converting SV code into Specman E
In the vr_ad Package there is an equivalent method. Assuming you have a vr_ad_mem object called data_2d_i, you can e.g. call
data_2d_i.readmemh(file_s,0,1000,0,1000);
To read addresses 0..1000 from that file into memory.
Example:
import vr_ad/e/vr_ad_top;
extend sys {
mem: vr_ad_mem;
keep mem.addressing_width_in_bytes == 1;
keep mem.size == 1000;
run() is also {
var data_2d_l: list of byte;
-- read first 16 bytes of mem-file and store the result in a list
mem.readmemh("mem.txt", 0, 15, 0, 15);
data_2d_l = mem.fetch(0, 16);
print data_2d_l;
};
};

Numba: UntypedAttributeError in class method

I have the following class and method that should convolve an array with a kernel.
import numpy as np
from numpy.fft import fft2 as FFT, ifft2 as IFFT
from PIL import Image
from tqdm import trange, tqdm
from numba import jit
from time import sleep
import _kernel
class convolve(object):
""" contains methods to convolve two images """
def __init__(self, image_array, kernel):
self.array = image_array
self.kernel = kernel
self.__rangeX_ = self.array.shape[0]
self.__rangeY_ = self.array.shape[1]
self.__rangeKX_ = self.kernel.shape[0]
self.__rangeKY_ = self.kernel.shape[1]
if (self.__rangeKX_ >= self.__rangeX_ or \
self.__rangeKY_ >= self.__rangeY_):
raise ValueError('Must submit suitable sizes for convolution.')
#jit(nopython=True)
def spaceConv(self):
""" normal convolution, O(N^2*n^2). This is usually too slow """
# pad array for convolution
offsetX = self.__rangeKX_ // 2
offsetY = self.__rangeKY_ // 2
self.array = np.pad(self.array, \
[(offsetY, offsetY), (offsetX, offsetX)], \
mode='constant', constant_values=0)
# this is the O(N^2) part of this algorithm
for i in xrange(self.__rangeX_ - 2*offsetX):
for j in xrange(self.__rangeY_ - 2*offsetY):
# Now O(n^2) portion
total = 0.0
for k in xrange(2*offsetX+1):
for t in xrange(2*offsetY+1):
total += self.kernel[k][t] * self.array[i+k][j+t]
self.array[i+offsetX][j+offsetY] = total
return self.array
As an additional note (in case anyone asks), _kernel just generates specific kernels one may want to convolve the image with (e.g. Gaussian, Moffat, etc.), so it has nothing to do with this class.
When I call the above class on an image and kernel, I get the following error:
Traceback (most recent call last):
File "fftconv.py", line 147, in <module>
plt.imshow(conv.spaceConv(), interpolation='none', cmap='gray')
File "/root/anaconda2/lib/python2.7/site-packages/numba/dispatcher.py", line 304, in _compile_for_args
raise e
numba.errors.UntypedAttributeError: Caused By:
Traceback (most recent call last):
File "/root/anaconda2/lib/python2.7/site-packages/numba/compiler.py", line 249, in run
stage()
File "/root/anaconda2/lib/python2.7/site-packages/numba/compiler.py", line 465, in stage_nopython_frontend
self.locals)
File "/root/anaconda2/lib/python2.7/site-packages/numba/compiler.py", line 789, in type_inference_stage
infer.propagate()
File "/root/anaconda2/lib/python2.7/site-packages/numba/typeinfer.py", line 717, in propagate
raise errors[0]
UntypedAttributeError: Unknown attribute "rangeKX" of type pyobject
File "fftconv.py", line 45
[1] During: typing of get attribute at fftconv.py (45)
Failed at nopython (nopython frontend)
Unknown attribute "rangeKX" of type pyobject
File "fftconv.py", line 45
[1] During: typing of get attribute at fftconv.py (45)
This error may have been caused by the following argument(s):
- argument 0: cannot determine Numba type of value <__main__.convolve object at 0xaff5628c>
Usually I'm pretty good at tracing through Python errors to the cause, but because I'm not familiar with the inner-works of Numba, I'm not sure why it doesn't know what type offsetX is. Any suggestions?
One step performed by numba is type-inference. This assigns types to the different values present in the function so that it can compile (in a way that it works fast).
The error means that numba doesn't understand the first input argument on the function (self in this case). Numba works best in plain functions where the arguments are scalars or array (all numeric). One option would be to move the O(n^2) loop into a function of its own and have that function receive the arrays and any other value explicitly, and decorate that function with numba.njit (or numba.jit(nopython=True), which are equivalent
Also worth a try is just trying the code "as is" removing the "nopython=True". If the performance is good enough then leave it alone :). That may happen, as numba.jit is able to detect loops inside the code that can be compiled in "no python" mode and automatically do what is needed so that the loop itself is compiled in full speed mode. The explicit "nopython=True" keyword disables that mode though.

matlab, how to use the output that is printed by a function?

I would like to store some values that are printed during the iterative procedure of a function, but I have no idea how.
here is the code I am using:
a = 0
b = 2
tol = 1.e-6
trace = 1
F = #(x)1./(x.^3-2*x-5);
Q = quad(F,a,b,tol,trace);
the quad funciton gives the integral of F from a to b using the adaptive quadrature method. trace = 1 prints the values to the console [fcnt a b-a Q] during the recursion, but does not store them to the variable.
I would like to store the values a and b-a that are printed during the procedure, for later use.
for instance, this code gives
>> quad(F,0,2,1.e-6,1);
9 0.0000000000 5.43160000e-01 -0.0989460227
11 0.5431600000 9.13680000e-01 -0.1584111746
13 0.5431600000 4.56840000e-01 -0.0755952309
15 1.0000000000 4.56840000e-01 -0.0828028464
17 1.0000000000 2.28420000e-01 -0.0391911692
19 1.2284200000 2.28420000e-01 -0.0436112507
21 1.4568400000 5.43160000e-01 -0.2054245169
23 1.4568400000 2.71580000e-01 -0.0667670196
25 1.4568400000 1.35790000e-01 -0.0302481864
27 1.5926300000 1.35790000e-01 -0.0365183194
29 1.7284200000 2.71580000e-01 -0.1366285551
31 1.7284200000 1.35790000e-01 -0.0492888403
33 1.8642100000 1.35790000e-01 -0.0871164919
35 1.8642100000 6.78950000e-02 -0.0350033472
37 1.9321050000 6.78950000e-02 -0.0520998049
39 1.9321050000 3.39475000e-02 -0.0228214919
41 1.9660525000 3.39475000e-02 -0.0292778809
I need the values printed in the second and third columns above.
Thank you.
I'm not sure I've understood your question; if you want to store the trace values
9 0.0000000000 5.43160000e-01 -0.0989460227 11
0.5431600000 9.13680000e-01 -0.1584111746
etc ...
into an array, consider that the trace values are printed by the quad funcition by using the fprintf.
You can edit the quand function - edit quad - and see:
if trace
fprintf('%8.0f %16.10f %18.8e %16.10f\n',fcnt,a,h,Q);
end
I see at least two possibilities:
1) Use the diary function
You can modify your code by calling diary right before calling quad; this function create a log of the ouput displayed in the CommandWindow into a text file.
Then, you can load the content of that file to impport its content (the trace data) in the Workspace.
Do not forget to add ";" at the end of the call to quad otherwise also the output of the function will be stored into the diary file and this will prevent the possibility of loading it
a = 0
b = 2
tol = 1.e-6
trace = 1
F = #(x)1./(x.^3-2*x-5);
% Define the name of the diary file
diary_filename='trace_data.txt';
% Enable saving the data into the "trace_data.txt" output file
diary(diary_filename)
Q1 = my_quad(F,a,b,tol,trace);
% Turn off the diary log
diary
% Load the trace data into the "trace_data" array in the workspace
trace_data=load(diary_filename)
You might have a more "general" approach and dynamically generate the trace data output file, by using tempname.
(tempname generate the filename in the temporary folder, so,if you want to store it into you current directory you have to split it, extract the actual filename by using fileparts)
a = 0
b = 2
tol = 1.e-6
trace = 1
F = #(x)1./(x.^3-2*x-5);
% Dynamically generation of the output file name
tmpName = tempname
% Extract the actual filename
[pathstr,name,ext]=fileparts(tmpName)
% Build the filename and add the extension
diary_file=[name '.txt']
% Enable saving the data into the "trace_data.txt" output file
diary(diary_file)
Q1 = my_quad(F,a,b,tol,trace);
% Turn off the diary log
diary
% Load the trace data into the "trace_data" array in the workspace
trace_data=load(diary_file)
2) Modify the quad function
Since the source code of the quad function is available, you can either directly modify the function (not recommended) or copy it in a folder on your path and modify it.
There are many way to modify the function.
One of them could be to:
add an input parameter in which you can specify the name of the output file
add in the function the code to open the file (fopen)
add the file handle in the fprintf call
close the output file at the end (fclose)
another possibility could be to add an output parameter in the definitin of the function in which to store the trace data; in thsi case you also have to add the code to store the trace data into an array at each iteration of the function.
Hope this helps.
Qapla'

Windbg pseudoregister expansion

I am trying to automate a device driver's debug session in Windows XP with Windbg. My device has an "index" register and a "data" register, both memory mapped. The index register must be filled with the internal register's index, and the value can be read from the data register.
So, the followind Windbg command prints correctly the value of the internel register 0x4C:
!ed [uc] 0xfa000000 0x4c; !dd [uc] 0xfa000004 L1
Now I would like to dump a range of internal registers, but it seems that the alias expansion doesn't work as expected in the !ed command. I am trying this cycle:
.for (r $t0=0; #$t0<0x100; r $t0=#$t0+1) { !ed [uc] 0xfa000000 #$t0; !dd [uc] 0xfa000004 L1 }
but it seems that the !ed command is ignored, as if #$t0 was expanded in an empty string.
Tried "$t0", "#$t0", "${t0}" and "#${t0}", but without success. What am I doing wrong?
Yes it seems !ed does not evaluate its arguments like other commands. You need to evaluate them beforehand, for instance with an alias, like this:
.for (r $t0=0; #$t0<0x100; r $t0=#$t0+1) { as /x val #$t0 ; .block {!ed [uc] 0xfa000000 ${val} ; !dd [uc] 0xfa000004 L1 } }