win32.c 138 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * $Id$
 *
 * Originally distributed under LPGL 2.1 (or later) by the Wine project.
 *
 * Modified for use with MPlayer, detailed CVS changelog at
 * http://www.mplayerhq.hu/cgi-bin/cvsweb.cgi/main/
 *
 * File now distributed as part of VLC media player with no modifications.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 */

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/***********************************************************

Win32 emulation code. Functions that emulate
responses from corresponding Win32 API calls.
Since we are not going to be able to load
virtually any DLL, we can only implement this
much, adding needed functions with each new codec.

Basic principle of implementation: it's not good
for DLL to know too much about its environment.

************************************************************/

#include "config.h"

#ifdef MPLAYER
#ifdef USE_QTX_CODECS
#define QTX
#endif
#define REALPLAYER
//#define LOADLIB_TRY_NATIVE
#endif

#ifdef QTX
50 51
#define PSEUDO_SCREEN_WIDTH	/*640*/800
#define PSEUDO_SCREEN_HEIGHT	/*480*/600
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#endif

#include "wine/winbase.h"
#include "wine/winreg.h"
#include "wine/winnt.h"
#include "wine/winerror.h"
#include "wine/debugtools.h"
#include "wine/module.h"
#include "wine/winuser.h"

#include <stdio.h>
#include "win32.h"

#include "registry.h"
#include "loader.h"
#include "com.h"
#include "ext.h"

#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <ctype.h>
#include <pthread.h>
#include <errno.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/time.h>
#include <sys/timeb.h>
87
#ifdef	HAVE_KSTAT
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
#include <kstat.h>
#endif

#if HAVE_VSSCANF
int vsscanf( const char *str, const char *format, va_list ap);
#else
/* system has no vsscanf.  try to provide one */
static int vsscanf( const char *str, const char *format, va_list ap)
{
    long p1 = va_arg(ap, long);
    long p2 = va_arg(ap, long);
    long p3 = va_arg(ap, long);
    long p4 = va_arg(ap, long);
    long p5 = va_arg(ap, long);
    return sscanf(str, format, p1, p2, p3, p4, p5);
}
#endif

106
static char* def_path = WIN32_PATH;
107 108 109 110

static void do_cpuid(unsigned int ax, unsigned int *regs)
{
    __asm__ __volatile__
111 112 113 114 115 116 117 118 119 120 121
	(
	 "pushl %%ebx; pushl %%ecx; pushl %%edx;"
	 ".byte  0x0f, 0xa2;"
	 "movl   %%eax, (%2);"
	 "movl   %%ebx, 4(%2);"
	 "movl   %%ecx, 8(%2);"
	 "movl   %%edx, 12(%2);"
	 "popl %%edx; popl %%ecx; popl %%ebx;"
	 : "=a" (ax)
	 :  "0" (ax), "S" (regs)
	);
122 123 124 125 126
}
static unsigned int c_localcount_tsc()
{
    int a;
    __asm__ __volatile__
127 128 129 130 131 132
	(
	 "rdtsc\n\t"
	 :"=a"(a)
	 :
	 :"edx"
	);
133 134 135 136 137
    return a;
}
static void c_longcount_tsc(long long* z)
{
    __asm__ __volatile__
138 139 140 141 142 143 144 145 146 147
	(
	 "pushl %%ebx\n\t"
	 "movl %%eax, %%ebx\n\t"
	 "rdtsc\n\t"
	 "movl %%eax, 0(%%ebx)\n\t"
	 "movl %%edx, 4(%%ebx)\n\t"
	 "popl %%ebx\n\t"
	 ::"a"(z)
	 :"edx"
	);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
}
static unsigned int c_localcount_notsc()
{
    struct timeval tv;
    unsigned limit=~0;
    limit/=1000000;
    gettimeofday(&tv, 0);
    return limit*tv.tv_usec;
}
static void c_longcount_notsc(long long* z)
{
    struct timeval tv;
    unsigned long long result;
    unsigned limit=~0;
    if(!z)return;
    limit/=1000000;
    gettimeofday(&tv, 0);
    result=tv.tv_sec;
    result<<=32;
    result+=limit*tv.tv_usec;
    *z=result;
}
static unsigned int localcount_stub(void);
static void longcount_stub(long long*);
static unsigned int (*localcount)()=localcount_stub;
static void (*longcount)(long long*)=longcount_stub;

static pthread_mutex_t memmut;

static unsigned int localcount_stub(void)
{
    unsigned int regs[4];
    do_cpuid(1, regs);
    if ((regs[3] & 0x00000010) != 0)
    {
183 184
	localcount=c_localcount_tsc;
	longcount=c_longcount_tsc;
185 186 187
    }
    else
    {
188 189
	localcount=c_localcount_notsc;
	longcount=c_longcount_notsc;
190 191 192 193 194 195 196 197 198
    }
    return localcount();
}
static void longcount_stub(long long* z)
{
    unsigned int regs[4];
    do_cpuid(1, regs);
    if ((regs[3] & 0x00000010) != 0)
    {
199 200
	localcount=c_localcount_tsc;
	longcount=c_longcount_tsc;
201 202 203
    }
    else
    {
204 205
	localcount=c_localcount_notsc;
	longcount=c_longcount_notsc;
206 207 208 209 210 211 212 213 214
    }
    longcount(z);
}

#ifdef MPLAYER
#include "../mp_msg.h"
#endif
int LOADER_DEBUG=1; // active only if compiled with -DDETAILED_OUT
//#define DETAILED_OUT
Rafaël Carré's avatar
Rafaël Carré committed
215
static inline void dbgprintf(const char* fmt, ...)
216 217 218 219
{
#ifdef DETAILED_OUT
    if(LOADER_DEBUG)
    {
220 221 222 223 224 225 226 227 228 229 230 231 232
	FILE* f;
	va_list va;
	va_start(va, fmt);
	f=fopen("./log", "a");
	vprintf(fmt, va);
	fflush(stdout);
	if(f)
	{
	    vfprintf(f, fmt, va);
	    fsync(fileno(f));
	    fclose(f);
	}
	va_end(va);
233 234 235 236 237
    }
#endif
#ifdef MPLAYER
    if (verbose > 2)
    {
238 239 240 241 242 243
	va_list va;
	
	va_start(va, fmt);
	vprintf(fmt, va);
//	mp_dbg(MSGT_WIN32, MSGL_DBG3, fmt, va);
	va_end(va);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    }
  fflush(stdout);
#endif
}


char export_names[300][32]={
    "name1",
    //"name2",
    //"name3"
};
//#define min(x,y) ((x)<(y)?(x):(y))

void destroy_event(void* event);

struct th_list_t;
typedef struct th_list_t{
    int id;
    void* thread;
    struct th_list_t* next;
    struct th_list_t* prev;
} th_list;


// have to be cleared by GARBAGE COLLECTOR
static unsigned char* heap=NULL;
static int heap_counter=0;
static tls_t* g_tls=NULL;
static th_list* list=NULL;

static void test_heap(void)
{
    int offset=0;
    if(heap==0)
278
	return;
279 280
    while(offset<heap_counter)
    {
281 282 283 284 285 286
	if(*(int*)(heap+offset)!=0x433476)
	{
	    printf("Heap corruption at address %d\n", offset);
	    return;
	}
	offset+=8+*(int*)(heap+offset+4);
287 288
    }
    for(;offset<min(offset+1000, 20000000); offset++)
289 290 291 292
	if(heap[offset]!=0xCC)
	{
	    printf("Free heap corruption at address %d\n", offset);
	}
293 294 295 296 297 298 299 300 301 302 303 304 305
}
#undef MEMORY_DEBUG

#ifdef MEMORY_DEBUG

static void* my_mreq(int size, int to_zero)
{
    static int test=0;
    test++;
    if(test%10==0)printf("Memory: %d bytes allocated\n", heap_counter);
    //    test_heap();
    if(heap==NULL)
    {
306 307
	heap=malloc(20000000);
	memset(heap, 0xCC,20000000);
308 309 310
    }
    if(heap==0)
    {
311 312
	printf("No enough memory\n");
	return 0;
313 314 315
    }
    if(heap_counter+size>20000000)
    {
316 317
	printf("No enough memory\n");
	return 0;
318 319 320 321 322 323 324
    }
    *(int*)(heap+heap_counter)=0x433476;
    heap_counter+=4;
    *(int*)(heap+heap_counter)=size;
    heap_counter+=4;
    printf("Allocated %d bytes of memory: sys %d, user %d-%d\n", size, heap_counter-8, heap_counter, heap_counter+size);
    if(to_zero)
325
	memset(heap+heap_counter, 0, size);
326
    else
327
	memset(heap+heap_counter, 0xcc, size);  // make crash reproducable
328 329 330 331 332 333 334 335
    heap_counter+=size;
    return heap+heap_counter-size;
}
static int my_release(char* memory)
{
    //    test_heap();
    if(memory==NULL)
    {
336 337
	printf("ERROR: free(0)\n");
	return 0;
338 339 340
    }
    if(*(int*)(memory-8)!=0x433476)
    {
341 342
	printf("MEMORY CORRUPTION !!!!!!!!!!!!!!!!!!!\n");
	return 0;
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    }
    printf("Freed %d bytes of memory\n", *(int*)(memory-4));
    //    memset(memory-8, *(int*)(memory-4), 0xCC);
    return 0;
}

#else
#define GARBAGE
typedef struct alloc_header_t alloc_header;
struct alloc_header_t
{
    // let's keep allocated data 16 byte aligned
    alloc_header* prev;
    alloc_header* next;
    long deadbeef;
    long size;
    long type;
    long reserved1;
    long reserved2;
    long reserved3;
};

#ifdef GARBAGE
static alloc_header* last_alloc = NULL;
static int alccnt = 0;
#endif

#define AREATYPE_CLIENT 0
#define AREATYPE_EVENT 1
#define AREATYPE_MUTEX 2
#define AREATYPE_COND 3
#define AREATYPE_CRITSECT 4

/* -- critical sections -- */
struct CRITSECT
{
    pthread_t id;
    pthread_mutex_t mutex;
    int locked;
    long deadbeef;
};

void* mreq_private(int size, int to_zero, int type);
void* mreq_private(int size, int to_zero, int type)
{
    int nsize = size + sizeof(alloc_header);
    alloc_header* header = (alloc_header* ) malloc(nsize);
    if (!header)
        return 0;
    if (to_zero)
393
	memset(header, 0, nsize);
394 395 396
#ifdef GARBAGE
    if (!last_alloc)
    {
397 398
	pthread_mutex_init(&memmut, NULL);
	pthread_mutex_lock(&memmut);
399 400 401
    }
    else
    {
402 403
	pthread_mutex_lock(&memmut);
	last_alloc->next = header;  /* set next */
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    }

    header->prev = last_alloc;
    header->next = 0;
    last_alloc = header;
    alccnt++;
    pthread_mutex_unlock(&memmut);
#endif
    header->deadbeef = 0xdeadbeef;
    header->size = size;
    header->type = type;

    //if (alccnt < 40000) printf("MY_REQ: %p\t%d   t:%d  (cnt:%d)\n",  header, size, type, alccnt);
    return header + 1;
}

static int my_release(void* memory)
{
    alloc_header* header = (alloc_header*) memory - 1;
#ifdef GARBAGE
    alloc_header* prevmem;
    alloc_header* nextmem;

    if (memory == 0)
428
	return 0;
429 430 431

    if (header->deadbeef != (long) 0xdeadbeef)
    {
432 433
	dbgprintf("FATAL releasing corrupted memory! %p  0x%lx  (%d)\n", header, header->deadbeef, alccnt);
	return 0;
434 435 436 437 438 439 440
    }

    pthread_mutex_lock(&memmut);

    switch(header->type)
    {
    case AREATYPE_EVENT:
441 442
	destroy_event(memory);
	break;
443
    case AREATYPE_COND:
444 445
	pthread_cond_destroy((pthread_cond_t*)memory);
	break;
446
    case AREATYPE_MUTEX:
447 448
	pthread_mutex_destroy((pthread_mutex_t*)memory);
	break;
449
    case AREATYPE_CRITSECT:
450 451
	pthread_mutex_destroy(&((struct CRITSECT*)memory)->mutex);
	break;
452
    default:
453 454
	//memset(memory, 0xcc, header->size);
	;
455 456 457 458 459 460 461
    }

    header->deadbeef = 0;
    prevmem = header->prev;
    nextmem = header->next;

    if (prevmem)
462
	prevmem->next = nextmem;
463
    if (nextmem)
464
	nextmem->prev = prevmem;
465 466

    if (header == last_alloc)
467
	last_alloc = prevmem;
468 469 470 471

    alccnt--;

    if (last_alloc)
472
	pthread_mutex_unlock(&memmut);
473
    else
474
	pthread_mutex_destroy(&memmut);
475 476 477 478

    //if (alccnt < 40000) printf("MY_RELEASE: %p\t%ld    (%d)\n", header, header->size, alccnt);
#else
    if (memory == 0)
479
	return 0;
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
#endif
    //memset(header + 1, 0xcc, header->size);
    free(header);
    return 0;
}
#endif

static inline void* my_mreq(int size, int to_zero)
{
    return mreq_private(size, to_zero, AREATYPE_CLIENT);
}

static int my_size(void* memory)
{
    if(!memory) return 0;
    return ((alloc_header*)memory)[-1].size;
}

static void* my_realloc(void* memory, int size)
{
    void *ans = memory;
    int osize;
    if (memory == NULL)
503
	return my_mreq(size, 0);
504 505 506
    osize = my_size(memory);
    if (osize < size)
    {
507 508 509
	ans = my_mreq(size, 0);
	memcpy(ans, memory, osize);
	my_release(memory);
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    }
    return ans;
}

/*
 *
 *  WINE  API  - native implementation for several win32 libraries
 *
 */

static int WINAPI ext_unknown()
{
    printf("Unknown func called\n");
    return 0;
}

static int  WINAPI expGetVolumeInformationA( const char *root, char *label,
                                       unsigned int label_len, unsigned int *serial,
                                       unsigned int *filename_len,unsigned int *flags,
                                       char *fsname, unsigned int fsname_len )
{
dbgprintf("GetVolumeInformationA( %s, 0x%x, %ld, 0x%x, 0x%x, 0x%x, 0x%x, %ld) => 1\n",
532
		      root,label,label_len,serial,filename_len,flags,fsname,fsname_len);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
//hack Do not return any real data - do nothing
return 1;
}

static unsigned int WINAPI expGetDriveTypeA( const char *root )
{
 dbgprintf("GetDriveTypeA( %s ) => %d\n",root,DRIVE_FIXED);
 // hack return as Fixed Drive Type
 return DRIVE_FIXED;
}

static unsigned int WINAPI expGetLogicalDriveStringsA( unsigned int len, char *buffer )
{
 dbgprintf("GetLogicalDriveStringsA(%d, 0x%x) => 4\n",len,buffer);
 // hack only have one drive c:\ in this hack
  *buffer++='c';
  *buffer++=':';
  *buffer++='\\';
  *buffer++='\0';
  *buffer= '\0';
return 4; // 1 drive * 4 bytes (includes null)
}


static int WINAPI expIsBadWritePtr(void* ptr, unsigned int count)
{
    int result = (count == 0 || ptr != 0) ? 0 : 1;
    dbgprintf("IsBadWritePtr(0x%x, 0x%x) => %d\n", ptr, count, result);
    return result;
}
static int WINAPI expIsBadReadPtr(void* ptr, unsigned int count)
{
    int result = (count == 0 || ptr != 0) ? 0 : 1;
    dbgprintf("IsBadReadPtr(0x%x, 0x%x) => %d\n", ptr, count, result);
    return result;
}
static int WINAPI expDisableThreadLibraryCalls(int module)
{
    dbgprintf("DisableThreadLibraryCalls(0x%x) => 0\n", module);
    return 0;
}

static HMODULE WINAPI expGetDriverModuleHandle(DRVR* pdrv)
{
    HMODULE result;
    if (pdrv==NULL)
579
	result=0;
580
    else
581
	result=pdrv->hDriverModule;
582 583 584 585
    dbgprintf("GetDriverModuleHandle(%p) => %p\n", pdrv, result);
    return result;
}

586 587
#define	MODULE_HANDLE_kernel32	((HMODULE)0x120)
#define	MODULE_HANDLE_user32	((HMODULE)0x121)
588
#ifdef QTX
589 590 591
#define	MODULE_HANDLE_wininet	((HMODULE)0x122)
#define	MODULE_HANDLE_ddraw	((HMODULE)0x123)
#define	MODULE_HANDLE_advapi32	((HMODULE)0x124)
592
#endif
593 594 595 596
#define	MODULE_HANDLE_comdlg32	((HMODULE)0x125)
#define	MODULE_HANDLE_msvcrt	((HMODULE)0x126)
#define	MODULE_HANDLE_ole32	((HMODULE)0x127)
#define	MODULE_HANDLE_winmm	((HMODULE)0x128)
597 598 599 600 601 602 603

static HMODULE WINAPI expGetModuleHandleA(const char* name)
{
    WINE_MODREF* wm;
    HMODULE result;
    if(!name)
#ifdef QTX
604
	result=1;
605
#else
606
	result=0;
607 608 609
#endif
    else
    {
610 611 612 613
	wm=MODULE_FindModule(name);
	if(wm==0)result=0;
	else
	    result=(HMODULE)(wm->module);
614 615 616
    }
    if(!result)
    {
617 618
	if(name && (strcasecmp(name, "kernel32")==0 || !strcasecmp(name, "kernel32.dll")))
	    result=MODULE_HANDLE_kernel32;
619
#ifdef QTX
620 621
	if(name && strcasecmp(name, "user32")==0)
	    result=MODULE_HANDLE_user32;
622 623 624 625 626 627 628
#endif
    }
    dbgprintf("GetModuleHandleA('%s') => 0x%x\n", name, result);
    return result;
}

static void* WINAPI expCreateThread(void* pSecAttr, long dwStackSize,
629 630
				    void* lpStartAddress, void* lpParameter,
				    long dwFlags, long* dwThreadId)
631 632 633 634 635 636
{
    pthread_t *pth;
    //    printf("CreateThread:");
    pth = (pthread_t*) my_mreq(sizeof(pthread_t), 0);
    pthread_create(pth, NULL, (void*(*)(void*))lpStartAddress, lpParameter);
    if(dwFlags)
637
	printf( "WARNING: CreateThread flags not supported\n");
638
    if(dwThreadId)
639
	*dwThreadId=(long)pth;
640 641
    if(list==NULL)
    {
642 643
	list=my_mreq(sizeof(th_list), 1);
	list->next=list->prev=NULL;
644 645 646
    }
    else
    {
647 648 649 650
	list->next=my_mreq(sizeof(th_list), 0);
	list->next->prev=list;
	list->next->next=NULL;
	list=list->next;
651 652 653
    }
    list->thread=pth;
    dbgprintf("CreateThread(0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x) => 0x%x\n",
654
	      pSecAttr, dwStackSize, lpStartAddress, lpParameter, dwFlags, dwThreadId, pth);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    return pth;
}

struct mutex_list_t;

struct mutex_list_t
{
    char type;
    pthread_mutex_t *pm;
    pthread_cond_t  *pc;
    char state;
    char reset;
    char name[128];
    int  semaphore;
    struct mutex_list_t* next;
    struct mutex_list_t* prev;
};
typedef struct mutex_list_t mutex_list;
static mutex_list* mlist=NULL;

void destroy_event(void* event)
{
    mutex_list* pp=mlist;
    //    printf("garbage collector: destroy_event(%x)\n", event);
    while(pp)
    {
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
	if(pp==(mutex_list*)event)
	{
	    if(pp->next)
		pp->next->prev=pp->prev;
	    if(pp->prev)
		pp->prev->next=pp->next;
	    if(mlist==(mutex_list*)event)
		mlist=mlist->prev;
	    /*
	     pp=mlist;
	     while(pp)
	     {
	     printf("%x => ", pp);
	     pp=pp->prev;
	     }
	     printf("0\n");
	     */
	    return;
	}
	pp=pp->prev;
701 702 703 704
    }
}

static void* WINAPI expCreateEventA(void* pSecAttr, char bManualReset,
705
				    char bInitialState, const char* name)
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
{
    pthread_mutex_t *pm;
    pthread_cond_t  *pc;
    /*
     mutex_list* pp;
     pp=mlist;
     while(pp)
     {
     printf("%x => ", pp);
     pp=pp->prev;
     }
     printf("0\n");
     */
    if(mlist!=NULL)
    {
721 722 723 724 725 726 727 728 729 730 731
	mutex_list* pp=mlist;
	if(name!=NULL)
	    do
	{
	    if((strcmp(pp->name, name)==0) && (pp->type==0))
	    {
		dbgprintf("CreateEventA(0x%x, 0x%x, 0x%x, 0x%x='%s') => 0x%x\n",
			  pSecAttr, bManualReset, bInitialState, name, name, pp->pm);
		return pp->pm;
	    }
	}while((pp=pp->prev) != NULL);
732 733 734 735 736 737 738
    }
    pm=mreq_private(sizeof(pthread_mutex_t), 0, AREATYPE_MUTEX);
    pthread_mutex_init(pm, NULL);
    pc=mreq_private(sizeof(pthread_cond_t), 0, AREATYPE_COND);
    pthread_cond_init(pc, NULL);
    if(mlist==NULL)
    {
739 740
	mlist=mreq_private(sizeof(mutex_list), 00, AREATYPE_EVENT);
	mlist->next=mlist->prev=NULL;
741 742 743
    }
    else
    {
744 745 746 747
	mlist->next=mreq_private(sizeof(mutex_list), 00, AREATYPE_EVENT);
	mlist->next->prev=mlist;
	mlist->next->next=NULL;
	mlist=mlist->next;
748 749 750 751 752 753 754
    }
    mlist->type=0; /* Type Event */
    mlist->pm=pm;
    mlist->pc=pc;
    mlist->state=bInitialState;
    mlist->reset=bManualReset;
    if(name)
755
	strncpy(mlist->name, name, 127);
756
    else
757
	mlist->name[0]=0;
758
    if(pm==NULL)
759
	dbgprintf("ERROR::: CreateEventA failure\n");
760 761 762 763 764
    /*
     if(bInitialState)
     pthread_mutex_lock(pm);
     */
    if(name)
765 766
	dbgprintf("CreateEventA(0x%x, 0x%x, 0x%x, 0x%x='%s') => 0x%x\n",
		  pSecAttr, bManualReset, bInitialState, name, name, mlist);
767
    else
768 769
	dbgprintf("CreateEventA(0x%x, 0x%x, 0x%x, NULL) => 0x%x\n",
		  pSecAttr, bManualReset, bInitialState, mlist);
770 771 772 773 774 775 776 777 778
    return mlist;
}

static void* WINAPI expSetEvent(void* event)
{
    mutex_list *ml = (mutex_list *)event;
    dbgprintf("SetEvent(%x) => 0x1\n", event);
    pthread_mutex_lock(ml->pm);
    if (ml->state == 0) {
779 780
	ml->state = 1;
	pthread_cond_signal(ml->pc);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    }
    pthread_mutex_unlock(ml->pm);

    return (void *)1;
}
static void* WINAPI expResetEvent(void* event)
{
    mutex_list *ml = (mutex_list *)event;
    dbgprintf("ResetEvent(0x%x) => 0x1\n", event);
    pthread_mutex_lock(ml->pm);
    ml->state = 0;
    pthread_mutex_unlock(ml->pm);

    return (void *)1;
}

static void* WINAPI expWaitForSingleObject(void* object, int duration)
{
    mutex_list *ml = (mutex_list *)object;
    // FIXME FIXME FIXME - this value is sometime unititialize !!!
    int ret = WAIT_FAILED;
    mutex_list* pp=mlist;
    if(object == (void*)0xcfcf9898)
    {
805 806 807
	/**
	 From GetCurrentThread() documentation:
	 A pseudo handle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself whenever a thread handle is required. Pseudo handles are not inherited by child processes.
808

809
	 This handle has the maximum possible access to the thread object. For systems that support security descriptors, this is the maximum access allowed by the security descriptor for the calling process. For systems that do not support security descriptors, this is THREAD_ALL_ACCESS.
810

811 812 813 814
	 The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always interpreted as referring to the thread that is using it. A thread can create a "real" handle to itself that can be used by other threads, or inherited by other processes, by specifying the pseudo handle as the source handle in a call to the DuplicateHandle function.
	 **/
	dbgprintf("WaitForSingleObject(thread_handle) called\n");
	return (void*)WAIT_FAILED;
815 816 817 818 819 820
    }
    dbgprintf("WaitForSingleObject(0x%x, duration %d) =>\n",object, duration);

    // loop below was slightly fixed - its used just for checking if
    // this object really exists in our list
    if (!ml)
821
	return (void*) ret;
822
    while (pp && (pp->pm != ml->pm))
823
	pp = pp->prev;
824
    if (!pp) {
825 826
	dbgprintf("WaitForSingleObject: NotFound\n");
	return (void*)ret;
827 828 829 830 831 832
    }

    pthread_mutex_lock(ml->pm);

    switch(ml->type) {
    case 0: /* Event */
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
	if (duration == 0) { /* Check Only */
	    if (ml->state == 1) ret = WAIT_FAILED;
	    else                   ret = WAIT_OBJECT_0;
	}
	if (duration == -1) { /* INFINITE */
	    if (ml->state == 0)
		pthread_cond_wait(ml->pc,ml->pm);
	    if (ml->reset)
		ml->state = 0;
	    ret = WAIT_OBJECT_0;
	}
	if (duration > 0) {  /* Timed Wait */
	    struct timespec abstime;
	    struct timeval now;
	    gettimeofday(&now, 0);
	    abstime.tv_sec = now.tv_sec + (now.tv_usec+duration)/1000000;
	    abstime.tv_nsec = ((now.tv_usec+duration)%1000000)*1000;
	    if (ml->state == 0)
		ret=pthread_cond_timedwait(ml->pc,ml->pm,&abstime);
	    if (ret == ETIMEDOUT) ret = WAIT_TIMEOUT;
	    else                  ret = WAIT_OBJECT_0;
	    if (ml->reset)
		ml->state = 0;
	}
	break;
858
    case 1:  /* Semaphore */
859 860 861 862 863 864 865 866 867 868 869 870 871
	if (duration == 0) {
	    if(ml->semaphore==0) ret = WAIT_FAILED;
	    else {
		ml->semaphore++;
		ret = WAIT_OBJECT_0;
	    }
	}
	if (duration == -1) {
	    if (ml->semaphore==0)
		pthread_cond_wait(ml->pc,ml->pm);
	    ml->semaphore--;
	}
	break;
872 873 874 875 876 877 878 879 880
    }
    pthread_mutex_unlock(ml->pm);

    dbgprintf("WaitForSingleObject(0x%x, %d): 0x%x => 0x%x \n",object,duration,ml,ret);
    return (void *)ret;
}

#ifdef QTX
static void* WINAPI expWaitForMultipleObjects(int count, const void** objects,
881
		    int WaitAll, int duration)
882 883 884 885 886 887
{
    int i;
    void *object;
    void *ret;

    dbgprintf("WaitForMultipleObjects(%d, 0x%x, %d, duration %d) =>\n",
888 889
	count, objects, WaitAll, duration);
    
890 891
    for (i = 0; i < count; i++)
    {
892 893 894 895 896 897
	object = (void *)objects[i];
	ret = expWaitForSingleObject(object, duration);
	if (WaitAll)
	    dbgprintf("WaitAll flag not yet supported...\n");
	else
	    return ret;
898 899 900 901 902 903 904 905 906 907 908
    }
    return NULL;
}

static void WINAPI expExitThread(int retcode)
{
    dbgprintf("ExitThread(%d)\n", retcode);
    pthread_exit(&retcode);
}

static HANDLE WINAPI expCreateMutexA(void *pSecAttr,
909
		    char bInitialOwner, const char *name)
910 911
{
    HANDLE mlist = (HANDLE)expCreateEventA(pSecAttr, 0, 0, name);
912
    
913
    if (name)
914 915
	dbgprintf("CreateMutexA(0x%x, %d, '%s') => 0x%x\n",
	    pSecAttr, bInitialOwner, name, mlist);
916
    else
917 918
	dbgprintf("CreateMutexA(0x%x, %d, NULL) => 0x%x\n",
	    pSecAttr, bInitialOwner, mlist);
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
#ifndef QTX
    /* 10l to QTX, if CreateMutex returns a real mutex, WaitForSingleObject
       waits for ever, else it works ;) */
    return mlist;
#endif
}

static int WINAPI expReleaseMutex(HANDLE hMutex)
{
    dbgprintf("ReleaseMutex(%x) => 1\n", hMutex);
    /* FIXME:XXX !! not yet implemented */
    return 1;
}
#endif

static int pf_set = 0;
static BYTE PF[64] = {0,};

static void DumpSystemInfo(const SYSTEM_INFO* si)
{
    dbgprintf("  Processor architecture %d\n", si->u.s.wProcessorArchitecture);
    dbgprintf("  Page size: %d\n", si->dwPageSize);
    dbgprintf("  Minimum app address: %d\n", si->lpMinimumApplicationAddress);
    dbgprintf("  Maximum app address: %d\n", si->lpMaximumApplicationAddress);
    dbgprintf("  Active processor mask: 0x%x\n", si->dwActiveProcessorMask);
    dbgprintf("  Number of processors: %d\n", si->dwNumberOfProcessors);
    dbgprintf("  Processor type: 0x%x\n", si->dwProcessorType);
    dbgprintf("  Allocation granularity: 0x%x\n", si->dwAllocationGranularity);
    dbgprintf("  Processor level: 0x%x\n", si->wProcessorLevel);
    dbgprintf("  Processor revision: 0x%x\n", si->wProcessorRevision);
}

static void WINAPI expGetSystemInfo(SYSTEM_INFO* si)
{
    /* FIXME: better values for the two entries below... */
    static int cache = 0;
    static SYSTEM_INFO cachedsi;
    unsigned int regs[4];
    dbgprintf("GetSystemInfo(%p) =>\n", si);

    if (cache) {
960 961 962
	memcpy(si,&cachedsi,sizeof(*si));
	DumpSystemInfo(si);
	return;
963 964 965 966 967
    }
    memset(PF,0,sizeof(PF));
    pf_set = 1;

    cachedsi.u.s.wProcessorArchitecture     = PROCESSOR_ARCHITECTURE_INTEL;
968
    cachedsi.dwPageSize 			= getpagesize();
969 970

    /* FIXME: better values for the two entries below... */
971 972 973 974 975 976 977 978
    cachedsi.lpMinimumApplicationAddress	= (void *)0x00000000;
    cachedsi.lpMaximumApplicationAddress	= (void *)0x7FFFFFFF;
    cachedsi.dwActiveProcessorMask		= 1;
    cachedsi.dwNumberOfProcessors		= 1;
    cachedsi.dwProcessorType		= PROCESSOR_INTEL_386;
    cachedsi.dwAllocationGranularity	= 0x10000;
    cachedsi.wProcessorLevel		= 5; /* pentium */
    cachedsi.wProcessorRevision		= 0x0101;
979 980 981 982 983

#ifdef MPLAYER
    /* mplayer's way to detect PF's */
    {
#include "../cpudetect.h"
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
	extern CpuCaps gCpuCaps;

	if (gCpuCaps.hasMMX)
	    PF[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
	if (gCpuCaps.hasSSE)
	    PF[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
	if (gCpuCaps.has3DNow)
	    PF[PF_AMD3D_INSTRUCTIONS_AVAILABLE] = TRUE;

	    if (gCpuCaps.cpuType == 4)
	    {
	        cachedsi.dwProcessorType = PROCESSOR_INTEL_486;
		cachedsi.wProcessorLevel = 4;
	    }
	    else if (gCpuCaps.cpuType >= 5)
	    {
		cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		cachedsi.wProcessorLevel = 5;
	    }
	    else
	    {
	        cachedsi.dwProcessorType = PROCESSOR_INTEL_386;
		cachedsi.wProcessorLevel = 3;
	    }
	    cachedsi.wProcessorRevision = gCpuCaps.cpuStepping;
    	    cachedsi.dwNumberOfProcessors = 1;	/* hardcoded */
1010 1011 1012 1013 1014 1015 1016
    }
#endif

/* disable cpuid based detection (mplayer's cpudetect.c does this - see above) */
#ifndef MPLAYER
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__svr4__) || defined(__DragonFly__)
    do_cpuid(1, regs);
1017
    switch ((regs[0] >> 8) & 0xf) {			// cpu family
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    case 3: cachedsi.dwProcessorType = PROCESSOR_INTEL_386;
    cachedsi.wProcessorLevel= 3;
    break;
    case 4: cachedsi.dwProcessorType = PROCESSOR_INTEL_486;
    cachedsi.wProcessorLevel= 4;
    break;
    case 5: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
    cachedsi.wProcessorLevel= 5;
    break;
    case 6: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
    cachedsi.wProcessorLevel= 5;
    break;
    default:cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
    cachedsi.wProcessorLevel= 5;
    break;
    }
1034
    cachedsi.wProcessorRevision = regs[0] & 0xf;	// stepping
1035
    if (regs[3] & (1 <<  8))
1036
	PF[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
1037
    if (regs[3] & (1 << 23))
1038
	PF[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
1039
    if (regs[3] & (1 << 25))
1040
	PF[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
1041
    if (regs[3] & (1 << 31))
1042
	PF[PF_AMD3D_INSTRUCTIONS_AVAILABLE] = TRUE;
1043 1044 1045 1046 1047 1048 1049 1050
    cachedsi.dwNumberOfProcessors=1;
#endif
#endif /* MPLAYER */

/* MPlayer: linux detection enabled (based on proc/cpuinfo) for checking
   fdiv_bug and fpu emulation flags -- alex/MPlayer */
#ifdef __linux__
    {
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
	char buf[20];
	char line[200];
	FILE *f = fopen ("/proc/cpuinfo", "r");

	if (!f)
	    return;
	while (fgets(line,200,f)!=NULL) {
	    char	*s,*value;

	    /* NOTE: the ':' is the only character we can rely on */
	    if (!(value = strchr(line,':')))
		continue;
	    /* terminate the valuename */
	    *value++ = '\0';
	    /* skip any leading spaces */
	    while (*value==' ') value++;
	    if ((s=strchr(value,'\n')))
		*s='\0';

	    /* 2.1 method */
	    if (!lstrncmpiA(line, "cpu family",strlen("cpu family"))) {
		if (isdigit (value[0])) {
		    switch (value[0] - '0') {
		    case 3: cachedsi.dwProcessorType = PROCESSOR_INTEL_386;
		    cachedsi.wProcessorLevel= 3;
		    break;
		    case 4: cachedsi.dwProcessorType = PROCESSOR_INTEL_486;
		    cachedsi.wProcessorLevel= 4;
		    break;
		    case 5: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    case 6: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    default:cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    }
		}
		/* set the CPU type of the current processor */
		sprintf(buf,"CPU %ld",cachedsi.dwProcessorType);
		continue;
	    }
	    /* old 2.0 method */
	    if (!lstrncmpiA(line, "cpu",strlen("cpu"))) {
		if (	isdigit (value[0]) && value[1] == '8' &&
			value[2] == '6' && value[3] == 0
		   ) {
		    switch (value[0] - '0') {
		    case 3: cachedsi.dwProcessorType = PROCESSOR_INTEL_386;
		    cachedsi.wProcessorLevel= 3;
		    break;
		    case 4: cachedsi.dwProcessorType = PROCESSOR_INTEL_486;
		    cachedsi.wProcessorLevel= 4;
		    break;
		    case 5: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    case 6: cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    default:cachedsi.dwProcessorType = PROCESSOR_INTEL_PENTIUM;
		    cachedsi.wProcessorLevel= 5;
		    break;
		    }
		}
		/* set the CPU type of the current processor */
		sprintf(buf,"CPU %ld",cachedsi.dwProcessorType);
		continue;
	    }
	    if (!lstrncmpiA(line,"fdiv_bug",strlen("fdiv_bug"))) {
		if (!lstrncmpiA(value,"yes",3))
		    PF[PF_FLOATING_POINT_PRECISION_ERRATA] = TRUE;

		continue;
	    }
	    if (!lstrncmpiA(line,"fpu",strlen("fpu"))) {
		if (!lstrncmpiA(value,"no",2))
		    PF[PF_FLOATING_POINT_EMULATED] = TRUE;

		continue;
	    }
	    if (!lstrncmpiA(line,"processor",strlen("processor"))) {
		/* processor number counts up...*/
		unsigned int x;

		if (sscanf(value,"%d",&x))
		    if (x+1>cachedsi.dwNumberOfProcessors)
			cachedsi.dwNumberOfProcessors=x+1;

		/* Create a new processor subkey on a multiprocessor
		 * system
		 */
		sprintf(buf,"%d",x);
	    }
	    if (!lstrncmpiA(line,"stepping",strlen("stepping"))) {
		int	x;

		if (sscanf(value,"%d",&x))
		    cachedsi.wProcessorRevision = x;
	    }
	    if
		( (!lstrncmpiA(line,"flags",strlen("flags")))
		  || (!lstrncmpiA(line,"features",strlen("features"))) )
	    {
		if (strstr(value,"cx8"))
		    PF[PF_COMPARE_EXCHANGE_DOUBLE] = TRUE;
		if (strstr(value,"mmx"))
		    PF[PF_MMX_INSTRUCTIONS_AVAILABLE] = TRUE;
		if (strstr(value,"tsc"))
		    PF[PF_RDTSC_INSTRUCTION_AVAILABLE] = TRUE;
		if (strstr(value,"xmm"))
		    PF[PF_XMMI_INSTRUCTIONS_AVAILABLE] = TRUE;
		if (strstr(value,"3dnow"))
		    PF[PF_AMD3D_INSTRUCTIONS_AVAILABLE] = TRUE;
	    }
	}
	fclose (f);
	/*
	 *	ad hoc fix for smp machines.
	 *	some problems on WaitForSingleObject,CreateEvent,SetEvent
	 *			CreateThread ...etc..
	 *
	 */
	cachedsi.dwNumberOfProcessors=1;
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    }
#endif /* __linux__ */
    cache = 1;
    memcpy(si,&cachedsi,sizeof(*si));
    DumpSystemInfo(si);
}

// avoid undefined expGetSystemInfo
static WIN_BOOL WINAPI expIsProcessorFeaturePresent(DWORD v)
{
    WIN_BOOL result = 0;
    if (!pf_set)
    {
1190 1191
	SYSTEM_INFO si;
	expGetSystemInfo(&si);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    }
    if(v<64) result=PF[v];
    dbgprintf("IsProcessorFeaturePresent(0x%x) => 0x%x\n", v, result);
    return result;
}


static long WINAPI expGetVersion()
{
    dbgprintf("GetVersion() => 0xC0000004\n");
    return 0xC0000004;//Windows 95
}

static HANDLE WINAPI expHeapCreate(long flags, long init_size, long max_size)
{
    //    printf("HeapCreate:");
    HANDLE result;
    if(init_size==0)
1210
	result=(HANDLE)my_mreq(0x110000, 0);
1211
    else
1212
	result=(HANDLE)my_mreq((init_size + 0xfff) & 0x7ffff000 , 0);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    dbgprintf("HeapCreate(flags 0x%x, initial size %d, maximum size %d) => 0x%x\n", flags, init_size, max_size, result);
    return result;
}

// this is another dirty hack
// VP31 is releasing one allocated Heap chunk twice
// we will silently ignore this second call...
static void* heapfreehack = 0;
static int heapfreehackshown = 0;
//extern void trapbug(void);
static void* WINAPI expHeapAlloc(HANDLE heap, int flags, int size)
{
    void* z;
    /**
     Morgan's m3jpeg32.dll v. 2.0 encoder expects that request for
     HeapAlloc returns area larger than size argument :-/

     actually according to M$ Doc  HeapCreate size should be rounded
     to page boundaries thus we should simulate this
     **/
    //if (size == 22276) trapbug();
    z=my_mreq((size + 0xfff) & 0x7ffff000, (flags & HEAP_ZERO_MEMORY));
    if(z==0)
1236
	printf("HeapAlloc failure\n");
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    dbgprintf("HeapAlloc(heap 0x%x, flags 0x%x, size %d) => 0x%x\n", heap, flags, size, z);
    heapfreehack = 0; // reset
    return z;
}
static long WINAPI expHeapDestroy(void* heap)
{
    dbgprintf("HeapDestroy(heap 0x%x) => 1\n", heap);
    my_release(heap);
    return 1;
}

static long WINAPI expHeapFree(HANDLE heap, DWORD dwFlags, LPVOID lpMem)
{
    dbgprintf("HeapFree(0x%x, 0x%x, pointer 0x%x) => 1\n", heap, dwFlags, lpMem);
    if (heapfreehack != lpMem && lpMem != (void*)0xffffffff
1252 1253 1254
	&& lpMem != (void*)0xbdbdbdbd)
	// 0xbdbdbdbd is for i263_drv.drv && libefence
	// it seems to be reading from relased memory
1255
        // EF_PROTECT_FREE doens't show any probleme
1256
	my_release(lpMem);
1257 1258
    else
    {
1259 1260
	if (!heapfreehackshown++)
	    printf("Info: HeapFree deallocating same memory twice! (%p)\n", lpMem);
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    }
    heapfreehack = lpMem;
    return 1;
}
static long WINAPI expHeapSize(int heap, int flags, void* pointer)
{
    long result=my_size(pointer);
    dbgprintf("HeapSize(heap 0x%x, flags 0x%x, pointer 0x%x) => %d\n", heap, flags, pointer, result);
    return result;
}
static void* WINAPI expHeapReAlloc(HANDLE heap,int flags,void *lpMem,int size)
{
    long orgsize = my_size(lpMem);
    dbgprintf("HeapReAlloc() Size %ld org %d\n",orgsize,size);
    return my_realloc(lpMem, size);
}
static long WINAPI expGetProcessHeap(void)
{
    dbgprintf("GetProcessHeap() => 1\n");
    return 1;
}
static void* WINAPI expVirtualAlloc(void* v1, long v2, long v3, long v4)
{
    void* z = VirtualAlloc(v1, v2, v3, v4);
    if(z==0)
1286
	printf("VirtualAlloc failure\n");
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    dbgprintf("VirtualAlloc(0x%x, %d, %d, %d) => 0x%x \n",v1,v2,v3,v4, z);
    return z;
}
static int WINAPI expVirtualFree(void* v1, int v2, int v3)
{
    int result = VirtualFree(v1,v2,v3);
    dbgprintf("VirtualFree(0x%x, %d, %d) => %d\n",v1,v2,v3, result);
    return result;
}

/* we're building a table of critical sections. cs_win pointer uses the DLL
 cs_unix is the real structure, we're using cs_win only to identifying cs_unix */
struct critsecs_list_t
{
    CRITICAL_SECTION *cs_win;
    struct CRITSECT *cs_unix;
};

/* 'NEWTYPE' is working with VIVO, 3ivX and QTX dll (no more segfaults) -- alex */
#undef CRITSECS_NEWTYPE
//#define CRITSECS_NEWTYPE 1

#ifdef CRITSECS_NEWTYPE
/* increased due to ucod needs more than 32 entries */
/* and 64 should be enough for everything */
#define CRITSECS_LIST_MAX 64
static struct critsecs_list_t critsecs_list[CRITSECS_LIST_MAX];

static int critsecs_get_pos(CRITICAL_SECTION *cs_win)
{
    int i;

    for (i=0; i < CRITSECS_LIST_MAX; i++)
1320 1321
	if (critsecs_list[i].cs_win == cs_win)
	    return(i);
1322 1323 1324 1325 1326 1327 1328 1329
    return(-1);
}

static int critsecs_get_unused(void)
{
    int i;

    for (i=0; i < CRITSECS_LIST_MAX; i++)
1330 1331
	if (critsecs_list[i].cs_win == NULL)
	    return(i);
1332 1333 1334 1335 1336 1337 1338 1339
    return(-1);
}

struct CRITSECT *critsecs_get_unix(CRITICAL_SECTION *cs_win)
{
    int i;

    for (i=0; i < CRITSECS_LIST_MAX; i++)
1340 1341
	if (critsecs_list[i].cs_win == cs_win && critsecs_list[i].cs_unix)
	    return(critsecs_list[i].cs_unix);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    return(NULL);
}
#endif

static void WINAPI expInitializeCriticalSection(CRITICAL_SECTION* c)
{
    dbgprintf("InitializeCriticalSection(0x%x)\n", c);
    /*    if(sizeof(pthread_mutex_t)>sizeof(CRITICAL_SECTION))
     {
     printf(" ERROR:::: sizeof(pthread_mutex_t) is %d, expected <=%d!\n",
     sizeof(pthread_mutex_t), sizeof(CRITICAL_SECTION));
     return;
     }*/
    /*    pthread_mutex_init((pthread_mutex_t*)c, NULL);   */
#ifdef CRITSECS_NEWTYPE
    {
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
	struct CRITSECT *cs;
	int i = critsecs_get_unused();

	if (i < 0)
	{
	    printf("InitializeCriticalSection(%p) - no more space in list\n", c);
	    return;
	}
	dbgprintf("got unused space at %d\n", i);
	cs = malloc(sizeof(struct CRITSECT));
	if (!cs)
	{
	    printf("InitializeCriticalSection(%p) - out of memory\n", c);
	    return;
	}
	pthread_mutex_init(&cs->mutex, NULL);
	cs->locked = 0;
	critsecs_list[i].cs_win = c;
	critsecs_list[i].cs_unix = cs;
	dbgprintf("InitializeCriticalSection -> itemno=%d, cs_win=%p, cs_unix=%p\n",
		  i, c, cs);
1379 1380 1381
    }
#else
    {
1382 1383 1384 1385
	struct CRITSECT* cs = mreq_private(sizeof(struct CRITSECT) + sizeof(CRITICAL_SECTION),
					   0, AREATYPE_CRITSECT);
	pthread_mutex_init(&cs->mutex, NULL);
	cs->locked=0;
1386
        cs->deadbeef = 0xdeadbeef;
1387
	*(void**)c = cs;
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    }
#endif
    return;
}

static void WINAPI expEnterCriticalSection(CRITICAL_SECTION* c)
{
#ifdef CRITSECS_NEWTYPE
    struct CRITSECT* cs = critsecs_get_unix(c);
#else
    struct CRITSECT* cs = (*(struct CRITSECT**)c);
#endif
    dbgprintf("EnterCriticalSection(0x%x) %p\n",c, cs);
    if (!cs)
    {
1403 1404
	dbgprintf("entered uninitialized critisec!\n");
	expInitializeCriticalSection(c);
1405
#ifdef CRITSECS_NEWTYPE
1406
	cs=critsecs_get_unix(c);
1407
#else
1408
	cs = (*(struct CRITSECT**)c);
1409
#endif
1410
	dbgprintf("Win32 Warning: Accessed uninitialized Critical Section (%p)!\n", c);
1411 1412
    }
    if(cs->locked)
1413 1414
	if(cs->id==pthread_self())
	    return;
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
    pthread_mutex_lock(&(cs->mutex));
    cs->locked=1;
    cs->id=pthread_self();
    return;
}
static void WINAPI expLeaveCriticalSection(CRITICAL_SECTION* c)
{
#ifdef CRITSECS_NEWTYPE
    struct CRITSECT* cs = critsecs_get_unix(c);
#else
    struct CRITSECT* cs = (*(struct CRITSECT**)c);
#endif
    //    struct CRITSECT* cs=(struct CRITSECT*)c;
    dbgprintf("LeaveCriticalSection(0x%x) 0x%x\n",c, cs);
    if (!cs)
    {
1431 1432
	dbgprintf("Win32 Warning: Leaving uninitialized Critical Section %p!!\n", c);
	return;
1433 1434 1435
    }
    if (cs->locked)
    {
1436 1437
	cs->locked=0;
	pthread_mutex_unlock(&(cs->mutex));
1438 1439
    }
    else
1440
	dbgprintf("Win32 Warning: Unlocking unlocked Critical Section %p!!\n", c);
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
    return;
}

static void expfree(void* mem); /* forward declaration */

static void WINAPI expDeleteCriticalSection(CRITICAL_SECTION *c)
{
#ifdef CRITSECS_NEWTYPE
    struct CRITSECT* cs = critsecs_get_unix(c);
#else
    struct CRITSECT* cs= (*(struct CRITSECT**)c);
#endif
    //    struct CRITSECT* cs=(struct CRITSECT*)c;
    dbgprintf("DeleteCriticalSection(0x%x)\n",c);

    if (!cs)
    {
1458 1459
	dbgprintf("Win32 Warning: Deleting uninitialized Critical Section %p!!\n", c);
	return;
1460
    }
1461
    
1462 1463
    if (cs->locked)
    {
1464 1465
	dbgprintf("Win32 Warning: Deleting unlocked Critical Section %p!!\n", c);
	pthread_mutex_unlock(&(cs->mutex));
1466 1467 1468 1469 1470 1471 1472 1473 1474
    }

#ifndef GARBAGE
    pthread_mutex_destroy(&(cs->mutex));
    // released by GarbageCollector in my_relase otherwise
#endif
    my_release(cs);
#ifdef CRITSECS_NEWTYPE
    {
1475
	int i = critsecs_get_pos(c);
1476

1477 1478 1479 1480 1481
	if (i < 0)
	{
	    printf("DeleteCriticalSection(%p) error (critsec not found)\n", c);
	    return;
	}
1482

1483 1484 1485 1486
	critsecs_list[i].cs_win = NULL;
	expfree(critsecs_list[i].cs_unix);
	critsecs_list[i].cs_unix = NULL;
	dbgprintf("DeleteCriticalSection -> itemno=%d\n", i);
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    }
#endif
    return;
}
static int WINAPI expGetCurrentThreadId()
{
    dbgprintf("GetCurrentThreadId() => %d\n", pthread_self());
    return pthread_self();
}
static int WINAPI expGetCurrentProcess()
{
    dbgprintf("GetCurrentProcess() => %d\n", getpid());
    return getpid();
}

#ifdef QTX
// this version is required for Quicktime codecs (.qtx/.qts) to work.
// (they assume some pointers at FS: segment)

extern void* fs_seg;

//static int tls_count;
static int tls_use_map[64];
static int WINAPI expTlsAlloc()
{
    int i;
    for(i=0; i<64; i++)
1514 1515 1516 1517 1518 1519
	if(tls_use_map[i]==0)
	{
	    tls_use_map[i]=1;
	    dbgprintf("TlsAlloc() => %d\n",i);
	    return i;
	}
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    dbgprintf("TlsAlloc() => -1 (ERROR)\n");
    return -1;
}

//static int WINAPI expTlsSetValue(DWORD index, void* value)
static int WINAPI expTlsSetValue(int index, void* value)
{
    dbgprintf("TlsSetValue(%d,0x%x) => 1\n",index,value);
//    if((index<0) || (index>64))
    if((index>=64))
1530
	return 0;
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    *(void**)((char*)fs_seg+0x88+4*index) = value;
    return 1;
}

static void* WINAPI expTlsGetValue(DWORD index)
{
    dbgprintf("TlsGetValue(%d)\n",index);
//    if((index<0) || (index>64))
    if((index>=64)) return NULL;
    return *(void**)((char*)fs_seg+0x88+4*index);
}

static int WINAPI expTlsFree(int idx)
{
    int index = (int) idx;
    dbgprintf("TlsFree(%d)\n",index);
    if((index<0) || (index>64))
1548
	return 0;
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    tls_use_map[index]=0;
    return 1;
}

#else
struct tls_s {
    void* value;
    int used;
    struct tls_s* prev;
    struct tls_s* next;
};

static void* WINAPI expTlsAlloc()
{
    if (g_tls == NULL)
    {
1565 1566
	g_tls=my_mreq(sizeof(tls_t), 0);
	g_tls->next=g_tls->prev=NULL;
1567 1568 1569
    }
    else
    {
1570 1571 1572 1573
	g_tls->next=my_mreq(sizeof(tls_t), 0);
	g_tls->next->prev=g_tls;
	g_tls->next->next=NULL;
	g_tls=g_tls->next;
1574 1575 1576
    }
    dbgprintf("TlsAlloc() => 0x%x\n", g_tls);
    if (g_tls)
1577
	g_tls->value=0; /* XXX For Divx.dll */
1578 1579 1580 1581 1582 1583 1584 1585
    return g_tls;
}

static int WINAPI expTlsSetValue(void* idx, void* value)
{
    tls_t* index = (tls_t*) idx;
    int result;
    if(index==0)
1586
	result=0;
1587 1588
    else
    {
1589 1590
	index->value=value;
	result=1;
1591 1592 1593 1594 1595 1596 1597 1598 1599
    }
    dbgprintf("TlsSetValue(index 0x%x, value 0x%x) => %d \n", index, value, result );
    return result;
}
static void* WINAPI expTlsGetValue(void* idx)
{
    tls_t* index = (tls_t*) idx;
    void* result;
    if(index==0)
1600
	result=0;
1601
    else
1602
	result=index->value;
1603 1604 1605 1606 1607 1608 1609 1610
    dbgprintf("TlsGetValue(index 0x%x) => 0x%x\n", index, result);
    return result;
}
static int WINAPI expTlsFree(void* idx)
{
    tls_t* index = (tls_t*) idx;
    int result;
    if(index==0)
1611
	result=0;
1612 1613
    else
    {
1614 1615 1616 1617 1618
	if(index->next)
	    index->next->prev=index->prev;
	if(index->prev)
	    index->prev->next=index->next;
	if (g_tls == index)
1619
            g_tls = index->prev;
1620 1621
	my_release((void*)index);
	result=1;
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
    }
    dbgprintf("TlsFree(index 0x%x) => %d\n", index, result);
    return result;
}
#endif

static void* WINAPI expLocalAlloc(int flags, int size)
{
    void* z = my_mreq(size, (flags & GMEM_ZEROINIT));
    if (z == 0)
1632
	printf("LocalAlloc() failed\n");
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    dbgprintf("LocalAlloc(%d, flags 0x%x) => 0x%x\n", size, flags, z);
    return z;
}

static void* WINAPI expLocalReAlloc(int handle,int size, int flags)
{
    void *newpointer;
    int oldsize;

    newpointer=NULL;
    if (flags & LMEM_MODIFY) {
1644 1645
	dbgprintf("LocalReAlloc MODIFY\n");
	return (void *)handle;
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    }
    oldsize = my_size((void *)handle);
    newpointer = my_realloc((void *)handle,size);
    dbgprintf("LocalReAlloc(%x %d(old %d), flags 0x%x) => 0x%x\n", handle,size,oldsize, flags,newpointer);

    return newpointer;
}

static void* WINAPI expLocalLock(void* z)
{
    dbgprintf("LocalLock(0x%x) => 0x%x\n", z, z);
    return z;
}

static void* WINAPI expGlobalAlloc(int flags, int size)
{
    void* z;
    dbgprintf("GlobalAlloc(%d, flags 0x%X)\n", size, flags);

    z=my_mreq(size, (flags & GMEM_ZEROINIT));
    //z=calloc(size, 1);
    //z=malloc(size);
    if(z==0)
1669
	printf("GlobalAlloc() failed\n");
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    dbgprintf("GlobalAlloc(%d, flags 0x%x) => 0x%x\n", size, flags, z);
    return z;
}
static void* WINAPI expGlobalLock(void* z)
{
    dbgprintf("GlobalLock(0x%x) => 0x%x\n", z, z);
    return z;
}
// pvmjpg20 - but doesn't work anyway
static int WINAPI expGlobalSize(void* amem)
{
    int size = 100000;
#ifdef GARBAGE
    alloc_header* header = last_alloc;
    alloc_header* mem = (alloc_header*) amem - 1;
    if (amem == 0)
1686
	return 0;
1687 1688 1689
    pthread_mutex_lock(&memmut);
    while (header)
    {
1690 1691 1692 1693 1694
	if (header->deadbeef != 0xdeadbeef)
	{
	    dbgprintf("FATAL found corrupted memory! %p  0x%lx  (%d)\n", header, header->deadbeef, alccnt);
	    break;
	}
1695

1696 1697 1698 1699 1700
	if (header == mem)
	{
	    size = header->size;
	    break;
	}
1701

1702
	header = header->prev;
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    }
    pthread_mutex_unlock(&memmut);
#endif

    dbgprintf("GlobalSize(0x%x)\n", amem);
    return size;
}

static int WINAPI expLoadIconA( long hinstance, char *name )
{
 dbgprintf("LoadIconA( %ld, 0x%x ) => 1\n",hinstance,name);
 return 1;
}

static int WINAPI expLoadStringA(long instance, long  id, void* buf, long size)
{
    int result=LoadStringA(instance, id, buf, size);
    //    if(buf)
    dbgprintf("LoadStringA(instance 0x%x, id 0x%x, buffer 0x%x, size %d) => %d ( %s )\n",
1722
	      instance, id, buf, size, result, buf);
1723 1724
    //    else
    //    dbgprintf("LoadStringA(instance 0x%x, id 0x%x, buffer 0x%x, size %d) => %d\n",
1725
    //	instance, id, buf, size, result);
1726 1727 1728 1729 1730 1731 1732 1733 1734
    return result;
}

static long WINAPI expMultiByteToWideChar(long v1, long v2, char* s1, long siz1, short* s2, int siz2)
{
#warning FIXME
    int i;
    int result;
    if(s2==0)
1735
	result=1;
1736 1737
    else
    {
1738 1739 1740 1741 1742 1743 1744 1745 1746
	if(siz1>siz2/2)siz1=siz2/2;
	for(i=1; i<=siz1; i++)
	{
	    *s2=*s1;
	    if(!*s1)break;
	    s2++;
	    s1++;
	}
	result=i;
1747 1748
    }
    if(s1)
1749 1750 1751
	dbgprintf("MultiByteToWideChar(codepage %d, flags 0x%x, string 0x%x='%s',"
		  "size %d, dest buffer 0x%x, dest size %d) => %d\n",
		  v1, v2, s1, s1, siz1, s2, siz2, result);
1752
    else
1753 1754 1755
	dbgprintf("MultiByteToWideChar(codepage %d, flags 0x%x, string NULL,"
		  "size %d, dest buffer 0x%x, dest size %d) =>\n",
		  v1, v2, siz1, s2, siz2, result);
1756 1757 1758 1759 1760 1761 1762 1763 1764
    return result;
}
static void wch_print(const short* str)
{
    dbgprintf("  src: ");
    while(*str)dbgprintf("%c", *str++);
    dbgprintf("\n");
}
static long WINAPI expWideCharToMultiByte(long v1, long v2, short* s1, long siz1,
1765
					  char* s2, int siz2, char* c3, int* siz3)
1766 1767 1768
{
    int result;
    dbgprintf("WideCharToMultiByte(codepage %d, flags 0x%x, src 0x%x, src size %d, "
1769
	      "dest 0x%x, dest size %d, defch 0x%x, used_defch 0x%x)", v1, v2, s1, siz1, s2, siz2, c3, siz3);
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    result=WideCharToMultiByte(v1, v2, s1, siz1, s2, siz2, c3, siz3);
    dbgprintf("=> %d\n", result);
    //if(s1)wch_print(s1);
    if(s2)dbgprintf("  dest: %s\n", s2);
    return result;
}
static long WINAPI expGetVersionExA(OSVERSIONINFOA* c)
{
    dbgprintf("GetVersionExA(0x%x) => 1\n");
    c->dwOSVersionInfoSize=sizeof(*c);
    c->dwMajorVersion=4;
    c->dwMinorVersion=0;
    c->dwBuildNumber=0x4000457;
#if 1
    // leave it here for testing win9x-only codecs
    c->dwPlatformId=VER_PLATFORM_WIN32_WINDOWS;
    strcpy(c->szCSDVersion, " B");
#else
    c->dwPlatformId=VER_PLATFORM_WIN32_NT; // let's not make DLL assume that it can read CR* registers
    strcpy(c->szCSDVersion, "Service Pack 3");
#endif
    dbgprintf("  Major version: 4\n  Minor version: 0\n  Build number: 0x4000457\n"
1792
	      "  Platform Id: VER_PLATFORM_WIN32_NT\n Version string: 'Service Pack 3'\n");
1793 1794 1795
    return 1;
}
static HANDLE WINAPI expCreateSemaphoreA(char* v1, long init_count,
1796
					 long max_count, char* name)
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
{
    pthread_mutex_t *pm;
    pthread_cond_t  *pc;
    mutex_list* pp;
    /*
     printf("CreateSemaphoreA(%p = %s)\n", name, (name ? name : "<null>"));
     pp=mlist;
     while(pp)
     {
     printf("%p => ", pp);
     pp=pp->prev;
     }
     printf("0\n");
     */
    if(mlist!=NULL)
    {
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
	mutex_list* pp=mlist;
	if(name!=NULL)
	    do
	{
	    if((strcmp(pp->name, name)==0) && (pp->type==1))
	    {
		dbgprintf("CreateSemaphoreA(0x%x, init_count %d, max_count %d, name 0x%x='%s') => 0x%x\n",
			  v1, init_count, max_count, name, name, mlist);
		return (HANDLE)mlist;
	    }
	}while((pp=pp->prev) != NULL);
1824 1825 1826 1827 1828 1829 1830
    }
    pm=mreq_private(sizeof(pthread_mutex_t), 0, AREATYPE_MUTEX);
    pthread_mutex_init(pm, NULL);
    pc=mreq_private(sizeof(pthread_cond_t), 0, AREATYPE_COND);
    pthread_cond_init(pc, NULL);
    if(mlist==NULL)
    {
1831 1832
	mlist=mreq_private(sizeof(mutex_list), 00, AREATYPE_EVENT);
	mlist->next=mlist->prev=NULL;
1833 1834 1835
    }
    else
    {
1836 1837 1838 1839 1840
	mlist->next=mreq_private(sizeof(mutex_list), 00, AREATYPE_EVENT);
	mlist->next->prev=mlist;
	mlist->next->next=NULL;
	mlist=mlist->next;
	//	printf("new semaphore %p\n", mlist);
1841 1842 1843 1844 1845 1846 1847 1848
    }
    mlist->type=1; /* Type Semaphore */
    mlist->pm=pm;
    mlist->pc=pc;
    mlist->state=0;
    mlist->reset=0;
    mlist->semaphore=init_count;
    if(name!=NULL)
1849
	strncpy(mlist->name, name, 64);
1850
    else
1851
	mlist->name[0]=0;
1852
    if(pm==NULL)
1853
	dbgprintf("ERROR::: CreateSemaphoreA failure\n");
1854
    if(name)
1855 1856
	dbgprintf("CreateSemaphoreA(0x%x, init_count %d, max_count %d, name 0x%x='%s') => 0x%x\n",
		  v1, init_count, max_count, name, name, mlist);
1857
    else
1858 1859
	dbgprintf("CreateSemaphoreA(0x%x, init_count %d, max_count %d, name 0) => 0x%x\n",
		  v1, init_count, max_count, mlist);
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
    return (HANDLE)mlist;
}

static long WINAPI expReleaseSemaphore(long hsem, long increment, long* prev_count)
{
    // The state of a semaphore object is signaled when its count
    // is greater than zero and nonsignaled when its count is equal to zero
    // Each time a waiting thread is released because of the semaphore's signaled
    // state, the count of the semaphore is decreased by one.
    mutex_list *ml = (mutex_list *)hsem;

    pthread_mutex_lock(ml->pm);
    if (prev_count != 0) *prev_count = ml->semaphore;
    if (ml->semaphore == 0) pthread_cond_signal(ml->pc);
    ml->semaphore += increment;
    pthread_mutex_unlock(ml->pm);
    dbgprintf("ReleaseSemaphore(semaphore 0x%x, increment %d, prev_count 0x%x) => 1\n",
1877
	      hsem, increment, prev_count);
1878 1879 1880 1881 1882 1883 1884 1885
    return 1;
}


static long WINAPI expRegOpenKeyExA(long key, const char* subkey, long reserved, long access, int* newkey)
{
    long result=RegOpenKeyExA(key, subkey, reserved, access, newkey);
    dbgprintf("RegOpenKeyExA(key 0x%x, subkey %s, reserved %d, access 0x%x, pnewkey 0x%x) => %d\n",
1886
	      key, subkey, reserved, access, newkey, result);
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    if(newkey)dbgprintf("  New key: 0x%x\n", *newkey);
    return result;
}
static long WINAPI expRegCloseKey(long key)
{
    long result=RegCloseKey(key);
    dbgprintf("RegCloseKey(0x%x) => %d\n", key, result);
    return result;
}
static long WINAPI expRegQueryValueExA(long key, const char* value, int* reserved, int* type, int* data, int* count)
{
    long result=RegQueryValueExA(key, value, reserved, type, data, count);
    dbgprintf("RegQueryValueExA(key 0x%x, value %s, reserved 0x%x, data 0x%x, count 0x%x)"
1900
	      " => 0x%x\n", key, value, reserved, data, count, result);
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
    if(data && count)dbgprintf("  read %d bytes: '%s'\n", *count, data);
    return result;
}

//from wine source dlls/advapi32/registry.c
static long WINAPI expRegCreateKeyA(long hkey, const char* name, int *retkey)
{
    dbgprintf("RegCreateKeyA(key 0x%x, name 0x%x='%s',newkey=0x%x)\n",hkey,name,retkey);
    return RegCreateKeyExA( hkey, name, 0, NULL,REG_OPTION_NON_VOLATILE,
                            KEY_ALL_ACCESS , NULL, retkey, NULL );
}

static long WINAPI expRegCreateKeyExA(long key, const char* name, long reserved,
1914 1915
				      void* classs, long options, long security,
				      void* sec_attr, int* newkey, int* status)
1916 1917 1918
{
    long result=RegCreateKeyExA(key, name, reserved, classs, options, security, sec_attr, newkey, status);
    dbgprintf("RegCreateKeyExA(key 0x%x, name 0x%x='%s', reserved=0x%x,"
1919 1920
	      " 0x%x, 0x%x, 0x%x, newkey=0x%x, status=0x%x) => %d\n",
	      key, name, name, reserved, classs, options, security, sec_attr, newkey, status, result);
1921 1922 1923 1924 1925 1926 1927 1928
    if(!result && newkey) dbgprintf("  New key: 0x%x\n", *newkey);
    if(!result && status) dbgprintf("  New key status: 0x%x\n", *status);
    return result;
}
static long WINAPI expRegSetValueExA(long key, const char* name, long v1, long v2, void* data, long size)
{
    long result=RegSetValueExA(key, name, v1, v2, data, size);
    dbgprintf("RegSetValueExA(key 0x%x, name '%s', 0x%x, 0x%x, data 0x%x -> 0x%x '%s', size=%d) => %d",
1929
	      key, name, v1, v2, data, *(int*)data, data, size, result);
1930 1931 1932 1933 1934 1935 1936
    return result;
}

static long WINAPI expRegOpenKeyA (long hKey, LPCSTR lpSubKey, int* phkResult)
{
    long result=RegOpenKeyExA(hKey, lpSubKey, 0, 0, phkResult);
    dbgprintf("RegOpenKeyExA(key 0x%x, subkey '%s', 0x%x) => %d\n",
1937
	      hKey, lpSubKey, phkResult, result);
1938 1939 1940 1941 1942
    if(!result && phkResult) dbgprintf("  New key: 0x%x\n", *phkResult);
    return result;
}

static DWORD WINAPI expRegEnumValueA(HKEY hkey, DWORD index, LPSTR value, LPDWORD val_count,
1943
				     LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count)
1944 1945
{
    return RegEnumValueA(hkey, index, value, val_count,