0

I tried to call C function in so file inside Python3 script.

The C function prototype is:

const char* _decrypt(const char* str); // always return NULL or malloc'ed buffer

I loaded the so in Python3, and call the function as below:

slib = ctypes.cdll.LoadLibrary('path_to_crypto.so')
ret = slib._decrypt(ctypes.c_char_p(ciphertext)) # ciphertext is valid
ctypes.c_char_p(ret).value.decode('utf-8') # this may cause SEGV fault

Occationally, ret is minus, such as -1744677792. By occationally, I mean sometimes I got minus value, sometime I got valid positive return value..

Since C function always return either NULL or valid malloc'ed buffer.

How is it possible to get minus value inside Python?

--

The issue is caused by address incorrectly returned to Python3. By applying

ret = ret & 0xffffffff

I can get the right address.

But the so is based on 64 bits address, and I tried to use 0xffffffffffffffff to mask the returned value, it does not work this way, that's it will also cause SEGV fault.

Is this because Python3 use 32bits address by default?

FaceBro
  • 787
  • 2
  • 13
  • 29
  • It returns an address. An adress is not signed. If the first bit is set, you think it is negative. No...it is just an address... – Paul Ogilvie Nov 23 '19 at 09:35
  • @PaulOgilvie Good point, but when I convert this address with first bit set to c_char_p, the scripts SEGV falut.. That's why I think it's invalid return, for most of cases the returned value is positive. – FaceBro Nov 23 '19 at 10:07
  • You CAN'T convert the address. You can only _dereference_ the address to get to the value. (But I am not a Python expert - what is `c_char_p`?) – Paul Ogilvie Nov 23 '19 at 11:44
  • @PaulOgilvie By convert, I mean dereference it by using the address to initialize c_char_p object, and cause SEGV fault. I use ret = ret & 0xffffffff to convert minus address, and it works.. – FaceBro Nov 23 '19 at 11:46
  • Your question is not clear. What is `ret`? Where do you assign to a c_char_p? You do not show enough of your code. – Paul Ogilvie Nov 23 '19 at 11:49
  • @PaulOgilvie more details added. – FaceBro Nov 23 '19 at 11:54
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202936/discussion-between-facebro-and-paul-ogilvie). – FaceBro Nov 23 '19 at 12:06
  • Does this answer your question? [C function called from Python via ctypes returns incorrect value](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value). You have ***Undefined Behavior***. – CristiFati Nov 23 '19 at 14:44
  • @CristiFatiYes,, this is exactly the answer. Cool. – FaceBro Nov 24 '19 at 01:59

0 Answers0