sp-analysis failed in IDA pro - ida

I am using IDA pro to analysis software binary. Sometime, some function with end up with sp-analysis failed.
I am writing program with IDAPython. Is there any API to detect this case, so I can ignore those failure cases for now.

You can do this:
def get_sp_failed():
failed_funcs = []
ea = 0
while ea != BADADDR:
ea = idaapi.find_text(ea, 0, 0, "sp-analysis failed", idaapi.SEARCH_DOWN | idaapi.SEARCH_NEXT)
if ea != BADADDR:
func = idaapi.get_func(ea)
failed_funcs.append(func.startEA)
ea = func.endEA
return failed_funcs

ALT+K the negative stack pointer and change the previous to -.
#Train answer didn't really help unfortunately.

Related

robotic arm not working with pyserial and gcode

I am working on a robotic arm.
M106 is turn on the fan
M17 is stepper on
M18 is stepper off
G1 X... Y.. X.. is the coordinates of movement
the port is correct, the terminal prints the hello hi there...
However the robotic arm is not moving, I totally have no clue why is this happening.
Is it there is some problem with my code?
import serial
import struct
def gcode_encode(gcode):
gcode += '\r\n'
return struct.pack(f'<{len(gcode)}s', gcode.encode(encoding='utf-8'))
print("hello")
# ser = serial.Serial('COM7', 9600, timeout=0, parity=serial.PARITY_EVEN, rtscts=1)
ser = serial.Serial()
ser.port = 'COM7'
ser.baudrate = 9600
ser.timeout = 0
ser.open()
g = gcode_encode('M106')
ser.write(b'g')
g = gcode_encode('M17')
ser.write(b'g')
g = gcode_encode('M18')
ser.write(b'g')
g = gcode_encode('G1 X0 Y120 Z120')
ser.write(b'g')
g = gcode_encode('G1 X50 Y120 Z60')
ser.write(b'g')
ser.close()
print("hi")
You are writing only the character 'g' to the port. If you want to write bytes of a variable g, you need to use bytes(g). The same is with f'<{len(gcode)}s', the characters in single or double quotes are not a command here, but just a string. Also you don't need packing of the string, just encoding.
Also add some pauses between commands using time.sleep().

How to convert opencv functions to mexopencv functions useable in matlab?

My Problem:
I want to use functions of opencv like the MIL-Tracker or MedianFlow-Tracker in Matlab (these functions are not in mexopencv). But I don't know how or understand how to do this. The documentation of opencv/mexopencv doesn't help me. This doesn't help: how do OpenCV shared libraries in matlab? - because the link in the answer is down.
So is there a way to use these functions in Matlab? And if- How?
Why?: As a part of my bachelor thesis I have to compare different already implemented ways to track people.
If you would like to use these functions specifically in MATLAB you could always write your own MEX file in C/C++ and send the data back/forward between the two calls, however this would require some basic C++ knowledge and understanding creating MEX files.
Personally I would definately recommend trying this with Python and the OpenCV Python interface since its so widely used and more supported than using the calls in MATLAB (plus its always a useful skill to be able to switch between Python and MATLAB as and when needed).
There is a full example with the MIL-Tracker and the MedianFlow-Tracker (and others) here (Which demonstrates using them in C++ and Python!).
Python Example :
import cv2
import sys
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if __name__ == '__main__' :
# Set up tracker.
# Instead of MIL, you can also use
tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN']
tracker_type = tracker_types[2]
if int(minor_ver) < 3:
tracker = cv2.Tracker_create(tracker_type)
else:
if tracker_type == 'BOOSTING':
tracker = cv2.TrackerBoosting_create()
if tracker_type == 'MIL':
tracker = cv2.TrackerMIL_create()
if tracker_type == 'KCF':
tracker = cv2.TrackerKCF_create()
if tracker_type == 'TLD':
tracker = cv2.TrackerTLD_create()
if tracker_type == 'MEDIANFLOW':
tracker = cv2.TrackerMedianFlow_create()
if tracker_type == 'GOTURN':
tracker = cv2.TrackerGOTURN_create()
# Read video
video = cv2.VideoCapture("videos/chaplin.mp4")
# Exit if video not opened.
if not video.isOpened():
print "Could not open video"
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print 'Cannot read video file'
sys.exit()
# Define an initial bounding box
bbox = (287, 23, 86, 320)
# Uncomment the line below to select a different bounding box
bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
ok = tracker.init(frame, bbox)
while True:
# Read a new frame
ok, frame = video.read()
if not ok:
break
# Start timer
timer = cv2.getTickCount()
# Update tracker
ok, bbox = tracker.update(frame)
# Calculate Frames per second (FPS)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
# Draw bounding box
if ok:
# Tracking success
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
else :
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
# Display FPS on frame
cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
# Display result
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
if k == 27 : break
I would definately try it using Python (if this is an option). Otherwise if MATLAB is a must then probably try implementing the C++ example code shown in the link before as a MEX file and linking openCV during the compilation i.e.
mex trackerMexOpenCV.cpp 'true filepath location to openCV lib'
I hope this helps!

python OverflowError: 34, raised for no apparent reason

I've written a python script to evaluate a physical quantity and, for some reason, python decided to raise an OverflowError for no justified reason. Here's the script
import numpy as np
from math import sqrt,cos, log, pi
from scipy import integrate as sciint
from scipy import optimize as sciopt
rt=np.inf
ymin=cos(np.radians(0.5))
def func(u,y, D, rt):
return (1.+u)**(-4)/u/sqrt(u*u-D**2*(1-y*y))
def lim_u(y, D, rt):
return [D*sqrt(1-y*y), rt]
def lim_y(D, rt):
return [ymin,1]
def Jfactor(D,rt,r0,rho0,tmax):
ymin=cos(np.radians(tmax))
Dprime=D/r0
rtprime=rt/r0
Msun2kpc5_GeVcm5 = 4463954.894661358
cst = 4*pi*rho0**2*r0*Msun2kpc5_GeVcm5
res = sciint.nquad(func, ranges=[lim_u, lim_y], args=(Dprime,rtprime),
opts=[{'epsabs':1.e-10,'epsrel':1.e-10,'limit':1000},
{'epsabs':1.e-10,'epsrel':1.e-10,'limit':1000}])
return cst*res[0]
def deltaJ(rho0,J,D,rt,r0,tmax):
#return J-Jfactor(D,rt,r0,1.,tmax)*10.**(rho0*2.)
return long(J-Jfactor(D,rt,r0,1.,tmax)*10.**(rho0*2.))
D=104.
rt=np.inf
tmax=0.5
J = 10.**18
for j,r0 in enumerate(np.logspace(-1.,np.log10(5),10)):
results = sciopt.minimize_scalar(deltaJ,bracket=(7.,9.),args=(J,D,rt,r0,tmax))
print r0,results.x,results.fun
Very quickly: I want scipy.optimize.minimize_scalar to minimize deltaJ but here's (part of) the error message I get
File "test2.py", line 26, in deltaJ
return long(J-Jfactor(D,rt,r0,1.,tmax)*10.**(rho0*2.))
OverflowError: (34, 'Numerical result out of range')
Now, if J = 10**18, Jfactor(D,rt,r0,1.,tmax) is ~ 5, I expect minimize_scalar to easily scan over rho0 to find ~ 8.5. Instead I get this error message.
As you can see, I've even bracketed the range and tried using long(), but nothing helped. Using instead another minimizing method, eg. bounded, gives again a weird result (function value of ~ -7e17)...
Does anybody have an idea to have this working? Thank you

"LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd" when importing from Matlab files

After importing this data file from Matlab with scipy.io.loadmat, things appeared to work fine until we tried to calculate the conditioning number of one of the matrixes within.
Here's the minimum amount of code that reproduces for us:
import scipy
import numpy
stuff = scipy.io.loadmat("dati-esercizio1.mat")
numpy.linalg.cond(stuff["A"])
Here's the extended stacktrace courtesy of iPython:
In [3]: numpy.linalg.cond(A)
---------------------------------------------------------------------------
LapackError Traceback (most recent call last)
/snip/<ipython-input-3-15d9ef00a605> in <module>()
----> 1 numpy.linalg.cond(A)
/snip/python2.7/site-packages/numpy/linalg/linalg.py in cond(x, p)
1409 x = asarray(x) # in case we have a matrix
1410 if p is None:
-> 1411 s = svd(x,compute_uv=False)
1412 return s[0]/s[-1]
1413 else:
/snip/python2.7/site-packages/numpy/linalg/linalg.py in svd(a, full_matrices, compute_uv)
1313 work = zeros((lwork,), t)
1314 results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
-> 1315 work, -1, iwork, 0)
1316 lwork = int(work[0])
1317 work = zeros((lwork,), t)
LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd
All obvious ideas (like flattening and reshaping the matrix or recreating the matrix from scratch reassigning it element by element) failed. How can I want to massage the data, then, in order to make it more agreeable with numpy?
It's a bug, fixed some time ago: https://github.com/numpy/numpy/pull/235
Workaround:
np.linalg.cond(stuff['A'].newbyteorder('='))
This works for me:
In [33]: stuff = loadmat('dati-esercizio1.mat')
In [34]: a = stuff['A']
In [35]: try: np.linalg.cond(a)
....: except: print "Fail!"
Fail!
In [36]: b = np.array(a, dtype='>d')
In [37]: np.linalg.cond(b)
Out[37]: 62493201976.673141
In [38]: np.all(a == b) # Verify they hold the same data.
Out[38]: True
Apparently it's something wrong with the byte order (endianness?) of each number in the resulting ndarray and not just with the ndarray object itself.
Something like this but more elegant should do the trick:
n, m = A.shape()
B = numpy.empty_like(A)
for i in xrange(n):
for j in xrange(m):
B[i,j] = float(A[i,j])
del A
B = A
print numpy.linalg.cond(A) # 62493210091.354507
(For some reason an in-place replacement still gives that error - so there's something wrong with the byte order of the whole object, too.)

How to get threads->tid() value in XS code?

I need to get current perl thread id in a C function inside *.XS part of a perl module.
In pure perl (*.pm part) I would simply do:
$id = threads->tid();
But what is a recommended way to get this value in XS?
Unfortunately http://perldoc.perl.org/perlthrtut.html and http://perldoc.perl.org/threads.html do not talk about dealing with threads in XS.
Thanks in advance
--
kmx
To call a method, one uses call_method.
UV get_tid() {
dSP;
UV tid;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv("threads", 0)));
PUTBACK;
count = call_method("tid", G_SCALAR|G_EVAL);
SPAGAIN;
if (SvTRUE(ERRSV) || count != 1)
tid = 0;
else
tid = (UV)POPi;
PUTBACK;
FREETMPS;
LEAVE;
return tid;
}
See how threads itself does it! I suggest you download threads from CPAN, unpack it and take a look at threads.xs. The part you need is a function called ithread_tid.