Symbol Device Kill Process - windows-mobile-6.5

I'm trying to see how many instances of an application are running on a MC65 device, a Windows Mobile 6.5 device. Then if there is more than one instance of the application running kill all instances and run the application. I've tried that code here. But it doesn't work on the MC65 device. I believe this is because it is a symbol device and I've read somewhere that they act differently than non-symbol devices.
Does anyone know how to find out what processes are running on a symbol device programatically?
Update: Upon further testing the device is having problems creating a snapshot of the running processes. Still haven't found a solution.

Taking a snapshot should work fine BUT you have to use a flag to avoid memory limitations throwing an exception:
[Flags]
private enum SnapshotFlags : uint
{
HeapList = 0x00000001,
Process = 0x00000002,
Thread = 0x00000004,
Module = 0x00000008,
Module32 = 0x00000010,
Inherit = 0x80000000,
All = 0x0000001F,
NoHeaps = 0x40000000
}
Then in a normal call to CreateToolhelp32Snapshot you can get a list of processes:
public static Dictionary<UInt32, process> getProcessNameList()
{
int iCnt = 0;
//List<processnames> name_list = new List<processnames>();
Dictionary<UInt32, process> _pList = new Dictionary<uint, process>();
uint procID = 0;
IntPtr pHandle = CreateToolhelp32Snapshot(SnapshotFlags.Process | SnapshotFlags.NoHeaps, procID);
if ((Int32)pHandle == INVALID_HANDLE_VALUE)
throw new Exception("CreateToolhelp32Snapshot error: " + Marshal.GetLastWin32Error().ToString());
if ((int)pHandle != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pEntry = new PROCESSENTRY32();
pEntry.dwSize = (uint)Marshal.SizeOf(pEntry);
if (Process32First(pHandle, ref pEntry) == 1)
{
do
{
//name_list.Add(new processnames(pEntry.th32ProcessID, pEntry.szExeFile));
_pList[pEntry.th32ProcessID] = new process(pEntry.th32ProcessID, pEntry.szExeFile, new List<thread>());
iCnt++;
} while (Process32Next(pHandle, ref pEntry) == 1);
}
else
System.Diagnostics.Debug.WriteLine("Process32First error: " + Marshal.GetLastWin32Error().ToString());
CloseToolhelp32Snapshot(pHandle);
}
return _pList;
}
The above code is part of my remote ProcessorUsage test application.
Nevertheless normal windows mobile application will terminate them self if a previous instance is already running. That is also the default when you create and run a SmartDevice project in CSharp or CPP targetting "Windows Mobile ...".
If you target a Standard Windows CE based SDK, there is no automatic code generated to prevent multiple instances in the start code of the app.
Let us know, if you still need assistance.

Related

FreeBSD newbus driver loading succesfully but cant create /dev/** file and debugging

I am installing a new newbuf driver on FreeBSD 10.0 . After compiling with make the driver.ko file has been created and than kldload can load successfully. kldload returns 0 and I can see the device at the kldstat output. When attempt to use the driver opening the /dev/** file, the file is not exist.
I think that this /dev/** file should be created by make_dev function which is located in device_attach member method. To test if the kldload reaches this attaching function; when write printf and uprintf to debug the driver, I can not see any output at console nor dmesg output.
But the problem is after writing printf at beginnings (after local variable definitions) of device_identify and device_probe functions, I can't see any output again at console nor dmesg.
My question is that even if the physical driver has problem (not located etc.), should I see the ouput of printf at the device_identify member function which is called by kldload at starting course (I think)?
Do I have a mistake when debugging newbuf driver with printf (I also tried a hello_world device driver and at this driver I can take output of printf at dmesg)?
Mainly how can I test/debug this driver's kldload processes?
Below some parts of my driver code (I think at least I should see MSG1, but I can not see):
struct mydrv_softc
{
device_t dev;
};
static devclass_t mydrv_devclass;
static struct cdevsw mydrv_cdevsw = {
.d_version = D_VERSION,
.d_name = "mydrv",
.d_flags = D_NEEDGIANT,
.d_open = mydrv_open,
.d_close = mydrv_close,
.d_ioctl = mydrv_ioctl,
.d_write = mydrv_write,
.d_read = mydrv_read
};
static void mydrv_identify (driver_t *driver, device_t parent) {
devclass_t dc;
device_t child;
printf("MSG1: The process inside the identfy function.");
dc = devclass_find("mydrv");
if (devclass_get_device(dc, 0) == NULL) {
child = BUS_ADD_CHILD(parent, 0, "mydrv", -1);
}
}
static int mydrv_probe(device_t dev) {
printf("MSG2: The process inside the probe function.");
mydrv_init();
if (device_get_unit(dev) != 0)
return (ENXIO);
device_set_desc(dev, "FreeBSD Device Driver");
return (0);
}
static int mydrv_attach(device_t dev) {
struct mydrv_softc *sc;
device_printf(dev, "MSG3: The process will make attachment.");
sc = (struct mydrv_softc *) device_get_softc(dev);
sc->dev = (device_t)make_dev(&mydrv_cdevsw, 0, UID_ROOT, GID_WHEEL, 0644, "mydrv_drv");
return 0;
}
static int mydrv_detach(device_t dev) {
struct mydrv_softc *sc;
sc = (struct mydrv_softc *) device_get_softc(dev);
destroy_dev((struct cdev*)(sc->dev));
bus_generic_detach(dev);
return 0;
}
static device_method_t mydrv_methods[] = {
DEVMETHOD(device_identify, mydrv_identify),
DEVMETHOD(device_probe, mydrv_probe),
DEVMETHOD(device_attach, mydrv_attach),
DEVMETHOD(device_detach, mydrv_detach),
{ 0, 0 }
};
static driver_t mydrv_driver = {
"mydrv",
mydrv_methods,
sizeof(struct mydrv_softc),
};
DRIVER_MODULE(mydrv, ppbus, mydrv_driver, mydrv_devclass, 0, 0);
If you don't see your printf's output on your console then your device functions will probably not be called. Can you show us your module's code?
Have you used DRIVER_MODULE() or DEV_MODULE()?
What parent bus are you using?
I guess printf works fine, but I prefer to use device_printf as it also prints the device name, and will be easier when looking through logs or dmesg output. Also leave multiple debug prints and check the log files on your system. Most logs for the device drivers are logged in /var/log/messages. But check other log files too.
Are you running your code on a virtual machine? Some device drivers don't show up their device files in /dev if the OS is running on a virtual machine. You should probably run your OS on actual hardware for the device file to show up.
As far as I know, you can't see the output in dmesg if you cannot find the corresponding device file in /dev but you may have luck with logs as I mentioned.
The easiest way to debug is of course using the printf statements. Other than this, you can debug the kernel using gdb running on another system. I am not familiar with the exact process but I know you can do this. Google it.

FindFirstPrinterChangeNotification with network printer fails with ERROR_INVALID_HANDLE (called from service)

I want to monitor print jobs on remote (shared) printers from service. I have impersonation access token for user who connects printer (e.g. \PC-PRINTER\Canon Printer).
After impersonation as the user I call OpenPrinter to printer and then FindFirstPrinterChangeNotification. OpenPrinter succeeded but FindFirstPrinterChangeNotification failed with ERROR_INVALID_HANDLE error.
If I try it as normal user (owner of printer - not a service), all succeeded and notification are functional. Also if I try it on Windows XP it succeeded, it fails only on Windows 7 and probably Windows Vista.
I suppose that I have to set some security attributes for impersonation token or pass some other attributes to OpenPrinter. I have tried many things, but I didn't find solution.
My code example:
PRINTER_NOTIFY_OPTIONS_TYPE optionsType;
unsigned short jobFields[] = {JOB_NOTIFY_FIELD_PRINTER_NAME};
optionsType.Type = JOB_NOTIFY_TYPE;
optionsType.Count = 1;
optionsType.pFields = &jobFields[0];
PRINTER_NOTIFY_OPTIONS options;
options.Version = 2;
options.Count = 1;
options.pTypes = &optionsType;
options.Flags = 0;
DWORD dwFilter = PRINTER_CHANGE_DELETE_JOB | PRINTER_CHANGE_SET_JOB ;
HANDLE hPrinterHandle = NULL;
ImpersonateLoggedOnUser(hUserToken); //I retrieve token from printer owner's process (I try every process for this user)
OpenPrinter(L"\\\\PC-PRINTER\\Canon Printer", &hPrinterHandle, NULL); \\it succeeded and I try many other parameters as well
HANDLE hNotification = FindFirstPrinterChangeNotification(hPrinterHandle, dwFilter, 0, (LPVOID) &options);
if (hNotification == INVALID_HANDLE_VALUE)
{//it comes here, GetLastError() == ERROR_INVALID_HANDLE (Windows 7, process runs as service)
//it succeded on Windows XP or when process runs in printer owner context
}
RevertToSelf();
Thanks for any solution!

Local Hook not working

I have an application and wish to monitor MSWord keypressing (LOCAL HOOK), but I cant figure out how to find the pid to be used! The bellow CODE WORKS GOOD with global hook (pid = 0) and with (pid = GetCurrentThreadId). But doesn´t work with GetWindowThreadProcessId:
HWND hWindow = FindWindowEx(NULL,NULL,String("Notepad").w_str(),NULL);
if (!hWindow) {
ShowMessage("hWindow fail");
return;
}
unsigned long pid;
GetWindowThreadProcessId(hWindow ,&pid);
//pid = GetCurrentThreadId();
if (!hWindow) {
ShowMessage("pid fail");
return;
}
String s = "HookDLL.dll";
DllHandle=LoadLibrary(s.w_str());
HOOKFCT_2 InstHook=reinterpret_cast<HOOKFCT_2> (GetProcAddress(DllHandle,"InstallHook"));
if(!InstHook(pid, (void *)(callIt) ))
{
Label1->Caption="Unable to install mouse hook!";
}
else Label1->Caption="Mouse hook installed!";
I will be very, very gratefuLl for any light on the problem...
Notice:
I wish a hook to MSWord only.
The above code works, failling only when trying to hook on another application (i.e.: not using pid=0 or pid=GetCurrentThreadId), resulting in = "Unable to install mouse hook!".
I already try FindWindow, FindWindowEx, GetForegroundWindow, GetActiveWindow; since not of this works, I belive the problem is GetWindowThreadProcessId.
SetWindowsHookEx requires thread ID, not process ID. Pass thread ID instead:
DWORD threadID = GetWindowThreadProcessId(hWindow, 0);
if(!InstHook(threadID, (void *)(callIt) )) {...}

C# Winspool.drv "Cannot open printer"

I'm having a problem calling Winspool.drv "OpenPrinter" when I run my program in standard user acccount. But when I ran my program in Administrator account. It can properly execute API call.
I am trying to call OpenPrinter using this API
[DllImport("WinSpool.drv", SetLastError = true)]
static extern unsafe bool OpenPrinter (string pPrinterName, int* phPrinter, void* pDefault);
and implementing it using this code
static unsafe int CSOpenPrinter(string printerName)
{
bool bResult;
int hPrinter;
PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS();
//int rawsize = Marshal.SizeOf(pd);
//IntPtr pdPtr = Marshal.AllocHGlobal(rawsize);
//pd.pDatatype = null;
//pd.pDevMode = null;
pd.DesiredAccess = PRINTER_ALL_ACCESS;
bResult = OpenPrinter(printerName, &hPrinter, &pd);
System.Diagnostics.Debug.WriteLine("bResult: " + bResult);
if (!bResult)
{
throw new ApplicationException("Cannot open printer '" +
printerName + "' " +
Marshal.GetLastWin32Error());
}
return hPrinter;
}
Ok again, that code works perfectly when I try to make my program "Run As Administrator". How do I make my application run as a Administrator without right clicking on the application and selecting "Run As Administrator"?
I believe this is a UAC problem, but can you give me an Idea how to solve this? Is adding app.manifest will help? Can you give me an exampple?
Best to all
What are you trying to do with the printer? Your code is asking for full access and so requires admin access.
If you just want to use the printer, request PRINTER_ACCESS_USE access instead.
If it is actually an admin process, then add an appropriate manifest to the executable to tell windows that it needs admin access.
Add manifest file to your project. Like here

Windows - Prevent crashes "Checking for a solution..." and "Restarting the program..."

This may not be a purely programming related question, but I come across this often during development. When my app crashes and I choose to kill it, Windows automatically throws up a "Checking for a solution..." dialog box. When I hit the cancel button on that I get another dialog box that says "Restarting the program..." Is there a way to prevent this behavior? When I stop an app I'd prefer if it were silently killed. I'm using Windows 7 if the platform is important.
Although Microsoft recommends using a newer replacement API available only on Windows Vista and later, there is an API which works for all versions of Windows from XP onward: AddERExcludedApplication(). This function takes the module name without path information (e.g., "myprogram.exe") for which error reporting is to be disabled.
The new method available only Windows Vista and later is to call WerAddExcludedApplication() function. This API allows you to specify whether it should change the HKEY_CURRENT_USER registry hive, or the HKEY_LOCAL_MACHINE registry hive. Be sure to set this for the HKCU if the HKLM set fails, such as:
typedef BOOL (*ADD_MER_EXCLUDED_APP_XP) (PCWSTR);
typedef BOOL (*ADD_MER_EXCLUDED_APP_VISTA) (PCWSTR, BOOL);
bool disable_microsoft_error_reporting(PCWSTR wz_app)
{
const WCHAR * const WZ_MER_DLL_XP = L"faultrep.dll";
const char * const SZ_MER_PROC_XP = "AddERExcludedApplicationW";
const WCHAR * const WZ_MER_DLL_VISTA = L"wer.dll";
const char * const SZ_MER_PROC_VISTA = "WerAddExcludedApplicationW";
const int WER_EXCLUDE_FOR_ALL_USERS = TRUE;
const int WER_EXCLUDE_FOR_THIS_USER = FALSE;
HANDLE hlib_error_reports_xp = NULL;
HANDLE hlib_error_reports_vista = NULL;
ADD_MER_EXCLUDED_APP_XP add_mer_excluded_app_xp = NULL;
ADD_MER_EXCLUDED_APP_VISTA add_mer_excluded_app_vista = NULL;
bool success = false;
// First, attempt the API that has been around since XP.
hlib_error_reports_xp = LoadLibrary(WZ_MER_DLL_XP);
if (hlib_error_reports_xp)
{
add_mer_excluded_app_xp = (ADD_MER_EXCLUDED_APP_XP)GetProcAddress(hlib_error_reports_xp, SZ_MER_PROC_XP);
if (add_mer_excluded_app_xp)
success = add_mer_excluded_app_xp(wz_app);
FreeLibrary(hlib_error_reports_xp);
hlib_error_reports_xp = NULL;
add_mer_excluded_app_xp = NULL;
if (success)
return true;
}
// That did not succeed. Attempt the Vista API.
hlib_error_reports_vista = LoadLibrary(WZ_MER_DLL_VISTA);
if (hlib_error_reports_vista)
{
add_mer_excluded_app_vista = (ADD_MER_EXCLUDED_APP_VISTA)GetProcAddress(hlib_error_reports_vista, SZ_MER_PROC_VISTA);
if (add_mer_excluded_app_vista)
{
success = (S_OK == add_mer_excluded_app_vista(wz_app, WER_EXCLUDE_FOR_ALL_USERS));
if (!success)
success = (S_OK == add_mer_excluded_app_vista(wz_app, WER_EXCLUDE_FOR_THIS_USER));
}
FreeLibrary(hlib_error_reports_vista);
hlib_error_reports_vista = NULL;
add_mer_excluded_app_vista = NULL;
if (success)
return true;
}
// Nothing worked. Fail.
return false;
}
To further curtail the execution of the WER components, imeplement an unhandled exception filter and pass it to: SetUnhandledExceptionFilter() function. To shunt WER, your filter must never return EXCEPTION_CONTINUE_SEARCH or EXCEPTION_EXECUTE_HANDLER.
One of the drawbacks of implementing the SetUnhandledExceptionFilter() function is that it interferes with Just-in-time debugging.
You mention you want the app to be "silently killed." In that case:
LONG WINAPI global_exception_filter(struct _EXCEPTION_POINTERS *exception_info)
{
ExitProcess(0xDEDD000D);
}
int WINAPI WinMain(
HINSTANCE _hinstance,
HINSTANCE hinstance_prev,
LPSTR sz_cmd_line,
int cmd_show
)
{
SetUnhandledExceptionFilter(global_exception_filter);
/* ... */
}
Will cause the application to immediately vanish upon unhandled exception. N.B., the exit code to return is a matter of taste.
Check out the answers on these questions:
How do I disable the ‘Debug / Close Application’ dialog on Windows Vista?
Hide Error Report window
I realize that others have answered with ways to work around this, but...
Let's not forget that the best way to protect against this is to write a program that doesn't crash. :-) You shouldn't be seeing this if you are using memory correctly and not hanging the GUI thread.
Altering the behavior of an application crash is a great way to introduce subtle and deadly bugs. See also this blog post from Microsoft's Raymond Chen.
Take a look at the Windows Error Reporting APIs.

Resources