synaTudor-work.patch 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  1. diff --git a/libtudor/meson.build b/libtudor/meson.build
  2. index d2556af..0854792 100644
  3. --- a/libtudor/meson.build
  4. +++ b/libtudor/meson.build
  5. @@ -74,23 +74,26 @@ driver_dll_names = [
  6. add_global_arguments('-Wno-incompatible-pointer-types', language : 'c')
  7. add_global_arguments('-g', language : ['c', 'cpp'])
  8. -add_global_arguments('-fsanitize=address', language : ['c', 'cpp'])
  9. +# add_global_arguments('-fsanitize=address', language : ['c', 'cpp'])
  10. bridge_proj = subproject('cryptbridge')
  11. cryptbridge_dep = bridge_proj.get_variable('cryptbridge_dep')
  12. -driver_dlls = custom_target('driver-download',
  13. - output: driver_dll_names,
  14. - input: ['download_driver.sh', 'installer.sha'],
  15. - command: [find_program('bash'), '@INPUT0@', '@INPUT1@', '@PRIVATE_DIR@', '@OUTDIR@'] + driver_dll_names
  16. -)
  17. -
  18. -driver_dll_blobs = generator(find_program('ld'),
  19. - output: '@BASENAME@.o',
  20. - arguments: ['-r', '-b', 'binary', '-o', '@OUTPUT@', '@INPUT@']
  21. -).process([driver_dlls])
  22. +# Local build: use pre-extracted Synaptics 5.5.2731.1050 DLLs instead of
  23. +# the original download_driver.sh (which was hardcoded to the author's machine).
  24. +driver_dlls = []
  25. +foreach n : driver_dll_names
  26. + driver_dlls += custom_target('blob-' + n,
  27. + output: n + '.o',
  28. + input: files('/home/nebulon/projects/fingerprint/driverdlls/' + n),
  29. + command: ['sh', '-c',
  30. + 'mkdir -p libtudor && cp "$1" "libtudor/$2" && exec ld -r -b binary -o "$3" "libtudor/$2"',
  31. + 'sh', '@INPUT@', n, '@OUTPUT@'],
  32. + build_by_default: true,
  33. + )
  34. +endforeach
  35. libtudor_flags = []
  36. @@ -110,7 +113,7 @@ libtudor_inc = include_directories('inc')
  37. # wudm1_inc = include_directories('src/wudm1_inc')
  38. # winapi_inc = include_directories('src/winapi')
  39. -libtudor = shared_library('tudor', [libtudor_src, driver_dll_blobs],
  40. +libtudor = shared_library('tudor', [libtudor_src, driver_dlls],
  41. dependencies: [thread_dep, libcrypto_dep, libusb_dep, cryptbridge_dep],
  42. c_args: ['-D_GNU_SOURCE'] + libtudor_flags,
  43. cpp_args: ['-D_GNU_SOURCE'] + libtudor_flags,
  44. diff --git a/libtudor/src/loader.c b/libtudor/src/loader.c
  45. index be29477..4402170 100644
  46. --- a/libtudor/src/loader.c
  47. +++ b/libtudor/src/loader.c
  48. @@ -67,6 +67,8 @@ bool load_dll(struct dll_image *dll, const char *name, uint8_t *data, uint32_t s
  49. //Copy data
  50. pe_copy_mem(&pe, 0, pe.image_size, image_mem);
  51. log_debug("Copied image memory to mapping at %p - %p", image_mem, image_mem + pe.image_size);
  52. + //Machine-readable load line for post-mortem crash symbolization
  53. + fprintf(stderr, "TUDOR_LOAD %s base=%p size=%x\n", name, image_mem, pe.image_size);
  54. //Resolve imports
  55. for(int i = 0; i < pe.num_import_libs; i++) {
  56. diff --git a/libtudor/src/tudor/driver.c b/libtudor/src/tudor/driver.c
  57. index 156c9de..63a306d 100644
  58. --- a/libtudor/src/tudor/driver.c
  59. +++ b/libtudor/src/tudor/driver.c
  60. @@ -40,7 +40,7 @@ static struct winmodule ntdll_module = {
  61. typedef BOOL __winfnc (*api_DllMain)(HANDLE hinstDLL, int fdwReason, void *lpReserved);
  62. struct windrv_dll *tudor_adapter_dll, *tudor_driver_dll;
  63. -WINBIO_SENSOR_INTERFACE *tudor_sensor_adapter;
  64. +WINBIO_SENSOR_INTERFACE_V1 *tudor_sensor_adapter;
  65. WINBIO_ENGINE_INTERFACE *tudor_engine_adapter;
  66. static DRIVER_OBJECT umdf_driver;
  67. @@ -126,10 +126,34 @@ bool tudor_init() {
  68. winmodule_set_cur(&tudor_adapter_dll->module);
  69. HRESULT hres;
  70. - if((hres = ((api_WbioQuerySensorInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQuerySensorInterface"))(&tudor_sensor_adapter)) != 0) {
  71. + if((hres = ((api_WbioQuerySensorInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQuerySensorInterface"))((WINBIO_SENSOR_INTERFACE**) &tudor_sensor_adapter)) != 0) {
  72. log_error("Error querying sensor interface: 0x%x!", hres);
  73. return false;
  74. }
  75. + //Snapshot the sensor interface table, then restore every function slot
  76. + //from the pristine static image (the relinked adapter's runtime state
  77. + //overlaps the table's static storage in .data and clobbers slots).
  78. + {
  79. + WINBIO_SENSOR_INTERFACE_V1 *snapshot = (WINBIO_SENSOR_INTERFACE_V1*) malloc(sizeof(WINBIO_SENSOR_INTERFACE_V1));
  80. + memcpy(snapshot, tudor_sensor_adapter, sizeof(WINBIO_SENSOR_INTERFACE_V1));
  81. + tudor_sensor_adapter = snapshot;
  82. +
  83. + uintptr_t mod_base = (uintptr_t) tudor_adapter_dll->image.base_addr;
  84. + static const uint32_t sensor_slot_rvas[15] = {
  85. + 0x005b50, 0x005d50, 0x005ee0, 0x005ff0, 0x006250,
  86. + 0x006460, 0x0065d0, 0x006660, 0x0066f0, 0x006bf0,
  87. + 0x006ec0, 0x006f50, 0x0070b0, 0x0072f0, 0x0075b0,
  88. + };
  89. + void **slots = (void**) tudor_sensor_adapter;
  90. + for(int i = 0; i < 15; i++) {
  91. + slots[4 + i] = (void*) (mod_base + sensor_slot_rvas[i]);
  92. + }
  93. + //Alias the Windows 10 names onto the legacy entry points.
  94. + tudor_sensor_adapter->PipelineInit = (IBIO_SENSOR_PIPELINE_INIT_FN*) tudor_sensor_adapter->Reset;
  95. + tudor_sensor_adapter->PipelineCleanup = (IBIO_SENSOR_PIPELINE_CLEANUP_FN*) tudor_sensor_adapter->Cancel;
  96. + tudor_sensor_adapter->Activate = (IBIO_SENSOR_ACTIVATE_FN*) tudor_sensor_adapter->Reset;
  97. + tudor_sensor_adapter->Deactivate = (IBIO_SENSOR_DEACTIVATE_FN*) tudor_sensor_adapter->Cancel;
  98. + }
  99. if((hres = ((api_WbioQueryEngineInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQueryEngineInterface"))(&tudor_engine_adapter)) != 0) {
  100. log_error("Error querying engine interface: 0x%x!", hres);
  101. return false;
  102. diff --git a/libtudor/src/tudor/driver_wudf1.cpp b/libtudor/src/tudor/driver_wudf1.cpp
  103. index dde101b..bcc5f1c 100644
  104. --- a/libtudor/src/tudor/driver_wudf1.cpp
  105. +++ b/libtudor/src/tudor/driver_wudf1.cpp
  106. @@ -50,6 +50,10 @@ static winmodule ntdll_module = {
  107. .environ = (const char*[]) { NULL }
  108. };
  109. +//WUDF call tracing for debugging: compile-in, enabled via env TUDOR_WUDF_TRACE
  110. +static bool tudor_wudf_trace = (getenv("TUDOR_WUDF_TRACE") != NULL);
  111. +#define WUDF_TRACE(...) do { if(tudor_wudf_trace) { printf("[WUDF] " __VA_ARGS__); fflush(stdout); } } while(0)
  112. +
  113. #define DLL_PROCESS_ATTACH 1
  114. #define DLL_PROCESS_DETACH 0
  115. #define DLL_THREAD_ATTACH 2
  116. @@ -57,9 +61,16 @@ static winmodule ntdll_module = {
  117. typedef BOOL __winfnc (*api_DllMain)(HANDLE hinstDLL, int fdwReason, void *lpReserved);
  118. struct windrv_dll *tudor_adapter_dll, *tudor_driver_dll;
  119. -WINBIO_SENSOR_INTERFACE *tudor_sensor_adapter;
  120. +WINBIO_SENSOR_INTERFACE_V1 *tudor_sensor_adapter;
  121. WINBIO_ENGINE_INTERFACE *tudor_engine_adapter;
  122. +//Dummy engine adapter used with TUDOR_NO_ENGINE (for sensor bring-up tests)
  123. +static HRESULT dummy_engine_attach(WINBIO_PIPELINE *pipeline) { (void) pipeline; return ERROR_SUCCESS; }
  124. +static HRESULT dummy_engine_pipeline_init(WINBIO_PIPELINE *pipeline) { (void) pipeline; return ERROR_SUCCESS; }
  125. +static HRESULT dummy_engine_pipeline_cleanup(WINBIO_PIPELINE *pipeline) { (void) pipeline; return ERROR_SUCCESS; }
  126. +static HRESULT dummy_engine_activate(WINBIO_PIPELINE *pipeline) { (void) pipeline; return ERROR_SUCCESS; }
  127. +static HRESULT dummy_engine_deactivate(WINBIO_PIPELINE *pipeline) { (void) pipeline; return ERROR_SUCCESS; }
  128. +
  129. static DRIVER_OBJECT umdf_driver;
  130. struct winwdf_driver *tudor_wdf_driver;
  131. @@ -89,7 +100,6 @@ struct windrv_dll tudor_windrv_dlls[] = {
  132. };
  133. -
  134. #define DEFINE_GUID11(name, a, b, c, d, e, f, g, h, i, j, k) \
  135. static const GUID_DLL name = { \
  136. (a), (b), (c), \
  137. @@ -209,7 +219,8 @@ struct IObjectCleanup;
  138. class MyDevInit : public IWDFDeviceInitialize {
  139. public:
  140. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) {
  141. - printf("QueryInterface\r\n");
  142. + LPOLESTR _s; StringFromIID(riid, &_s);
  143. + std::wcout << L"[QI] " << _s << (ppvObject ? (void*)*ppvObject : (void*)0) << std::endl;
  144. return 0;
  145. }
  146. virtual ULONG STDMETHODCALLTYPE AddRef(void) {
  147. @@ -241,6 +252,9 @@ class MyDevInit : public IWDFDeviceInitialize {
  148. _Out_ IWDFNamedPropertyStore **ppPropStore,
  149. /* [annotation][unique][out] */
  150. _Out_opt_ WDF_PROPERTY_STORE_DISPOSITION *pDisposition) {
  151. + if(ppPropStore) *ppPropStore = NULL;
  152. + if(pDisposition) *pDisposition = (WDF_PROPERTY_STORE_DISPOSITION) 0;
  153. +
  154. printf("RetrieveDevicePropertyStore\r\n");
  155. return 0;
  156. }
  157. @@ -304,31 +318,39 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  158. public:
  159. virtual HRESULT STDMETHODCALLTYPE DeleteWdfObject( void) {
  160. + printf("[MEM] DeleteWdfObject\n"); fflush(stdout);
  161. printf("DeleteWdfObject\r\n");
  162. return 0;
  163. }
  164. + void *assigned_context = NULL;
  165. virtual HRESULT STDMETHODCALLTYPE AssignContext(
  166. /* [annotation][unique][in] */
  167. _In_opt_ __drv_aliasesMem IObjectCleanup *pCleanupCallback,
  168. /* [annotation][unique][in] */
  169. - _In_opt_ __drv_aliasesMem void *pContext) {
  170. - printf("AssignContext\r\n");
  171. + _In_opt_ __drv_aliasesMem void *pContext) {
  172. + printf("[MEM] AssignContext\n"); fflush(stdout);
  173. + printf("AssignContext(%p)\r\n", pContext);
  174. + assigned_context = pContext;
  175. return 0;
  176. }
  177. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  178. /* [annotation][out] */
  179. _Out_ void **ppvContext) {
  180. - printf("RetrieveContext\r\n");
  181. + printf("[MEM] RetrieveContext\n"); fflush(stdout);
  182. + if(ppvContext) *ppvContext = assigned_context;
  183. + printf("RetrieveContext -> %p\r\n", assigned_context);
  184. return 0;
  185. }
  186. virtual void STDMETHODCALLTYPE AcquireLock( void) {
  187. + printf("[MEM] AcquireLock\n"); fflush(stdout);
  188. printf("AcquireLock\r\n");
  189. }
  190. virtual void STDMETHODCALLTYPE ReleaseLock( void) {
  191. + printf("[MEM] ReleaseLock\n"); fflush(stdout);
  192. printf("ReleaseLock\r\n");
  193. }
  194. public:
  195. @@ -338,7 +360,7 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  196. /* [annotation][out] */
  197. _Out_ PROPVARIANT *pv){
  198. std::wcout << L"=====================================" << std::endl;
  199. - std::wcout << L"GetNamedValue " << pszName << std::endl;
  200. + std::cout << "GetNamedValue " << utf16le_to_utf8(pszName) << std::endl;
  201. std::string fname = utf16le_to_utf8(pszName);
  202. std::cout << fname << std::endl;
  203. std::wcout << L"=====================================" << std::endl;
  204. @@ -348,6 +370,11 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  205. std::vector<char> buf((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
  206. std::cout << "Loaded " << buf.size() << " bytes of calibration data" << std::endl;
  207. if(buf.size() == 0) {
  208. + //No stored calibration data yet: report an empty value.
  209. + //The vt tag MUST be initialized, the caller passes an
  210. + //uninitialized PROPVARIANT buffer.
  211. + memset(pv, 0, sizeof(*pv));
  212. + pv->vt = VT_DECIMAL;
  213. DECIMAL_SETZERO(pv->decVal);
  214. } else {
  215. pv->vt = VT_BLOB;
  216. @@ -365,7 +392,9 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  217. std::cout << "UINT " << fname << " = " << pv->uintVal << std::endl;
  218. }
  219. else {
  220. - DECIMAL_SETZERO(pv->decVal);
  221. + memset(pv, 0, sizeof(*pv));
  222. + pv->vt = VT_UINT;
  223. + pv->uintVal = 0;
  224. std::cout << "UINT " << fname << " not found" << std::endl;
  225. }
  226. }
  227. @@ -389,7 +418,7 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  228. //PropVariantToStringAlloc(*pv, &buf);
  229. std::wcout << L"=====================================" << std::endl;
  230. - std::wcout << L"SetNamedValue " << pszName << "=" << pv->vt << std::endl;
  231. + std::cout << "SetNamedValue " << utf16le_to_utf8(pszName) << "=" << pv->vt << std::endl;
  232. std::string str_u8 = utf16le_to_utf8(pszName);
  233. std::cout << str_u8 << std::endl;
  234. switch(pv->vt) {
  235. @@ -447,13 +476,14 @@ struct MyNamedPropertyStore : public IWDFNamedPropertyStore2 {
  236. virtual HRESULT STDMETHODCALLTYPE DeleteNamedValue(
  237. /* [annotation][string][in] */
  238. _In_ LPCWSTR pwszName){
  239. - std::wcout << L"DeleteNamedValue " << pwszName<< std::endl;
  240. + std::cout << "DeleteNamedValue " << utf16le_to_utf8(pwszName) << std::endl;
  241. return 0;
  242. }
  243. };
  244. struct MyMem : public IWDFMemory {
  245. + void *assigned_context = NULL;
  246. public:
  247. MyMem(void *b, SIZE_T s) {
  248. buf = b;
  249. @@ -489,14 +519,16 @@ struct MyMem : public IWDFMemory {
  250. _In_opt_ __drv_aliasesMem void *pCleanupCallback,
  251. /* [annotation][unique][in] */
  252. _In_opt_ __drv_aliasesMem void *pContext) {
  253. - printf("AssignContext\r\n");
  254. + assigned_context = pContext;
  255. + printf("AssignContext(%p)\r\n", pContext);
  256. return 0;
  257. }
  258. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  259. /* [annotation][out] */
  260. _Out_ void **ppvContext) {
  261. - printf("RetrieveContext\r\n");
  262. + if(ppvContext) *ppvContext = assigned_context;
  263. + printf("RetrieveContext -> %p\r\n", assigned_context);
  264. return 0;
  265. }
  266. @@ -513,6 +545,7 @@ struct MyMem : public IWDFMemory {
  267. _In_ IWDFMemory *Source,
  268. /* [annotation][unique][in] */
  269. _In_opt_ PWDFMEMORY_OFFSET SourceOffset){
  270. + printf("[MEM] CopyFromMemory\n"); fflush(stdout);
  271. printf("CopyFromMemory\r\n");
  272. return 0;
  273. }
  274. @@ -525,6 +558,7 @@ struct MyMem : public IWDFMemory {
  275. void *TargetBuffer,
  276. /* [annotation][in] */
  277. _In_ SIZE_T NumOfBytesToCopyTo){
  278. + printf("[MEM] CopyToBuffer\n"); fflush(stdout);
  279. printf("CopyToBuffer\r\n");
  280. return 0;
  281. }
  282. @@ -537,12 +571,14 @@ struct MyMem : public IWDFMemory {
  283. void *SourceBuffer,
  284. /* [annotation][in] */
  285. _In_ SIZE_T NumOfBytesToCopyFrom){
  286. + printf("[MEM] CopyFromBuffer\n"); fflush(stdout);
  287. printf("CopyFromBuffer\r\n");
  288. return 0;
  289. }
  290. virtual SIZE_T STDMETHODCALLTYPE GetSize( void){
  291. + printf("[MEM] GetSize\n"); fflush(stdout);
  292. printf("GetSize\r\n");
  293. return size;
  294. }
  295. @@ -551,6 +587,7 @@ struct MyMem : public IWDFMemory {
  296. virtual void *STDMETHODCALLTYPE GetDataBuffer(
  297. /* [annotation][unique][out] */
  298. _Out_opt_ SIZE_T *BufferSize){
  299. + printf("[MEM] GetDataBuffer\n"); fflush(stdout);
  300. if(BufferSize) {
  301. *BufferSize = size;
  302. }
  303. @@ -564,6 +601,7 @@ struct MyMem : public IWDFMemory {
  304. void *Buffer,
  305. /* [annotation][in] */
  306. _In_ SIZE_T BufferSize){
  307. + printf("[MEM] SetBuffer\n"); fflush(stdout);
  308. printf("SetBuffer\r\n");
  309. buf = Buffer;
  310. size = BufferSize;
  311. @@ -574,6 +612,7 @@ struct MyMem : public IWDFMemory {
  312. };
  313. struct MyRequest : public IWDFIoRequest {
  314. + void *assigned_context = NULL;
  315. public:
  316. MyRequest(WDF_REQUEST_TYPE t, ULONG c, MyMem *out, MyMem *in) {
  317. reqType = t;
  318. @@ -582,12 +621,14 @@ struct MyRequest : public IWDFIoRequest {
  319. inMem = in;
  320. complete = FALSE;
  321. informationSize = 0;
  322. + completionStatus = 0;
  323. }
  324. WDF_REQUEST_TYPE reqType;
  325. ULONG ctl;
  326. BOOL complete;
  327. LONG_PTR informationSize;
  328. + HRESULT completionStatus;
  329. public:
  330. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) {
  331. LPOLESTR str;
  332. @@ -617,14 +658,16 @@ struct MyRequest : public IWDFIoRequest {
  333. _In_opt_ __drv_aliasesMem void *pCleanupCallback,
  334. /* [annotation][unique][in] */
  335. _In_opt_ __drv_aliasesMem void *pContext) {
  336. - printf("AssignContext\r\n");
  337. + assigned_context = pContext;
  338. + printf("AssignContext(%p)\r\n", pContext);
  339. return 0;
  340. }
  341. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  342. /* [annotation][out] */
  343. _Out_ void **ppvContext) {
  344. - printf("RetrieveContext\r\n");
  345. + if(ppvContext) *ppvContext = assigned_context;
  346. + printf("RetrieveContext -> %p\r\n", assigned_context);
  347. return 0;
  348. }
  349. @@ -641,7 +684,9 @@ struct MyRequest : public IWDFIoRequest {
  350. _In_ HRESULT CompletionStatus,
  351. /* [annotation][in] */
  352. _In_ SIZE_T Information){
  353. + printf("[REQ] CompleteWithInformation\n"); fflush(stdout);
  354. printf("CompleteWithInformation\r\n");
  355. + completionStatus = CompletionStatus;
  356. complete = TRUE;
  357. }
  358. @@ -649,6 +694,7 @@ struct MyRequest : public IWDFIoRequest {
  359. virtual void STDMETHODCALLTYPE SetInformation(
  360. /* [annotation][in] */
  361. _In_ ULONG_PTR Information){
  362. + printf("[REQ] SetInformation\n"); fflush(stdout);
  363. printf("SetInformation size=%lld\r\n", Information);
  364. informationSize = Information;
  365. }
  366. @@ -657,7 +703,9 @@ struct MyRequest : public IWDFIoRequest {
  367. virtual void STDMETHODCALLTYPE Complete(
  368. /* [annotation][in] */
  369. _In_ HRESULT CompletionStatus){
  370. + printf("[REQ] Complete\n"); fflush(stdout);
  371. printf("Complete: %lx\r\n", (unsigned long)CompletionStatus);
  372. + completionStatus = CompletionStatus;
  373. complete = TRUE;
  374. }
  375. @@ -667,11 +715,13 @@ struct MyRequest : public IWDFIoRequest {
  376. _In_ void *pCompletionCallback,
  377. /* [annotation][unique][in] */
  378. _In_opt_ void *pContext){
  379. + printf("[REQ] SetCompletionCallback\n"); fflush(stdout);
  380. printf("SetCompletionCallback\r\n");
  381. }
  382. virtual WDF_REQUEST_TYPE STDMETHODCALLTYPE GetType( void){
  383. + printf("[REQ] GetType\n"); fflush(stdout);
  384. printf("GetType\r\n");
  385. return reqType;
  386. }
  387. @@ -684,6 +734,10 @@ struct MyRequest : public IWDFIoRequest {
  388. _Out_opt_ USHORT *pFileAttributes,
  389. /* [annotation][unique][out] */
  390. _Out_opt_ USHORT *pShareAccess){
  391. + if(pOptions) *pOptions = 0;
  392. + if(pFileAttributes) *pFileAttributes = 0;
  393. + if(pShareAccess) *pShareAccess = 3;
  394. +
  395. printf("GetCreateParameters\r\n");
  396. }
  397. @@ -695,6 +749,10 @@ struct MyRequest : public IWDFIoRequest {
  398. _Out_opt_ LONGLONG *pullOffset,
  399. /* [annotation][unique][out] */
  400. _Out_opt_ ULONG *pulKey){
  401. + if(pSizeInBytes) *pSizeInBytes = 0;
  402. + if(pullOffset) *pullOffset = 0;
  403. + if(pulKey) *pulKey = 0;
  404. +
  405. printf("GetReadParameters\r\n");
  406. }
  407. @@ -706,6 +764,10 @@ struct MyRequest : public IWDFIoRequest {
  408. _Out_opt_ LONGLONG *pullOffset,
  409. /* [annotation][unique][out] */
  410. _Out_opt_ ULONG *pulKey){
  411. + if(pSizeInBytes) *pSizeInBytes = 0;
  412. + if(pullOffset) *pullOffset = 0;
  413. + if(pulKey) *pulKey = 0;
  414. +
  415. printf("GetWriteParameters\r\n");
  416. }
  417. @@ -717,6 +779,7 @@ struct MyRequest : public IWDFIoRequest {
  418. _Out_opt_ SIZE_T *pInBufferSize,
  419. /* [annotation][unique][out] */
  420. _Out_opt_ SIZE_T *pOutBufferSize){
  421. + printf("[REQ] GetDeviceIoControlParameters\n"); fflush(stdout);
  422. //printf("GetDeviceIoControlParameters %p %p %p\r\n", pControlCode, pInBufferSize, pOutBufferSize);
  423. *pControlCode = ctl;
  424. *pInBufferSize = inMem->size;
  425. @@ -729,6 +792,7 @@ struct MyRequest : public IWDFIoRequest {
  426. virtual void STDMETHODCALLTYPE GetOutputMemory(
  427. /* [annotation][out] */
  428. _Out_ IWDFMemory **ppWdfMemory){
  429. + printf("[REQ] GetOutputMemory\n"); fflush(stdout);
  430. *ppWdfMemory = outMem;
  431. //printf("GetOutputMemory\r\n");
  432. }
  433. @@ -736,6 +800,7 @@ struct MyRequest : public IWDFIoRequest {
  434. virtual void STDMETHODCALLTYPE GetInputMemory(
  435. /* [annotation][out] */
  436. _Out_ IWDFMemory **ppWdfMemory){
  437. + printf("[REQ] GetInputMemory\n"); fflush(stdout);
  438. *ppWdfMemory = inMem;
  439. // printf("GetInputMemory\r\n");
  440. }
  441. @@ -744,11 +809,13 @@ struct MyRequest : public IWDFIoRequest {
  442. virtual void STDMETHODCALLTYPE MarkCancelable(
  443. /* [annotation][in] */
  444. _In_ void *pCancelCallback){
  445. + printf("[REQ] MarkCancelable\n"); fflush(stdout);
  446. printf("MarkCancelable\r\n");
  447. //this->cancelCallback = pCancelCallback;
  448. }
  449. virtual HRESULT STDMETHODCALLTYPE UnmarkCancelable( void){
  450. + printf("[REQ] UnmarkCancelable\n"); fflush(stdout);
  451. printf("UnmarkCancelable\r\n");
  452. return 0;
  453. }
  454. @@ -763,6 +830,7 @@ struct MyRequest : public IWDFIoRequest {
  455. virtual HRESULT STDMETHODCALLTYPE ForwardToIoQueue(
  456. /* [annotation][in] */
  457. _In_ IWDFIoQueue *pDestination){
  458. + printf("[REQ] ForwardToIoQueue\n"); fflush(stdout);
  459. printf("ForwardToIoQueue\r\n");
  460. return 0;
  461. }
  462. @@ -775,6 +843,7 @@ struct MyRequest : public IWDFIoRequest {
  463. _In_ ULONG Flags,
  464. /* [annotation][in] */
  465. _In_ LONGLONG Timeout){
  466. + printf("[REQ] Send\n"); fflush(stdout);
  467. printf("Send\r\n");
  468. return 0;
  469. }
  470. @@ -783,6 +852,9 @@ struct MyRequest : public IWDFIoRequest {
  471. virtual void STDMETHODCALLTYPE GetFileObject(
  472. /* [annotation][out] */
  473. _Out_ void **ppFileObject){
  474. + printf("[REQ] GetFileObject\n"); fflush(stdout);
  475. + if(ppFileObject) *ppFileObject = NULL;
  476. +
  477. printf("GetFileObject\r\n");
  478. }
  479. @@ -801,6 +873,9 @@ struct MyRequest : public IWDFIoRequest {
  480. virtual void STDMETHODCALLTYPE GetIoQueue(
  481. /* [annotation][out] */
  482. _Out_ IWDFIoQueue **ppWdfIoQueue){
  483. + WUDF_TRACE("GetIoQueue -> %p\n", ppWdfIoQueue ? *ppWdfIoQueue : NULL);
  484. + if(ppWdfIoQueue) *ppWdfIoQueue = NULL;
  485. +
  486. printf("GetIoQueue\r\n");
  487. }
  488. @@ -826,12 +901,24 @@ struct MyRequest : public IWDFIoRequest {
  489. virtual void STDMETHODCALLTYPE GetCompletionParams(
  490. /* [annotation][out] */
  491. _Out_ IWDFRequestCompletionParams **ppCompletionParams){
  492. + printf("[REQ] GetCompletionParams\n"); fflush(stdout);
  493. + WUDF_TRACE("GetCompletionParams -> %p\n", ppCompletionParams ? *ppCompletionParams : NULL);
  494. + if(ppCompletionParams) *ppCompletionParams = NULL;
  495. +
  496. printf("GetCompletionParams\r\n");
  497. }
  498. };
  499. +static void *g_created_memory_buf = NULL;
  500. +static IWDFObject *g_wdf_object_stub = NULL;
  501. +static MyMem *g_dummy_file = NULL;
  502. +static MyMem *g_dummy_out_mem = NULL;
  503. +static MyMem *g_dummy_in_mem = NULL;
  504. +static IWDFIoRequest *g_request_stub = NULL;
  505. +static MyMem *g_file_stub = NULL;
  506. +
  507. struct MyPropertyStoreFactory : public IWDFPropertyStoreFactory {
  508. public:
  509. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) {
  510. @@ -875,6 +962,7 @@ public:
  511. };
  512. struct MyQueue : public IWDFIoQueue {
  513. + void *assigned_context = NULL;
  514. public:
  515. MyQueue(IUnknown *pCallbackInterface) {
  516. pCallbackInterface->AddRef();
  517. @@ -913,14 +1001,16 @@ struct MyQueue : public IWDFIoQueue {
  518. _In_opt_ __drv_aliasesMem void *pCleanupCallback,
  519. /* [annotation][unique][in] */
  520. _In_opt_ __drv_aliasesMem void *pContext) {
  521. - printf("AssignContext\r\n");
  522. + assigned_context = pContext;
  523. + printf("AssignContext(%p)\r\n", pContext);
  524. return 0;
  525. }
  526. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  527. /* [annotation][out] */
  528. _Out_ void **ppvContext) {
  529. - printf("RetrieveContext\r\n");
  530. + if(ppvContext) *ppvContext = assigned_context;
  531. + printf("RetrieveContext -> %p\r\n", assigned_context);
  532. return 0;
  533. }
  534. @@ -935,6 +1025,9 @@ struct MyQueue : public IWDFIoQueue {
  535. virtual void STDMETHODCALLTYPE GetDevice(
  536. /* [annotation][out] */
  537. _Out_ IWDFDevice **ppWdfDevice){
  538. + WUDF_TRACE("GetDevice -> %p\n", ppWdfDevice ? *ppWdfDevice : NULL);
  539. + if(ppWdfDevice) *ppWdfDevice = NULL;
  540. +
  541. printf("GetDevice\r\n");
  542. }
  543. @@ -954,6 +1047,9 @@ struct MyQueue : public IWDFIoQueue {
  544. _Out_ ULONG *pulNumOfRequestsInQueue,
  545. /* [annotation][out] */
  546. _Out_ ULONG *pulNumOfRequestsInDriver){
  547. + if(pulNumOfRequestsInQueue) *pulNumOfRequestsInQueue = 0;
  548. + if(pulNumOfRequestsInDriver) *pulNumOfRequestsInDriver = 0;
  549. +
  550. printf("GetState\r\n");
  551. return (WDF_IO_QUEUE_STATE)(WdfIoQueueAcceptRequests |
  552. WdfIoQueueDispatchRequests |
  553. @@ -966,7 +1062,8 @@ struct MyQueue : public IWDFIoQueue {
  554. /* [annotation][out] */
  555. _Out_ IWDFIoRequest **ppRequest){
  556. printf("RetrieveNextRequest\r\n");
  557. - return 0;
  558. + if(ppRequest) *ppRequest = NULL;
  559. +return 0;
  560. }
  561. @@ -976,7 +1073,8 @@ struct MyQueue : public IWDFIoQueue {
  562. /* [annotation][out] */
  563. _Out_ IWDFIoRequest **ppRequest){
  564. printf("RetrieveNextRequestByFileObject\r\n");
  565. - return 0;
  566. + if(ppRequest) *ppRequest = NULL;
  567. +return 0;
  568. }
  569. @@ -1029,6 +1127,7 @@ MyQueue *myQueue = NULL;
  570. struct MyDevice : public IWDFDevice3 {
  571. + void *assigned_context = NULL;
  572. public:
  573. MyDevice(IUnknown *pCallbackInterface) {
  574. pCallbackInterface->AddRef();
  575. @@ -1075,14 +1174,16 @@ struct MyDevice : public IWDFDevice3 {
  576. _In_opt_ __drv_aliasesMem void *pCleanupCallback,
  577. /* [annotation][unique][in] */
  578. _In_opt_ __drv_aliasesMem void *pContext) {
  579. - printf("AssignContext\r\n");
  580. + assigned_context = pContext;
  581. + printf("AssignContext(%p)\r\n", pContext);
  582. return 0;
  583. }
  584. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  585. /* [annotation][out] */
  586. _Out_ void **ppvContext) {
  587. - printf("RetrieveContext\r\n");
  588. + if(ppvContext) *ppvContext = assigned_context;
  589. + printf("RetrieveContext -> %p\r\n", assigned_context);
  590. return 0;
  591. }
  592. @@ -1113,6 +1214,9 @@ struct MyDevice : public IWDFDevice3 {
  593. virtual void STDMETHODCALLTYPE GetDriver(
  594. /* [annotation][out] */
  595. _Out_ IWDFDriver **ppWdfDriver){
  596. + WUDF_TRACE("GetDriver -> %p\n", ppWdfDriver ? *ppWdfDriver : NULL);
  597. + if(ppWdfDriver) *ppWdfDriver = NULL;
  598. +
  599. printf("GetDriver\r\n");
  600. }
  601. @@ -1130,6 +1234,9 @@ struct MyDevice : public IWDFDevice3 {
  602. virtual void STDMETHODCALLTYPE GetDefaultIoTarget(
  603. /* [annotation][out] */
  604. _Out_ IWDFIoTarget **ppWdfIoTarget){
  605. + WUDF_TRACE("GetDefaultIoTarget -> %p\n", ppWdfIoTarget ? *ppWdfIoTarget : NULL);
  606. + if(ppWdfIoTarget) *ppWdfIoTarget = NULL;
  607. +
  608. printf("GetDefaultIoTarget\r\n");
  609. }
  610. @@ -1140,6 +1247,10 @@ struct MyDevice : public IWDFDevice3 {
  611. /* [annotation][out] */
  612. _Out_ IWDFDriverCreatedFile **ppFile){
  613. printf("CreateWdfFile\r\n");
  614. + //Return a live object: the driver stores this as its file handle
  615. + //and dereferences it during I/O. NULL here crashes the capture path.
  616. + if(!g_dummy_file) g_dummy_file = new MyMem(malloc(16), 16);
  617. + if(ppFile) *ppFile = (IWDFDriverCreatedFile*) g_dummy_file;
  618. return 0;
  619. }
  620. @@ -1147,6 +1258,9 @@ struct MyDevice : public IWDFDevice3 {
  621. virtual void STDMETHODCALLTYPE GetDefaultIoQueue(
  622. /* [annotation][out] */
  623. _Out_ IWDFIoQueue **ppWdfIoQueue){
  624. + WUDF_TRACE("GetDefaultIoQueue -> %p\n", ppWdfIoQueue ? *ppWdfIoQueue : NULL);
  625. + if(ppWdfIoQueue) *ppWdfIoQueue = NULL;
  626. +
  627. printf("GetDefaultIoQueue\r\n");
  628. }
  629. @@ -1300,7 +1414,16 @@ struct MyDevice : public IWDFDevice3 {
  630. _In_opt_ IWDFObject *pParentObject,
  631. /* [annotation][out] */
  632. _Out_ IWDFIoRequest **ppRequest){
  633. + WUDF_TRACE("CreateRequest -> %p\n", ppRequest ? *ppRequest : NULL);
  634. printf("CreateRequest\r\n");
  635. + //Hand the driver a live request stub; a NULL here is dereferenced
  636. + //by the driver later in the capture path.
  637. + if(!g_request_stub) {
  638. + if(!g_dummy_out_mem) g_dummy_out_mem = new MyMem(malloc(256), 256);
  639. + if(!g_dummy_in_mem) g_dummy_in_mem = new MyMem(malloc(256), 256);
  640. + g_request_stub = (IWDFIoRequest*) new MyRequest(WdfRequestTypeOther, 0, g_dummy_out_mem, g_dummy_in_mem);
  641. + }
  642. + if(ppRequest) *ppRequest = g_request_stub;
  643. return 0;
  644. }
  645. @@ -1370,6 +1493,9 @@ struct MyDevice : public IWDFDevice3 {
  646. _In_opt_ IUnknown *pCallbackInterface,
  647. /* [annotation][out] */
  648. _Out_ void **ppRemoteInterface){
  649. + WUDF_TRACE("CreateRemoteInterface -> %p\n", ppRemoteInterface ? *ppRemoteInterface : NULL);
  650. + if(ppRemoteInterface) *ppRemoteInterface = NULL;
  651. +
  652. printf("CreateRemoteInterface\r\n");
  653. return 0;
  654. }
  655. @@ -1382,6 +1508,9 @@ struct MyDevice : public IWDFDevice3 {
  656. _In_opt_ IWDFObject *pParentObject,
  657. /* [annotation][out] */
  658. _Out_ void **ppRemoteTarget){
  659. + WUDF_TRACE("CreateRemoteTarget -> %p\n", ppRemoteTarget ? *ppRemoteTarget : NULL);
  660. + if(ppRemoteTarget) *ppRemoteTarget = NULL;
  661. +
  662. printf("CreateRemoteTarget\r\n");
  663. return 0;
  664. }
  665. @@ -1392,6 +1521,9 @@ struct MyDevice : public IWDFDevice3 {
  666. _Out_ WDF_DEVICE_IO_TYPE *ReadWritePreference,
  667. /* [annotation][out] */
  668. _Out_ WDF_DEVICE_IO_TYPE *IoControlPreference){
  669. + if(ReadWritePreference) *ReadWritePreference = (WDF_DEVICE_IO_TYPE) 0;
  670. + if(IoControlPreference) *IoControlPreference = (WDF_DEVICE_IO_TYPE) 0;
  671. +
  672. printf("GetDeviceStackIoTypePreference\r\n");
  673. }
  674. @@ -1424,6 +1556,8 @@ struct MyDevice : public IWDFDevice3 {
  675. _In_ MEMORY_CACHING_TYPE CacheType,
  676. /* [annotation][out] */
  677. _Out_ void **pPseudoBaseAddress){
  678. + if(pPseudoBaseAddress) *pPseudoBaseAddress = NULL;
  679. +
  680. printf("MapIoSpace\r\n");
  681. return 0;
  682. }
  683. @@ -1484,6 +1618,8 @@ struct MyDevice : public IWDFDevice3 {
  684. _In_ void* Configuration,
  685. /* [annotation][out] */
  686. _Out_ void **ppInterrupt){
  687. + if(ppInterrupt) *ppInterrupt = NULL;
  688. +
  689. printf("CreateInterrupt\r\n");
  690. return 0;
  691. }
  692. @@ -1496,6 +1632,8 @@ struct MyDevice : public IWDFDevice3 {
  693. _In_ IWDFObject *pParentObject,
  694. /* [annotation][out] */
  695. _Out_ void **ppWorkItem){
  696. + if(ppWorkItem) *ppWorkItem = NULL;
  697. +
  698. printf("CreateWorkItem\r\n");
  699. return 0;
  700. }
  701. @@ -1514,10 +1652,14 @@ struct MyDevice : public IWDFDevice3 {
  702. MyDevice* myDevice = NULL;
  703. +
  704. +
  705. struct MyDriver : public IWDFDriver {
  706. + void *assigned_context = NULL;
  707. public:
  708. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) {
  709. - printf("QueryInterface\r\n");
  710. + LPOLESTR _s; StringFromIID(riid, &_s);
  711. + std::wcout << L"[QI] " << _s << (ppvObject ? (void*)*ppvObject : (void*)0) << std::endl;
  712. return 0;
  713. }
  714. virtual ULONG STDMETHODCALLTYPE AddRef(void) {
  715. @@ -1540,14 +1682,16 @@ struct MyDriver : public IWDFDriver {
  716. _In_opt_ __drv_aliasesMem void *pCleanupCallback,
  717. /* [annotation][unique][in] */
  718. _In_opt_ __drv_aliasesMem void *pContext) {
  719. - printf("AssignContext\r\n");
  720. + assigned_context = pContext;
  721. + printf("AssignContext(%p)\r\n", pContext);
  722. return 0;
  723. }
  724. virtual HRESULT STDMETHODCALLTYPE RetrieveContext(
  725. /* [annotation][out] */
  726. _Out_ void **ppvContext) {
  727. - printf("RetrieveContext\r\n");
  728. + if(ppvContext) *ppvContext = assigned_context;
  729. + printf("RetrieveContext -> %p\r\n", assigned_context);
  730. return 0;
  731. }
  732. @@ -1585,6 +1729,12 @@ struct MyDriver : public IWDFDriver {
  733. /* [annotation][out] */
  734. _Out_ IWDFObject **ppWdfObject) {
  735. printf("CreateWdfObject\r\n");
  736. + //Return a minimal generic object. The driver only stores and later
  737. + //releases/context-manages these; a live stub keeps that safe.
  738. + if(ppWdfObject) {
  739. + if(!g_wdf_object_stub) g_wdf_object_stub = (IWDFObject*) new MyMem(malloc(16), 16);
  740. + *ppWdfObject = g_wdf_object_stub;
  741. + }
  742. return 0;
  743. }
  744. @@ -1599,7 +1749,8 @@ struct MyDriver : public IWDFDriver {
  745. _In_opt_ IWDFObject *pParentObject,
  746. /* [annotation][out] */
  747. _Out_ IWDFMemory **ppWdfMemory) {
  748. - printf("CreatePreallocatedWdfMemory\r\n");
  749. + printf("CreatePreallocatedWdfMemory(%p, %zu)\r\n", pBuff, BufferSize);
  750. + if(ppWdfMemory) *ppWdfMemory = new MyMem(pBuff, BufferSize);
  751. return 0;
  752. }
  753. @@ -1612,7 +1763,9 @@ struct MyDriver : public IWDFDriver {
  754. _In_opt_ IWDFObject *pParentObject,
  755. /* [annotation][out] */
  756. _Out_ IWDFMemory **ppWdfMemory) {
  757. - printf("CreateWdfMemory\r\n");
  758. + printf("CreateWdfMemory(%zu)\r\n", BufferSize);
  759. + g_created_memory_buf = malloc(BufferSize);
  760. + if(ppWdfMemory) *ppWdfMemory = new MyMem(g_created_memory_buf, BufferSize);
  761. return 0;
  762. }
  763. @@ -1650,25 +1803,49 @@ static NTSTATUS tudor_devctrl_wudf1(struct tudor_device *device, OVERLAPPED *ovl
  764. printf("[WUDF1-DEVCTRL] -> code 0x%x (size 0x%lx)\r\n", code, in_size);
  765. }
  766. - // For UMDF1, we need to handle this through the queue callback mechanism
  767. - // The actual I/O will be handled when the driver calls our queue callbacks
  768. -
  769. - // Store the request info for when the callback is invoked
  770. - // This is a simplified approach - you might need a more sophisticated request tracking system
  771. -
  772. if (myQueue) {
  773. - //MyMem in(ibuf, sizeof(ibuf)), out(obuf, sizeof(obuf));
  774. - MyMem in(in_buf, in_size), out(out_buf, out_size);
  775. - MyRequest req(WdfRequestTypeOther, 0x442004, &out, &in);
  776. -
  777. - printf("about to ioctl: 0x%x\r\n", code);
  778. - myQueue->ioctl->OnDeviceIoControl(myQueue, &req, code, 0, 0);
  779. - while(!req.complete)
  780. - usleep(20000);
  781. + //HEAP-allocate the memory/request objects: the driver retains pointers
  782. + //to them past this call (async completion, pending I/O). Stack objects
  783. + //were invalidated when this frame returned, leaving the driver with
  784. + //dangling pointers - the root cause of the capture-path null crash.
  785. + MyMem *in = new MyMem(in_buf, in_size);
  786. + MyMem *out = new MyMem(out_buf, out_size);
  787. + MyRequest *req = new MyRequest(WdfRequestTypeOther, code, out, in);
  788. +
  789. + printf("about to ioctl: 0x%x (queue=%p cb=%p)\r\n", code, (void*) myQueue, (void*) myQueue->ioctl);
  790. + fflush(stdout);
  791. + myQueue->ioctl->OnDeviceIoControl(myQueue, req, code, 0, 0);
  792. + printf("OnDeviceIoControl returned for 0x%x\r\n", code);
  793. + fflush(stdout);
  794. + while(!req->complete)
  795. + usleep(5000);
  796. + printf("ioctl 0x%x completed: status=0x%lx info=%lld\r\n",
  797. + code, (unsigned long) req->completionStatus, (long long) req->informationSize);
  798. + fflush(stdout);
  799. +
  800. + //The caller (DeviceIoControl) hands us an OVERLAPPED it will later
  801. + //wait on via GetOverlappedResult. Complete it with the driver's real
  802. + //status, otherwise the wait never ends.
  803. + size_t num_transfered = (size_t) req->informationSize;
  804. + if(num_transfered > out_size) num_transfered = out_size;
  805. +
  806. + HRESULT completion = req->completionStatus;
  807. + if(completion == 0) {
  808. + winio_complete_overlapped(ovlp, STATUS_SUCCESS, num_transfered);
  809. + return STATUS_SUCCESS;
  810. + }
  811. + if((completion & 0xffff0000) == 0x80070000) {
  812. + NTSTATUS status = (NTSTATUS) (completion & 0xffff);
  813. + winio_complete_overlapped(ovlp, status, 0);
  814. + return status;
  815. + }
  816. + winio_complete_overlapped(ovlp, (NTSTATUS) 0xC0000001, 0);
  817. + return (NTSTATUS) 0xC0000001; //STATUS_UNSUCCESSFUL
  818. }
  819. -
  820. - // For now, return pending - the actual completion will happen in the callback
  821. - return STATUS_PENDING;
  822. +
  823. + //No queue: treat as completed successfully
  824. + winio_complete_overlapped(ovlp, STATUS_SUCCESS, 0);
  825. + return STATUS_SUCCESS;
  826. }
  827. static NTSTATUS tudor_cancel_wudf1(struct tudor_device *device, OVERLAPPED *ovlp, struct winwdf_request *req) {
  828. @@ -1796,7 +1973,9 @@ bool tudor_init() {
  829. print_vtable(myDevice->pnphwcb, 5);
  830. rc = myDevice->pnphwcb->OnPrepareHardware(myDevice);
  831. - usleep(50000000);
  832. + //Settle time for the device's pairing/firmware handshake. The device
  833. + //re-enumerates during this window; 2s has proven sufficient.
  834. + usleep(2000000);
  835. printf("OnPrepareHardware rc = %lx\r\n", rc);
  836. fflush(stdout);
  837. //
  838. @@ -1804,11 +1983,11 @@ bool tudor_init() {
  839. abort();
  840. }
  841. //
  842. - usleep(1000000);
  843. + usleep(200000);
  844. printf("about to enter D0 state\r\n");
  845. rc = myDevice->pnpcb->OnD0Entry(myDevice, WdfPowerDeviceInvalid);
  846. printf("OnD0Entry rc = %lx\r\n", rc);
  847. - usleep(5000000);
  848. + usleep(300000);
  849. fflush(stdout);
  850. @@ -1816,15 +1995,88 @@ bool tudor_init() {
  851. winmodule_set_cur(&tudor_adapter_dll->module);
  852. HRESULT hres;
  853. - if((hres = ((api_WbioQuerySensorInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQuerySensorInterface"))(&tudor_sensor_adapter)) != 0) {
  854. + //EXPERIMENT: skip the engine interface entirely. Its query/calls write
  855. + //runtime state that overlaps the sensor interface's static storage in
  856. + //the relinked adapter image, corrupting the sensor table.
  857. + if(getenv("TUDOR_NO_ENGINE") == NULL) {
  858. + if((hres = ((api_WbioQueryEngineInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQueryEngineInterface"))(&tudor_engine_adapter)) != 0) {
  859. + log_error("Error querying engine interface: 0x%x!", hres);
  860. + return false;
  861. + }
  862. + } else {
  863. + printf("!! TUDOR_NO_ENGINE: engine interface disabled\n");
  864. + tudor_engine_adapter = (WINBIO_ENGINE_INTERFACE*) calloc(1, sizeof(WINBIO_ENGINE_INTERFACE));
  865. + //Dummy implementations: succeed and don't touch the pipeline
  866. + tudor_engine_adapter->Attach = (IBIO_ENGINE_ATTACH_FN*) dummy_engine_attach;
  867. + tudor_engine_adapter->PipelineInit = (IBIO_ENGINE_PIPELINE_INIT_FN*) dummy_engine_pipeline_init;
  868. + tudor_engine_adapter->PipelineCleanup = (IBIO_ENGINE_PIPELINE_CLEANUP_FN*) dummy_engine_pipeline_cleanup;
  869. + tudor_engine_adapter->Activate = (IBIO_ENGINE_ACTIVATE_FN*) dummy_engine_activate;
  870. + tudor_engine_adapter->Deactivate = (IBIO_ENGINE_DEACTIVATE_FN*) dummy_engine_deactivate;
  871. + }
  872. + if((hres = ((api_WbioQuerySensorInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQuerySensorInterface"))((WINBIO_SENSOR_INTERFACE**) &tudor_sensor_adapter)) != 0) {
  873. log_error("Error querying sensor interface: 0x%x!", hres);
  874. return false;
  875. }
  876. - if((hres = ((api_WbioQueryEngineInterface) find_dll_export(&tudor_adapter_dll->image, "WbioQueryEngineInterface"))(&tudor_engine_adapter)) != 0) {
  877. - log_error("Error querying engine interface: 0x%x!", hres);
  878. - return false;
  879. +
  880. + //Snapshot the sensor interface table, then restore every function slot
  881. + //from the pristine static image. The relinked adapter's runtime state
  882. + //overlaps the table's storage in .data and clobbers slots; the file RVAs
  883. + //are stable, so normalize all 15 slots in one step.
  884. + {
  885. + WINBIO_SENSOR_INTERFACE_V1 *snapshot = (WINBIO_SENSOR_INTERFACE_V1*) malloc(sizeof(WINBIO_SENSOR_INTERFACE_V1));
  886. + memcpy(snapshot, tudor_sensor_adapter, sizeof(WINBIO_SENSOR_INTERFACE_V1));
  887. + tudor_sensor_adapter = snapshot;
  888. +
  889. + uintptr_t mod_base = (uintptr_t) tudor_adapter_dll->image.base_addr;
  890. + static const uint32_t sensor_slot_rvas[15] = {
  891. + 0x005b50, 0x005d50, 0x005ee0, 0x005ff0, 0x006250,
  892. + 0x006460, 0x0065d0, 0x006660, 0x0066f0, 0x006bf0,
  893. + 0x006ec0, 0x006f50, 0x0070b0, 0x0072f0, 0x0075b0,
  894. + };
  895. + void **slots = (void**) tudor_sensor_adapter;
  896. + for(int i = 0; i < 15; i++) {
  897. + slots[4 + i] = (void*) (mod_base + sensor_slot_rvas[i]);
  898. + }
  899. +
  900. + //Alias the Windows 10 names onto the legacy entry points. This driver
  901. + //predates the pipeline API; Reset doubles as init/activate and Cancel
  902. + //as cleanup.
  903. + tudor_sensor_adapter->PipelineInit = (IBIO_SENSOR_PIPELINE_INIT_FN*) tudor_sensor_adapter->Reset;
  904. + tudor_sensor_adapter->PipelineCleanup = (IBIO_SENSOR_PIPELINE_CLEANUP_FN*) tudor_sensor_adapter->Cancel;
  905. + tudor_sensor_adapter->Activate = (IBIO_SENSOR_ACTIVATE_FN*) tudor_sensor_adapter->Reset;
  906. + tudor_sensor_adapter->Deactivate = (IBIO_SENSOR_DEACTIVATE_FN*) tudor_sensor_adapter->Cancel;
  907. }
  908. + //Debug: dump the queried interface tables so we can spot layout mismatches
  909. + printf("sensor adapter: version=%u type=%u size=%zu ptr=%p\n",
  910. + tudor_sensor_adapter->Version, tudor_sensor_adapter->Type, (size_t) tudor_sensor_adapter->Size, (void*) tudor_sensor_adapter);
  911. + printf(" Attach=%p Detach=%p ClearContext=%p QueryStatus=%p Reset=%p\n",
  912. + (void*) tudor_sensor_adapter->Attach, (void*) tudor_sensor_adapter->Detach,
  913. + (void*) tudor_sensor_adapter->ClearContext, (void*) tudor_sensor_adapter->QueryStatus,
  914. + (void*) tudor_sensor_adapter->Reset);
  915. + printf(" PipelineInit=%p PipelineCleanup=%p Activate=%p Deactivate=%p\n",
  916. + (void*) tudor_sensor_adapter->PipelineInit, (void*) tudor_sensor_adapter->PipelineCleanup,
  917. + (void*) tudor_sensor_adapter->Activate, (void*) tudor_sensor_adapter->Deactivate);
  918. + printf("engine adapter: version=%u type=%u size=%zu ptr=%p\n",
  919. + tudor_engine_adapter->Version, tudor_engine_adapter->Type, (size_t) tudor_engine_adapter->Size, (void*) tudor_engine_adapter);
  920. + //Even if the struct layout differs, print raw words at the expected offsets
  921. + printf("RAW sensor table:");
  922. + for(int i = 0; i < 12; i++) printf(" %016zx", ((size_t*) tudor_sensor_adapter)[i + 4]);
  923. + printf("\n");
  924. + printf("ADDRSensor=%p ADDREngine=%p\n", (void*) tudor_sensor_adapter, (void*) tudor_engine_adapter);
  925. + printf("ENGINE table:");
  926. + for(int i = 0; i < 16; i++) printf(" %016zx", ((size_t*) tudor_engine_adapter)[i + 4]);
  927. + printf("\n");
  928. + printf("ENGINE+0x60=%p ENGINE+0x100=%p\n",
  929. + (void*) *(void**) ((char*) tudor_engine_adapter + 0x60),
  930. + (void*) *(void**) ((char*) tudor_engine_adapter + 0x100));
  931. + printf(" Attach=%p Detach=%p ClearContext=%p\n",
  932. + (void*) tudor_engine_adapter->Attach, (void*) tudor_engine_adapter->Detach,
  933. + (void*) tudor_engine_adapter->ClearContext);
  934. + printf(" PipelineInit=%p PipelineCleanup=%p Activate=%p Deactivate=%p\n",
  935. + (void*) tudor_engine_adapter->PipelineInit, (void*) tudor_engine_adapter->PipelineCleanup,
  936. + (void*) tudor_engine_adapter->Activate, (void*) tudor_engine_adapter->Deactivate);
  937. +
  938. printf("tudor_init finish!\n");
  939. return true;
  940. @@ -1917,8 +2169,8 @@ bool tudor_open(struct tudor_device *device, libusb_device_handle *usb_dev, stru
  941. if(!device->pipeline) { perror("Error allocating WINBIO pipeline"); abort(); }
  942. *device->pipeline = (WINBIO_PIPELINE) {0};
  943. device->pipeline->EngineInterface = tudor_engine_adapter;
  944. - device->pipeline->SensorInterface = tudor_sensor_adapter;
  945. - // device->pipeline->StorageInterface = tudor_storage_adapter;
  946. + device->pipeline->SensorInterface = (WINBIO_SENSOR_INTERFACE*) tudor_sensor_adapter;
  947. + device->pipeline->StorageInterface = tudor_storage_adapter;
  948. // device->pipeline->SensorHandle = device->winbio_file = winio_create_file(device, true, NULL, NULL, (winio_devctrl_fnc*) tudor_devctrl, (winio_cancel_fnc*) tudor_cancel, (winio_cleanup_fnc*) tudor_cleanup, NULL);
  949. device->pipeline->SensorHandle = device->winbio_file = winio_create_file(
  950. device,
  951. @@ -1936,32 +2188,60 @@ bool tudor_open(struct tudor_device *device, libusb_device_handle *usb_dev, stru
  952. device->pipeline->StorageContext = device;
  953. log_debug("Attaching interfaces to pipeline...");
  954. - WINBIO_CALL_PIPELINE(tudor_sensor_adapter->Attach, device->pipeline);
  955. - WINBIO_CALL_PIPELINE(tudor_engine_adapter->Attach, device->pipeline);
  956. - // WINBIO_CALL_PIPELINE(tudor_storage_adapter->Attach, device->pipeline);
  957. + WINBIO_CALL_PIPELINE_RC("sensor.Attach", tudor_sensor_adapter->Attach, device->pipeline);
  958. + if(getenv("TUDOR_NO_ENGINE") == NULL) {
  959. + WINBIO_CALL_PIPELINE_RC("engine.Attach", tudor_engine_adapter->Attach, device->pipeline);
  960. + }
  961. + WINBIO_CALL_PIPELINE_RC("storage.Attach", tudor_storage_adapter->Attach, device->pipeline);
  962. +
  963. + printf("CTX: sensor=%p engine=%p storage=%p\n",
  964. + device->pipeline->SensorContext, device->pipeline->EngineContext, device->pipeline->StorageContext);
  965. log_debug("Initializing pipeline interfaces...");
  966. - WINBIO_CALL_PIPELINE(tudor_sensor_adapter->PipelineInit, device->pipeline);
  967. - WINBIO_CALL_PIPELINE(tudor_engine_adapter->PipelineInit, device->pipeline);
  968. - // WINBIO_CALL_PIPELINE(tudor_storage_adapter->PipelineInit, device->pipeline);
  969. + //NOTE: this driver (Synaptics WBDI 5.5.2731.1050) predates the Windows 10
  970. + //sensor pipeline API: its interface table has no PipelineInit or Activate
  971. + //entries (see WINBIO_SENSOR_INTERFACE_V1). Attach plus Reset is the whole
  972. + //initialization sequence for it.
  973. + if(getenv("TUDOR_PROBE_SLOT")) {
  974. + int slot = atoi(getenv("TUDOR_PROBE_SLOT"));
  975. + void **tbl = (void**) tudor_sensor_adapter;
  976. + fflush(stdout);
  977. + printf("PROBE SLOT %d (+%#04x): %p ...\n", slot, 0x20 + slot*8, tbl[4 + slot]);
  978. + fflush(stdout);
  979. + HRESULT r = ((HRESULT (*)(WINBIO_PIPELINE*)) tbl[4 + slot])(device->pipeline);
  980. + printf("PROBE SLOT %d -> 0x%x\n", slot, r);
  981. + fflush(stdout);
  982. + }
  983. //Reset the sensor
  984. log_debug("Resetting sensor...");
  985. - WINBIO_CALL_PIPELINE(tudor_sensor_adapter->Reset, device->pipeline);
  986. -
  987. - //Activate the pipeline
  988. - log_debug("Activating pipeline...");
  989. - WINBIO_CALL_PIPELINE(tudor_sensor_adapter->Activate, device->pipeline);
  990. - WINBIO_CALL_PIPELINE(tudor_engine_adapter->Activate, device->pipeline);
  991. - // WINBIO_CALL_PIPELINE(tudor_storage_adapter->Activate, device->pipeline);
  992. + //The driver's reset may need time to settle after firmware init
  993. + //(returns ERROR_NO_MORE_ITEMS while busy). Retry with backoff.
  994. + {
  995. + hres = 0x80070103 /* ERROR_NO_MORE_ITEMS */;
  996. + for(int attempt = 0; attempt < 20; attempt++) {
  997. + hres = tudor_sensor_adapter->Reset(device->pipeline);
  998. + printf("[PIPE] sensor.Reset attempt %d -> 0x%x\n", attempt, hres);
  999. + if(hres == ERROR_SUCCESS) break;
  1000. + usleep(500000);
  1001. + }
  1002. + if(hres != ERROR_SUCCESS) { log_error("Reset did not succeed: 0x%x", hres); return false; }
  1003. + }
  1004. //Check the sensor status
  1005. log_debug("Checking sensor status...");
  1006. ULONG sensor_status = WINBIO_SENSOR_FAILURE;
  1007. - WINBIO_CALL_PIPELINE(tudor_sensor_adapter->QueryStatus, device->pipeline, &sensor_status)
  1008. + WINBIO_CALL_PIPELINE_RC("sensor.QueryStatus", tudor_sensor_adapter->QueryStatus, device->pipeline, &sensor_status);
  1009. + printf("[PIPE] sensor status = 0x%x\n", sensor_status);
  1010. if(sensor_status != WINBIO_SENSOR_READY) {
  1011. - log_error("Sensor didn't return ready status! [status 0x%x]", status);
  1012. - return false;
  1013. + //NOT_CALIBRATED (5) is expected until the sensor performs its first
  1014. + //capture cycle; only a hard failure should block.
  1015. + if(sensor_status == WINBIO_SENSOR_NOT_CALIBRATED) {
  1016. + log_warn("Sensor not calibrated yet, continuing [status 0x%x]", sensor_status);
  1017. + } else {
  1018. + log_error("Sensor didn't return ready status! [status 0x%x]", sensor_status);
  1019. + return false;
  1020. + }
  1021. }
  1022. return true;
  1023. diff --git a/libtudor/src/tudor/internal.h b/libtudor/src/tudor/internal.h
  1024. index c3f0ac9..e5d58e3 100644
  1025. --- a/libtudor/src/tudor/internal.h
  1026. +++ b/libtudor/src/tudor/internal.h
  1027. @@ -58,10 +58,15 @@ struct windrv_dll {
  1028. extern struct windrv_dll tudor_windrv_dlls[];
  1029. #define WINBIO_CALL_PIPELINE(fnc, ...) if((hres = fnc(__VA_ARGS__)) != ERROR_SUCCESS) { log_error("Error in WINBIO pipeline function '%s': 0x%x!", #fnc, hres); return false; }
  1030. +#define WINBIO_CALL_PIPELINE_RC(name, fnc, ...) do { \
  1031. + hres = (fnc)(__VA_ARGS__); \
  1032. + printf("[PIPE] %s -> 0x%x\n", name, hres); \
  1033. + if(hres != ERROR_SUCCESS) { log_error("Error in WINBIO pipeline function '%s': 0x%x!", name, hres); return false; } \
  1034. +} while(0)
  1035. extern struct windrv_dll *tudor_adapter_dll, *tudor_driver_dll;
  1036. extern struct winwdf_driver *tudor_wdf_driver;
  1037. -extern WINBIO_SENSOR_INTERFACE *tudor_sensor_adapter;
  1038. +extern WINBIO_SENSOR_INTERFACE_V1 *tudor_sensor_adapter;
  1039. extern WINBIO_ENGINE_INTERFACE *tudor_engine_adapter;
  1040. extern WINBIO_STORAGE_INTERFACE *tudor_storage_adapter;
  1041. diff --git a/libtudor/src/tudor/winbio.h b/libtudor/src/tudor/winbio.h
  1042. index 0086f3c..06f5c74 100644
  1043. --- a/libtudor/src/tudor/winbio.h
  1044. +++ b/libtudor/src/tudor/winbio.h
  1045. @@ -428,6 +428,44 @@ typedef struct _WINBIO_SENSOR_INTERFACE {
  1046. IBIO_SENSOR_QUERY_PRIVATE_SENSOR_TYPE_FN *QueryPrivateSensorType;
  1047. } WINBIO_SENSOR_INTERFACE;
  1048. +//Legacy sensor interface layout as used by the Synaptics WBDI sensor adapter
  1049. +//5.5.2731.1050. Empirically verified against the adapter binary (function
  1050. +//trace strings + probe calls): this is a pre-Windows-10 adapter, so it has
  1051. +//no native PipelineInit/PipelineCleanup/Activate/Deactivate entries. The
  1052. +//older code paths spell those operations differently, so the modern names
  1053. +//are aliased onto the closest legacy function (Reset for "init/activate",
  1054. +//Cancel for "cleanup"), which is what the Windows 7 pipeline did.
  1055. +typedef struct _WINBIO_SENSOR_INTERFACE_V1 {
  1056. + WINBIO_ADAPTER_INTERFACE_VERSION Version;
  1057. + ULONG Type;
  1058. + SIZE_T Size;
  1059. + GUID AdapterId;
  1060. + IBIO_SENSOR_ATTACH_FN *Attach;
  1061. + IBIO_SENSOR_DETACH_FN *Detach;
  1062. + IBIO_SENSOR_CLEAR_CONTEXT_FN *ClearContext;
  1063. + IBIO_SENSOR_QUERY_STATUS_FN *QueryStatus;
  1064. + IBIO_SENSOR_RESET_FN *Reset;
  1065. + IBIO_SENSOR_SET_MODE_FN *SetMode;
  1066. + IBIO_SENSOR_SET_INDICATOR_STATUS_FN *SetIndicatorStatus;
  1067. + IBIO_SENSOR_GET_INDICATOR_STATUS_FN *GetIndicatorStatus;
  1068. + IBIO_SENSOR_START_CAPTURE_FN *StartCapture;
  1069. + IBIO_SENSOR_FINISH_CAPTURE_FN *FinishCapture;
  1070. + IBIO_SENSOR_EXPORT_SENSOR_DATA_FN *ExportSensorData;
  1071. + IBIO_SENSOR_CANCEL_FN *Cancel;
  1072. + IBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN *PushDataToEngine;
  1073. + IBIO_SENSOR_CONTROL_UNIT_FN *ControlUnit;
  1074. + IBIO_SENSOR_CONTROL_UNIT_PRIVILEGED_FN *ResetOwnership;
  1075. +
  1076. + //Aliases for legacy call sites that use the Windows 10 names. These are
  1077. + //not separate table slots: PipelineInit/PipelineCleanup/Activate/
  1078. + //Deactivate map onto the legacy Reset/Cancel entry points, which is the
  1079. + //closest equivalent behaviour for this driver generation.
  1080. + IBIO_SENSOR_PIPELINE_INIT_FN *PipelineInit;
  1081. + IBIO_SENSOR_PIPELINE_CLEANUP_FN *PipelineCleanup;
  1082. + IBIO_SENSOR_ACTIVATE_FN *Activate;
  1083. + IBIO_SENSOR_DEACTIVATE_FN *Deactivate;
  1084. +} WINBIO_SENSOR_INTERFACE_V1;
  1085. +
  1086. typedef HRESULT __winfnc IBIO_ENGINE_ATTACH_FN(WINBIO_PIPELINE *Pipeline);
  1087. typedef HRESULT __winfnc IBIO_ENGINE_DETACH_FN(WINBIO_PIPELINE *Pipeline);
  1088. typedef HRESULT __winfnc IBIO_ENGINE_CLEAR_CONTEXT_FN(WINBIO_PIPELINE *Pipeline);
  1089. diff --git a/libtudor/src/winapi/error.c b/libtudor/src/winapi/error.c
  1090. index a4318c1..1dcd77e 100644
  1091. --- a/libtudor/src/winapi/error.c
  1092. +++ b/libtudor/src/winapi/error.c
  1093. @@ -3,6 +3,10 @@
  1094. #include "internal.h"
  1095. static __thread DWORD last_error;
  1096. +static __thread int get_last_error_trace_count;
  1097. +
  1098. +//Set by the CLI when tracing is wanted; limits noise
  1099. +bool tudor_trace_errors = false;
  1100. void winerr_clear() {
  1101. WIN_CLOBBER_NONVOL_REGS
  1102. @@ -31,7 +35,10 @@ int winerr_from_errno() {
  1103. __winfnc DWORD GetLastError() {
  1104. WIN_CLOBBER_NONVOL_REGS
  1105. - // printf("Get last_error = %d\n", last_error);
  1106. + if(tudor_trace_errors && get_last_error_trace_count < 100) {
  1107. + printf("[DBG] GetLastError -> 0x%x\n", last_error);
  1108. + get_last_error_trace_count++;
  1109. + }
  1110. return last_error;
  1111. }
  1112. WINAPI(GetLastError)
  1113. diff --git a/libtudor/src/winapi/io.c b/libtudor/src/winapi/io.c
  1114. index e58fcfa..7050a05 100644
  1115. --- a/libtudor/src/winapi/io.c
  1116. +++ b/libtudor/src/winapi/io.c
  1117. @@ -266,11 +266,19 @@ __winfnc BOOL DeviceIoControl(HANDLE handle, DWORD code, const void *in_buf, DWO
  1118. //Start the operation
  1119. NTSTATUS status = file->devctrl_fnc(file->ctx, ovlp, code, in_buf, in_size, out_buf, out_size, op_ctx);
  1120. winerr_set_code(status);
  1121. - if(status != STATUS_SUCCESS) return FALSE;
  1122. + if(status != STATUS_SUCCESS && status != STATUS_PENDING) return FALSE;
  1123. if(file->is_async) {
  1124. - winerr_set_code(ERROR_IO_PENDING);
  1125. - return FALSE;
  1126. + //Windows semantics: an overlapped request tells the caller to wait
  1127. + //via GetOverlappedResult with ERROR_IO_PENDING (0x3e5), not the raw
  1128. + //NTSTATUS value. The overlapped must be completed by the backend.
  1129. + if(ovlp->Internal == STATUS_PENDING) {
  1130. + winerr_set_code(ERROR_IO_PENDING);
  1131. + return FALSE;
  1132. + }
  1133. + *out_ret = (DWORD) ovlp->InternalHigh;
  1134. + winerr_clear();
  1135. + return TRUE;
  1136. }
  1137. //Wait for the operation to complete
  1138. diff --git a/libtudor/src/winapi/pipe.c b/libtudor/src/winapi/pipe.c
  1139. index 1a582e0..0ab6da5 100644
  1140. --- a/libtudor/src/winapi/pipe.c
  1141. +++ b/libtudor/src/winapi/pipe.c
  1142. @@ -108,7 +108,8 @@ __winfnc HRESULT SHGetFolderPathA(
  1143. TRACE();
  1144. int folder = CSIDL_FOLDER_MASK & nFolder;
  1145. printf("SHGetFolderPathA: %d\n", folder);
  1146. - const char* path = "/home/rstar000/synaptics";
  1147. + const char *folder_env = getenv("TUDOR_DATA_DIR");
  1148. + const char* path = (folder_env && folder_env[0]) ? folder_env : "/tmp/tudor-synaptics";
  1149. if (pszPath == NULL) {
  1150. pszPath = malloc(sizeof(path + 1));
  1151. }
  1152. diff --git a/libtudor/src/winapi/winusb.c b/libtudor/src/winapi/winusb.c
  1153. index bc26227..44189f8 100644
  1154. --- a/libtudor/src/winapi/winusb.c
  1155. +++ b/libtudor/src/winapi/winusb.c
  1156. @@ -45,6 +45,14 @@ struct driver_info {
  1157. struct libusb_device_descriptor descr;
  1158. libusb_device_handle * dev;
  1159. + // Device location on the USB bus tree, used to re-acquire the sensor
  1160. + // after it re-enumerates (the driver forces device reconnects during
  1161. + // its trust/calibration cycles).
  1162. + uint8_t bus_number;
  1163. + uint8_t port_numbers[8];
  1164. + int port_numbers_len;
  1165. + pthread_mutex_t reopen_lock;
  1166. +
  1167. DWORD timeouts[0x100];
  1168. volatile char abort[0x100];
  1169. @@ -83,7 +91,12 @@ bool claim_device(struct driver_info *info)
  1170. err(libusb_set_configuration(info->dev, 1));
  1171. err(libusb_claim_interface(info->dev, 0));
  1172. - printf("libusb initialized, device = %p\n", info->dev);
  1173. + //Remember the device's position on the bus tree
  1174. + info->bus_number = libusb_get_bus_number(dev_list[i]);
  1175. + info->port_numbers_len = libusb_get_port_numbers(dev_list[i], info->port_numbers, sizeof(info->port_numbers));
  1176. + if(info->port_numbers_len < 0) info->port_numbers_len = 0;
  1177. +
  1178. + printf("libusb initialized, device = %p [bus %d, port path %d]\n", info->dev, info->bus_number, info->port_numbers_len ? info->port_numbers[0] : -1);
  1179. return TRUE;
  1180. }
  1181. }
  1182. @@ -93,6 +106,95 @@ bool claim_device(struct driver_info *info)
  1183. return FALSE;
  1184. }
  1185. +static bool device_matches_location(struct driver_info *info, libusb_device *dev)
  1186. +{
  1187. + if(libusb_get_bus_number(dev) != info->bus_number) return false;
  1188. +
  1189. + uint8_t ports[8];
  1190. + int len = libusb_get_port_numbers(dev, ports, sizeof(ports));
  1191. + if(len != info->port_numbers_len) return false;
  1192. +
  1193. + return memcmp(ports, info->port_numbers, len) == 0;
  1194. +}
  1195. +
  1196. +// Re-acquires the sensor after it has re-enumerated on the bus. The driver
  1197. +// intentionally forces the device to disconnect/reconnect during its
  1198. +// initialization cycles, which invalidates the old handle. Wait for the
  1199. +// device to come back at the same bus location and open it again.
  1200. +static bool reopen_device_once(struct driver_info *info)
  1201. +{
  1202. + int rc;
  1203. + pthread_mutex_lock(&info->reopen_lock);
  1204. +
  1205. + fprintf(stderr, "** device disconnected, waiting for it to reappear...\n");
  1206. +
  1207. + //The old handle is dead once the device has re-enumerated
  1208. + if(info->dev) {
  1209. + libusb_close(info->dev);
  1210. + info->dev = NULL;
  1211. + }
  1212. +
  1213. + //Poll for the device to come back (up to ~20 seconds)
  1214. + for(int attempt = 0; attempt < 100; attempt++) {
  1215. + libusb_device ** dev_list;
  1216. + int dev_cnt = libusb_get_device_list(info->ctx, &dev_list);
  1217. + if(dev_cnt < 0) {
  1218. + pthread_mutex_unlock(&info->reopen_lock);
  1219. + return false;
  1220. + }
  1221. +
  1222. + for(int i = 0; i < dev_cnt; i++) {
  1223. + libusb_device *dev = dev_list[i];
  1224. +
  1225. + if(!device_matches_location(info, dev)) continue;
  1226. +
  1227. + struct libusb_device_descriptor descriptor;
  1228. + if(libusb_get_device_descriptor(dev, &descriptor) != 0) continue;
  1229. + if(descriptor.idVendor != info->supported_devices[0].vend_id ||
  1230. + descriptor.idProduct != info->supported_devices[0].prod_id) continue;
  1231. +
  1232. + rc = libusb_open(dev, &info->dev);
  1233. + if(rc == 0) {
  1234. + rc = libusb_set_configuration(info->dev, 1);
  1235. + if(rc != 0 && rc != LIBUSB_ERROR_BUSY) {
  1236. + libusb_close(info->dev);
  1237. + info->dev = NULL;
  1238. + continue;
  1239. + }
  1240. + rc = libusb_claim_interface(info->dev, 0);
  1241. + if(rc != 0) {
  1242. + libusb_close(info->dev);
  1243. + info->dev = NULL;
  1244. + continue;
  1245. + }
  1246. +
  1247. + libusb_free_device_list(dev_list, 1);
  1248. + fprintf(stderr, "** device re-acquired [bus %d]\n", info->bus_number);
  1249. + pthread_mutex_unlock(&info->reopen_lock);
  1250. + return true;
  1251. + }
  1252. + }
  1253. +
  1254. + libusb_free_device_list(dev_list, 1);
  1255. +
  1256. + struct timeval tv = { .tv_sec = 0, .tv_usec = 200000 };
  1257. + libusb_handle_events_timeout(info->ctx, &tv);
  1258. + usleep(200000);
  1259. + }
  1260. +
  1261. + fprintf(stderr, "** device did not come back\n");
  1262. + pthread_mutex_unlock(&info->reopen_lock);
  1263. + return false;
  1264. +}
  1265. +
  1266. +//Handle a transfer error: if the device has vanished, re-acquire it and
  1267. +//report whether the caller should retry the transfer.
  1268. +static bool handle_usb_error(struct driver_info *info, int rc)
  1269. +{
  1270. + if(rc != LIBUSB_ERROR_NO_DEVICE && rc != LIBUSB_ERROR_IO) return false;
  1271. + return reopen_device_once(info);
  1272. +}
  1273. +
  1274. __winfnc BOOL
  1275. WinUsb_Initialize (HANDLE DeviceHandle, void** InterfaceHandle)
  1276. @@ -134,6 +236,7 @@ WinUsb_Initialize (HANDLE DeviceHandle, void** InterfaceHandle)
  1277. info->playback = 0;
  1278. info->dev = NULL;
  1279. + pthread_mutex_init(&info->reopen_lock, NULL);
  1280. if(info->playback) {
  1281. info->script = fopen("usb_script.txt", "rt");
  1282. @@ -224,6 +327,15 @@ __winfnc BOOL WinUsb_GetDescriptor(
  1283. LIBUSB_REQUEST_GET_DESCRIPTOR, dti,
  1284. LanguageID, Buffer, (uint16_t) BufferLength, 1000);
  1285. + //Wait for the device to come back if it re-enumerated, then retry
  1286. + if(rc == LIBUSB_ERROR_NO_DEVICE || rc == LIBUSB_ERROR_IO) {
  1287. + if(handle_usb_error(info, rc)) {
  1288. + rc = libusb_control_transfer(info->dev, LIBUSB_ENDPOINT_IN,
  1289. + LIBUSB_REQUEST_GET_DESCRIPTOR, dti,
  1290. + LanguageID, Buffer, (uint16_t) BufferLength, 1000);
  1291. + }
  1292. + }
  1293. +
  1294. // if(rc >= 0) {
  1295. // fprintf(info->script, "blackbox: usb %d dsc ", dti);
  1296. @@ -292,7 +404,16 @@ __winfnc BOOL WinUsb_ControlTransfer(
  1297. rc = libusb_control_transfer(info->dev,
  1298. SetupPacket.RequestType, SetupPacket.Request, SetupPacket.Value, SetupPacket.Index,
  1299. Buffer, SetupPacket.Length, 10000);
  1300. -
  1301. +
  1302. + //Wait for the device to come back if it re-enumerated, then retry
  1303. + if(rc == LIBUSB_ERROR_NO_DEVICE || rc == LIBUSB_ERROR_IO) {
  1304. + if(handle_usb_error(info, rc)) {
  1305. + rc = libusb_control_transfer(info->dev,
  1306. + SetupPacket.RequestType, SetupPacket.Request, SetupPacket.Value, SetupPacket.Index,
  1307. + Buffer, SetupPacket.Length, 10000);
  1308. + }
  1309. + }
  1310. +
  1311. if(rc < 0)
  1312. return FALSE;
  1313. #if 0
  1314. @@ -306,7 +427,7 @@ __winfnc BOOL WinUsb_ControlTransfer(
  1315. ULONG res = (ULONG) rc;
  1316. *LengthTransferred = res;
  1317. winerr_clear();
  1318. - usleep(500000);
  1319. + usleep(50000);
  1320. return TRUE;
  1321. }
  1322. WINAPI(WinUsb_ControlTransfer)
  1323. @@ -371,15 +492,24 @@ WinUsb_ReadPipe(
  1324. switch(wpi->PipeType) {
  1325. case UsbdPipeTypeBulk:
  1326. printf("bulk xfer\n");
  1327. - rc = libusb_bulk_transfer(
  1328. - dev->dev,
  1329. - PipeID,
  1330. - Buffer,
  1331. - BufferLength,
  1332. - (int*)LengthTransferred,
  1333. - dev->timeouts[PipeID]+1000);
  1334. - //sleep(3);
  1335. - printf("LengthTransferred: %d\n", *LengthTransferred);
  1336. + for(;;) {
  1337. + rc = libusb_bulk_transfer(
  1338. + dev->dev,
  1339. + PipeID,
  1340. + Buffer,
  1341. + BufferLength,
  1342. + (int*)LengthTransferred,
  1343. + dev->timeouts[PipeID]+1000);
  1344. + printf("LengthTransferred: %d\n", *LengthTransferred);
  1345. +
  1346. + //Device re-enumerated (the driver forces this during init)?
  1347. + //Wait for it to come back, then retry the transfer.
  1348. + if(rc == LIBUSB_ERROR_NO_DEVICE ||
  1349. + (rc == LIBUSB_ERROR_IO && *LengthTransferred == 0)) {
  1350. + if(handle_usb_error(dev, rc)) continue;
  1351. + }
  1352. + break;
  1353. + }
  1354. break;
  1355. case UsbdPipeTypeInterrupt:
  1356. @@ -430,7 +560,9 @@ WinUsb_ReadPipe(
  1357. return FALSE;
  1358. }
  1359. - exit(0); // Don't know what to do, panic quit
  1360. + //Report the failure to the driver instead of killing the process;
  1361. + //the driver's retry logic will handle re-initialization.
  1362. + return FALSE;
  1363. }
  1364. return TRUE;
  1365. @@ -508,17 +640,26 @@ WinUsb_WritePipe(
  1366. return TRUE;
  1367. }
  1368. - rc = libusb_bulk_transfer(dev->dev,
  1369. - PipeID,
  1370. - Buffer,
  1371. - BufferLength,
  1372. - &send,
  1373. - dev->timeouts[PipeID]+1000);
  1374. - printf("rc=%d send=%d\n", rc, send);
  1375. + for(;;) {
  1376. + rc = libusb_bulk_transfer(dev->dev,
  1377. + PipeID,
  1378. + Buffer,
  1379. + BufferLength,
  1380. + &send,
  1381. + dev->timeouts[PipeID]+1000);
  1382. + printf("rc=%d send=%d\n", rc, send);
  1383. +
  1384. + //Device re-enumerated (the driver forces this during init)?
  1385. + //Wait for it to come back, then retry the transfer.
  1386. + if(rc == LIBUSB_ERROR_NO_DEVICE ||
  1387. + (rc == LIBUSB_ERROR_IO && send == 0)) {
  1388. + if(handle_usb_error(dev, rc)) continue;
  1389. + }
  1390. + break;
  1391. + }
  1392. if(rc < 0) {
  1393. printf("E: xfer Failed - %s\n", libusb_error_name(rc));
  1394. - exit(0);
  1395. return FALSE;
  1396. }
  1397. *LengthTransferred = send;
  1398. diff --git a/meson.build b/meson.build
  1399. index af190d0..df53836 100644
  1400. --- a/meson.build
  1401. +++ b/meson.build
  1402. @@ -7,6 +7,6 @@ INSTALL_DIR = '/sbin/tudor'
  1403. subdir('libtudor')
  1404. subdir('cli')
  1405. -subdir('tudor-host')
  1406. -subdir('tudor-host-launcher')
  1407. -subdir('libfprint-tod')
  1408. +# subdir('tudor-host') # needs libfprint-2-tod-1, enable once TOD fork is installed
  1409. +# subdir('tudor-host-launcher')
  1410. +# subdir('libfprint-tod')
  1411. diff --git a/subprojects/cryptbridge/registry.c b/subprojects/cryptbridge/registry.c
  1412. index b850841..dc79911 100644
  1413. --- a/subprojects/cryptbridge/registry.c
  1414. +++ b/subprojects/cryptbridge/registry.c
  1415. @@ -98,7 +98,12 @@ static const char *get_base_path(void)
  1416. // registry_base_path = strdup("/tmp/regemu");
  1417. // }
  1418. - registry_base_path = strdup("/home/rstar000/Documents/fake_reg");
  1419. + const char *env = getenv("TUDOR_REGISTRY_PATH");
  1420. + if (env && env[0]) {
  1421. + registry_base_path = strdup(env);
  1422. + } else {
  1423. + registry_base_path = strdup("/tmp/tudor-registry");
  1424. + }
  1425. return registry_base_path;
  1426. }