Duplicate function calls while instrumenting with Pintool - instrumentation

I am trying to count the number of calls to malloc using a Pintool. I am using Pin3.6/source/tools/ManualExamples/malloc_mt.cpp as a reference. All my instrumentation does is looks for malloc definition when an image is loaded and inserts a print before the call to malloc.
I am testing it with the below small program I wrote.
My problem is that the call to malloc seems to be happening twice according to the tool whereas I am calling it just once in my test program.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *p;
p = malloc(0xfff);
free(p);
}
On instrumenting this prints:
thread 0 entered main called from main of img /home/---/workspace/hw4/tst_progs/test
thread 0 entered malloc(4095) called from __libc_malloc of img /lib/i386-linux-gnu/libc.so.6
thread 0 entered malloc(4095) called from __libc_malloc of img /lib/i386-linux-gnu/libc.so.6
thread 0 entered malloc(1024) called from __libc_malloc of img /lib/i386-linux-gnu/libc.so.6
Any suggestions?

Related

How to call upon a .dll file from C++ and extract the functions of it?

I would like to know the proper procedure for calling a .dll file with also having a .cpp and .h files for a certain application. I have a program which is the .cpp file with different .h header files and I also included the .dll file into the folder where the .cpp and .h files are located. I would like to know in the .cpp code how am I able to call upon this .dll file since inside of it there are different functions that will allow a DDC264 Evaluation Board to read data from memory through usb and extract the data. I am using a program called DevC++ and I am receiving a current Error which is [Id] returned 1 exit status and MakefileWin has changed.
Attached below is a snippit of the .cpp code:
I also would like to know how to fix both of these errors .enter image description hereenter image description here
// USB_IO_for_VB6.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "USB_IO_For_VB6.h"
#include "CyAPI.h"
#include <cstring>
#include <malloc.h>
#include "BASETSD.H"
#include <math.h>
#include <stdio.h>
// #include <string.h>
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// This is an example of an exported variable
//int USB_IO_FOR_VB6_EXPORTS int USB_IO_for_VB6_API =22;
I
USB_IO_FOR_VB6_API int nUSB_IO_for_VB6 = 22;
#define STRINGLEN 65536 //the larger this number is, the faster the data is shifted in.
#define MAX_CHANNELS_FAST 4096 // 2048= 1024A + 1024B
#define DBP 0 //debug print - 1 enables writing some information to a file in "C:\temp\"
// This function reads the device descriptors from the Cypress USB Chip(s).
// It returns arrays of values, one set of values per device detected.
// The user can then use the visual basic software to select which device to use.
int __stdcall ReadDeviceDescriptors(int *USBdevCount, int *bLengthPass, int *bDescriptorTypePass,
long *bcdUSBPass, int *bDeviceClassPass, int *bDeviceSubClassPass,
int *bDeviceProtocolPass, int *bMaxPacketSize0Pass, long *idVendorPass,
long *idProductPass, long *bcdDevicePass, int *iManufacturerPass,
int *iProductPass, int *iSerialNumberPass, int *bNumConfigurationsPass)
{
CCyUSBDevice *USBDevice;
USB_DEVICE_DESCRIPTOR descr;
USBDevice = new CCyUSBDevice(NULL); // Create an instance of CCyUSBDevice
USBdevCount[0] = USBDevice->DeviceCount();
for (int i=0; i < USBDevice->DeviceCount(); i++)
{
if (USBDevice->Open(i))
{
USBDevice->GetDeviceDescriptor(&descr);
bLengthPass[i]=descr.bLength;
bDescriptorTypePass[i]=descr.bDescriptorType;
bcdUSBPass[i]=descr.bcdUSB;
bDeviceClassPass[i]=descr.bDeviceClass;
bDeviceSubClassPass[i]=descr.bDeviceSubClass;
bDeviceProtocolPass[i]=descr.bDeviceProtocol;
bMaxPacketSize0Pass[i]=descr.bMaxPacketSize0;
idVendorPass[i]=descr.idVendor;
idProductPass[i]=descr.idProduct;
bcdDevicePass[i]=descr.bcdDevice;
iManufacturerPass[i]=descr.iManufacturer;
iProductPass[i]=descr.iProduct;
iSerialNumberPass[i]=descr.iSerialNumber;
bNumConfigurationsPass[i]=descr.bNumConfigurations;
USBDevice->Close();
}
}
return( USBdevCount[0] );
}
I am not sure about how to go about calling a .dll file in C++, I am fairly new to Object Oriented programming.
Regarding the MakefileWin error I tried changing the TDM-GCC release version from 32 to 64 bits and the error continues.
I also tried deleting the dllmain.cpp which is another cpp file that is not needed and moving another original.cpp file from the folder that is shown in one of the images.
I only have a single .cpp file running on my DevC++ compiler which I thought would not cause the Error [Id] returned 1 to exit status to pop up.

How to create a chain between 2 programs input-to-output?

I have a console program in Linux that when I execute it, it reads some sensors conditions and writes them in the terminal and user can see. Also have another program that when I run, it asks for sensors value and I must put them by hand.
How can I make a connection between these two programs that number one can pass it's values automatically through number 2 and I shall not write them by hand?
For example:
Program number1:
#include <stdio.h>
int main()
{
int[10] sens_value=get_sensors_value();
for(int i=0; i<10; i++)
std::cout<<sens_value;
return 0;
}
Program number 2:
#include <stdio.h>
int main()
{
int[10] sens_values;
for(int i=0; i<10;i++)
std::cin>>sens_values[i];
...etc
return 0
}
You can make only one program and transform your main method in diferent methods and call them in the same program, but you cant conect programs.

Fork(), one process doesn't terminate?

I have never get this before; i'm doing a simple program: a father process which creates child processes, and after it terminates; this is the code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int child(pid_t pid)
{
printf("process %d is terminating\n",pid);
exit(EXIT_SUCCESS);
}
int main()
{
int i;
for(i = 0; i < 2; i++){
if(fork() == 0)
child(getpid());
}
printf("father, pid=%d terminated\n",getpid());
/*if(wait(NULL) == -1)
perror("wait");*/
exit(EXIT_SUCCESS);
}
when i run, all processes printed, but one process, i think father but i'm not sure, doesn't terminate because terminal is active(doesn't appear $);
insted, if i insert commented line with wait, program runs correctly; why this?
terminal output
If you look at the last run in the screen capture, you'll see "process 8429 is terminating" after the terminal prompt has been printed to the screen.
What appears to be happening is your "father" process happens to exit first, and your shell then outputs the prompt. Then, in the last case, the child process (PID 8429) printed its output and then exited.
So it is terminating, but sometimes the child process doesn't terminate until after the parent process exited and your shell process has already printed the prompt.
Just hit "enter" again when it does that, and you should see a proper shell prompt. Or even enter a command, and it should run normally.

Calling Objective-C class from basic C, xcode project

I am try to implement an cocoa application For USB Detection. Whenever user connects the USB it automatically detected, this entire part is one C program (Normal C) is orking Fine.
My need is if the system detects a particular USB device, I want to call another application (i.e. another cocoa application) using system function. I open that application, but my problem is if the user removes that USB device (this is also detected in C program), I want to close the second application automatically.
Or, if I add a cocoa user interface/objective-c class in the first application, is it possible to call that class from inside the C program?
One class you could use for this is NSDistributedNotificationCenter. Your C program would need to post notifications and your other program(s) would subscribe to them. The scenario would go like this:
Second App: on launch register to receive "USB Device Removed" messages
C Program: dectect removed USB device
C Program: post notification "USB Device Removed"
Second App: receives notification "USB Device Removed"
Second App: quits itself
Of course your C program would now become an objective-c program. There is also C alternative, which is CFNotificationCenterGetDistributedCenter.
If the object already exists and you can pass a pointer to it, you can use the Objective-C runtime function objc_msgSend. For example:
#include <objc/runtime.h>
#include <objc/message.h>
void sendDoneToApp(id app)
{
/* [app done]; */
/* get selector for "done" */
SEL doneSel = sel_registerName("done");
/* cast objc_msgSend to the type we need */
void (*sendNoArgsNoRet)(id obj, SEL selector) = (void (*)(id, SEL))objc_msgSend;
/* send the message */
sendNoArgsNoRet(app, doneSel);
}
Yes it is possible. You could for example look at how libdispatch/Grand Central Dispatch manages this.
The basic idea is to pass C function-pointers + void-pointers to your C library. And then in the passed function you can call Obj-C functions. Example:
struct test_s {
NSString *my_string;
};
void my_function(void *data) {
struct test_s *context = data;
NSLog(#"%#", [#"Hello " stringByAppendingString:context->my_string];
}
void main(void) {
struct test_s context = { #"World!" };
/* dispatch_sync_f is a C function unaware of Obj-C */
dispatch_sync_f(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
&context,
my_function);
}

C Callback in Objective-C (IOKIT)

I am trying to write some code that interacts with an USB device in Objective C, and I got stuck on setting the callback function for incoming reports. In my case it's an IOKIT function but I think the problem is more general as I (apparently) don't know how to correctly set a C callback function in Objective-C. I've got a Class "USBController" that handles the io functions
USBController.m:
#include <CoreFoundation/CoreFoundation.h>
#include <Carbon/Carbon.h>
#include <IOKit/hid/IOHIDLib.h>
#import "USBController.h"
static void Handle_IOHIDDeviceIOHIDReportCallback(
void * inContext, // context from IOHIDDeviceRegisterInputReportCallback
IOReturn inResult, // completion result for the input report operation
void * inSender, // IOHIDDeviceRef of the device this report is from
IOHIDReportType inType, // the report type
uint32_t inReportID, // the report ID
uint8_t * inReport, // pointer to the report data
CFIndex InReportLength) // the actual size of the input report
{
printf("hello"); //just to see if the function is called
}
#implementation USBController
- (void)ConnectToDevice {
...
IOHIDDeviceRegisterInputReportCallback(tIOHIDDeviceRefs[0], report, reportSize,
Handle_IOHIDDeviceIOHIDReportCallback,(void*)self);
...
}
...
#end
All the functions are also declared in the header file.
I think I did pretty much the same as what I've found here, but it doesn't work. The project compiles nicely and everything works up till the moment there is input and the callback function is to be called. Then I get an "EXC_BAD_ACCESS" error. The first three arguments of the function are correct. I'm not so sure about the context..
What did I do wrong?
I am not sure at all that your EXEC_BAD_ACCESS depends on your callback. Indeed, if you say that it is called (I suppose you see the log) and since it only logs a message, there should be no problem with this.
EXEC_BAD_ACCESS is caused by an attempt to access an already deallocated object. You can get more information in two ways:
execute the program in debug mode, so when it crashes you will be able to see the stack content;
activate NSZombies or run the program using the performance tool Zombies; this will tell you exactly which object was accessed after its deallocation.
I know how to fix this. When calling this:
IOHIDDeviceRegisterInputReportCallback(tIOHIDDeviceRefs[0], report, reportSize,
Handle_IOHIDDeviceIOHIDReportCallback,(void*)self);
You don't include the code for the creation/type of the value called report. However the method name "Handle_IOHIDDeviceIOHIDReportCallback" comes from an Apple document where there is an error in the creation of the report value. https://developer.apple.com/library/archive/technotes/tn2187/_index.html
CFIndex reportSize = 64;
uint8_t report = malloc( reportSize ); // <---- WRONG
IOHIDDeviceRegisterInputReportCallback( deviceRef,
report,
reportSize,
Handle_IOHIDDeviceIOHIDReportCallback,
context );
Instead do this:
uint8_t *report = (uint8_t *)malloc(reportSize);