ntdll: Mac OS support for saving and restoring the extended FPU context on exceptions.
[wine] / programs / wineboot / wineboot.c
1 /*
2  * Copyright (C) 2002 Andreas Mohr
3  * Copyright (C) 2002 Shachar Shemesh
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19 /* Wine "bootup" handler application
20  *
21  * This app handles the various "hooks" windows allows for applications to perform
22  * as part of the bootstrap process. These are roughly divided into three types.
23  * Knowledge base articles that explain this are 137367, 179365, 232487 and 232509.
24  * Also, 119941 has some info on grpconv.exe
25  * The operations performed are (by order of execution):
26  *
27  * Preboot (prior to fully loading the Windows kernel):
28  * - wininit.exe (rename operations left in wininit.ini - Win 9x only)
29  * - PendingRenameOperations (rename operations left in the registry - Win NT+ only)
30  *
31  * Startup (before the user logs in)
32  * - Services (NT)
33  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce (9x, asynch)
34  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices (9x, asynch)
35  * 
36  * After log in
37  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, synch)
38  * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
39  * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
40  * - Startup folders (all, ?asynch?)
41  * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, asynch)
42  *
43  * Somewhere in there is processing the RunOnceEx entries (also no imp)
44  * 
45  * Bugs:
46  * - If a pending rename registry does not start with \??\ the entry is
47  *   processed anyways. I'm not sure that is the Windows behaviour.
48  * - Need to check what is the windows behaviour when trying to delete files
49  *   and directories that are read-only
50  * - In the pending rename registry processing - there are no traces of the files
51  *   processed (requires translations from Unicode to Ansi).
52  */
53
54 #include "config.h"
55 #include "wine/port.h"
56
57 #define WIN32_LEAN_AND_MEAN
58
59 #include <stdio.h>
60 #ifdef HAVE_GETOPT_H
61 # include <getopt.h>
62 #endif
63 #include <windows.h>
64 #include <wine/unicode.h>
65 #include <wine/debug.h>
66
67 #define COBJMACROS
68 #include <shlobj.h>
69 #include <shobjidl.h>
70 #include <shlwapi.h>
71 #include <shellapi.h>
72
73 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
74
75 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
76
77 extern BOOL shutdown_close_windows( BOOL force );
78 extern void kill_processes( BOOL kill_desktop );
79
80 static WCHAR windowsdir[MAX_PATH];
81
82 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
83  * Returns FALSE if there was an error, or otherwise if all is ok.
84  */
85 static BOOL wininit(void)
86 {
87     static const WCHAR nulW[] = {'N','U','L',0};
88     static const WCHAR renameW[] = {'r','e','n','a','m','e',0};
89     static const WCHAR wininitW[] = {'w','i','n','i','n','i','t','.','i','n','i',0};
90     static const WCHAR wininitbakW[] = {'w','i','n','i','n','i','t','.','b','a','k',0};
91     WCHAR initial_buffer[1024];
92     WCHAR *str, *buffer = initial_buffer;
93     DWORD size = sizeof(initial_buffer)/sizeof(WCHAR);
94     DWORD res;
95
96     for (;;)
97     {
98         if (!(res = GetPrivateProfileSectionW( renameW, buffer, size, wininitW ))) return TRUE;
99         if (res < size - 2) break;
100         if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
101         size *= 2;
102         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
103     }
104
105     for (str = buffer; *str; str += strlenW(str) + 1)
106     {
107         WCHAR *value;
108
109         if (*str == ';') continue;  /* comment */
110         if (!(value = strchrW( str, '=' ))) continue;
111
112         /* split the line into key and value */
113         *value++ = 0;
114
115         if (!lstrcmpiW( nulW, str ))
116         {
117             WINE_TRACE("Deleting file %s\n", wine_dbgstr_w(value) );
118             if( !DeleteFileW( value ) )
119                 WINE_WARN("Error deleting file %s\n", wine_dbgstr_w(value) );
120         }
121         else
122         {
123             WINE_TRACE("Renaming file %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
124
125             if( !MoveFileExW(value, str, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) )
126                 WINE_WARN("Error renaming %s to %s\n", wine_dbgstr_w(value), wine_dbgstr_w(str) );
127         }
128         str = value;
129     }
130
131     if (buffer != initial_buffer) HeapFree( GetProcessHeap(), 0, buffer );
132
133     if( !MoveFileExW( wininitW, wininitbakW, MOVEFILE_REPLACE_EXISTING) )
134     {
135         WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
136
137         return FALSE;
138     }
139
140     return TRUE;
141 }
142
143 static BOOL pendingRename(void)
144 {
145     static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
146                                       'F','i','l','e','R','e','n','a','m','e',
147                                       'O','p','e','r','a','t','i','o','n','s',0};
148     static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
149                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
150                                      'C','o','n','t','r','o','l','\\',
151                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
152     WCHAR *buffer=NULL;
153     const WCHAR *src=NULL, *dst=NULL;
154     DWORD dataLength=0;
155     HKEY hSession=NULL;
156     DWORD res;
157
158     WINE_TRACE("Entered\n");
159
160     if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
161             !=ERROR_SUCCESS )
162     {
163         WINE_TRACE("The key was not found - skipping\n");
164         return TRUE;
165     }
166
167     res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
168                                                              truly a REG_MULTI_SZ anyways */,
169             NULL, &dataLength );
170     if( res==ERROR_FILE_NOT_FOUND )
171     {
172         /* No value - nothing to do. Great! */
173         WINE_TRACE("Value not present - nothing to rename\n");
174         res=TRUE;
175         goto end;
176     }
177
178     if( res!=ERROR_SUCCESS )
179     {
180         WINE_ERR("Couldn't query value's length (%d)\n", res );
181         res=FALSE;
182         goto end;
183     }
184
185     buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
186     if( buffer==NULL )
187     {
188         WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
189         res=FALSE;
190         goto end;
191     }
192
193     res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
194     if( res!=ERROR_SUCCESS )
195     {
196         WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
197                 "please report to wine-devel@winehq.org\n", res);
198         res=FALSE;
199         goto end;
200     }
201
202     /* Make sure that the data is long enough and ends with two NULLs. This
203      * simplifies the code later on.
204      */
205     if( dataLength<2*sizeof(buffer[0]) ||
206             buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
207             buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
208     {
209         WINE_ERR("Improper value format - doesn't end with NULL\n");
210         res=FALSE;
211         goto end;
212     }
213
214     for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
215             src=dst+lstrlenW(dst)+1 )
216     {
217         DWORD dwFlags=0;
218
219         WINE_TRACE("processing next command\n");
220
221         dst=src+lstrlenW(src)+1;
222
223         /* We need to skip the \??\ header */
224         if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
225             src+=4;
226
227         if( dst[0]=='!' )
228         {
229             dwFlags|=MOVEFILE_REPLACE_EXISTING;
230             dst++;
231         }
232
233         if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
234             dst+=4;
235
236         if( *dst!='\0' )
237         {
238             /* Rename the file */
239             MoveFileExW( src, dst, dwFlags );
240         } else
241         {
242             /* Delete the file or directory */
243             if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
244             {
245                 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
246                 {
247                     /* It's a file */
248                     DeleteFileW(src);
249                 } else
250                 {
251                     /* It's a directory */
252                     RemoveDirectoryW(src);
253                 }
254             } else
255             {
256                 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
257             }
258         }
259     }
260
261     if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
262     {
263         WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
264         res=FALSE;
265     } else
266         res=TRUE;
267     
268 end:
269     HeapFree(GetProcessHeap(), 0, buffer);
270
271     if( hSession!=NULL )
272         RegCloseKey( hSession );
273
274     return res;
275 }
276
277 enum runkeys {
278     RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
279 };
280
281 const WCHAR runkeys_names[][30]=
282 {
283     {'R','u','n',0},
284     {'R','u','n','O','n','c','e',0},
285     {'R','u','n','S','e','r','v','i','c','e','s',0},
286     {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
287 };
288
289 #define INVALID_RUNCMD_RETURN -1
290 /*
291  * This function runs the specified command in the specified dir.
292  * [in,out] cmdline - the command line to run. The function may change the passed buffer.
293  * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
294  * [in] wait - whether to wait for the run program to finish before returning.
295  * [in] minimized - Whether to ask the program to run minimized.
296  *
297  * Returns:
298  * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
299  * If wait is FALSE - returns 0 if successful.
300  * If wait is TRUE - returns the program's return value.
301  */
302 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
303 {
304     STARTUPINFOW si;
305     PROCESS_INFORMATION info;
306     DWORD exit_code=0;
307
308     memset(&si, 0, sizeof(si));
309     si.cb=sizeof(si);
310     if( minimized )
311     {
312         si.dwFlags=STARTF_USESHOWWINDOW;
313         si.wShowWindow=SW_MINIMIZE;
314     }
315     memset(&info, 0, sizeof(info));
316
317     if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
318     {
319         WINE_WARN("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline), GetLastError() );
320         return INVALID_RUNCMD_RETURN;
321     }
322
323     WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
324                wine_dbgstr_w(cmdline), info.hProcess );
325
326     if(wait)
327     {   /* wait for the process to exit */
328         WaitForSingleObject(info.hProcess, INFINITE);
329         GetExitCodeProcess(info.hProcess, &exit_code);
330     }
331
332     CloseHandle( info.hProcess );
333
334     return exit_code;
335 }
336
337 /*
338  * Process a "Run" type registry key.
339  * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
340  *      opened.
341  * szKeyName is the key holding the actual entries.
342  * bDelete tells whether we should delete each value right before executing it.
343  * bSynchronous tells whether we should wait for the prog to complete before
344  *      going on to the next prog.
345  */
346 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
347         BOOL bSynchronous )
348 {
349     static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
350         'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
351         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
352     HKEY hkWin, hkRun;
353     DWORD res;
354     DWORD i, nMaxCmdLine=0, nMaxValue=0;
355     WCHAR *szCmdLine=NULL;
356     WCHAR *szValue=NULL;
357
358     if (hkRoot==HKEY_LOCAL_MACHINE)
359         WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
360     else
361         WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
362
363     if (RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ) != ERROR_SUCCESS)
364         return TRUE;
365
366     if (RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ) != ERROR_SUCCESS)
367     {
368         RegCloseKey( hkWin );
369         return TRUE;
370     }
371     RegCloseKey( hkWin );
372
373     if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
374                     &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
375         goto end;
376
377     if( i==0 )
378     {
379         WINE_TRACE("No commands to execute.\n");
380
381         res=ERROR_SUCCESS;
382         goto end;
383     }
384     
385     if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
386     {
387         WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
388
389         res=ERROR_NOT_ENOUGH_MEMORY;
390         goto end;
391     }
392
393     if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
394     {
395         WINE_ERR("Couldn't allocate memory for the value names\n");
396
397         res=ERROR_NOT_ENOUGH_MEMORY;
398         goto end;
399     }
400     
401     while( i>0 )
402     {
403         DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
404         DWORD type;
405
406         --i;
407
408         if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
409                         (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
410         {
411             WINE_ERR("Couldn't read in value %d - %d\n", i, res );
412
413             continue;
414         }
415
416         if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
417         {
418             WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
419         }
420         
421         if( type!=REG_SZ )
422         {
423             WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
424
425             continue;
426         }
427
428         if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
429         {
430             WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
431         }
432
433         WINE_TRACE("Done processing cmd #%d\n", i);
434     }
435
436     res=ERROR_SUCCESS;
437
438 end:
439     HeapFree( GetProcessHeap(), 0, szValue );
440     HeapFree( GetProcessHeap(), 0, szCmdLine );
441
442     if( hkRun!=NULL )
443         RegCloseKey( hkRun );
444
445     WINE_TRACE("done\n");
446
447     return res==ERROR_SUCCESS;
448 }
449
450 /*
451  * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
452  * of known good dlls and scans through and replaces corrupted DLLs with these
453  * known good versions. The only programs that should install into this dll
454  * cache are Windows Updates and IE (which is treated like a Windows Update)
455  *
456  * Implementing this allows installing ie in win2k mode to actually install the
457  * system dlls that we expect and need
458  */
459 static int ProcessWindowsFileProtection(void)
460 {
461     static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
462                                       'M','i','c','r','o','s','o','f','t','\\',
463                                       'W','i','n','d','o','w','s',' ','N','T','\\',
464                                       'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
465                                       'W','i','n','l','o','g','o','n',0};
466     static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
467     static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
468     static const WCHAR wildcardW[] = {'\\','*',0};
469     WIN32_FIND_DATAW finddata;
470     HANDLE find_handle;
471     BOOL find_rc;
472     DWORD rc;
473     HKEY hkey;
474     LPWSTR dllcache = NULL;
475
476     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
477     {
478         DWORD sz = 0;
479         if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
480         {
481             sz += sizeof(WCHAR);
482             dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
483             RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
484             strcatW( dllcache, wildcardW );
485         }
486     }
487     RegCloseKey(hkey);
488
489     if (!dllcache)
490     {
491         DWORD sz = GetSystemDirectoryW( NULL, 0 );
492         dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
493         GetSystemDirectoryW( dllcache, sz );
494         strcatW( dllcache, dllcacheW );
495     }
496
497     find_handle = FindFirstFileW(dllcache,&finddata);
498     dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
499     find_rc = find_handle != INVALID_HANDLE_VALUE;
500     while (find_rc)
501     {
502         static const WCHAR dotW[] = {'.',0};
503         static const WCHAR dotdotW[] = {'.','.',0};
504         WCHAR targetpath[MAX_PATH];
505         WCHAR currentpath[MAX_PATH];
506         UINT sz;
507         UINT sz2;
508         WCHAR tempfile[MAX_PATH];
509
510         if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
511         {
512             find_rc = FindNextFileW(find_handle,&finddata);
513             continue;
514         }
515
516         sz = MAX_PATH;
517         sz2 = MAX_PATH;
518         VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
519                      windowsdir, currentpath, &sz, targetpath, &sz2);
520         sz = MAX_PATH;
521         rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
522                              dllcache, targetpath, currentpath, tempfile, &sz);
523         if (rc != ERROR_SUCCESS)
524         {
525             WINE_ERR("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
526             DeleteFileW(tempfile);
527         }
528         find_rc = FindNextFileW(find_handle,&finddata);
529     }
530     FindClose(find_handle);
531     HeapFree(GetProcessHeap(),0,dllcache);
532     return 1;
533 }
534
535 /* start services */
536 static void start_services(void)
537 {
538     static const WCHAR servicesW[] = {'S','y','s','t','e','m','\\',
539                                       'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
540                                       'S','e','r','v','i','c','e','s',0};
541     static const WCHAR startW[] = {'S','t','a','r','t',0};
542     HKEY hkey, skey;
543     DWORD type, size, start, index = 0;
544     WCHAR name[MAX_PATH];
545     SC_HANDLE manager;
546
547     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, servicesW, &hkey )) return;
548
549     if (!(manager = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS )))
550     {
551         RegCloseKey( hkey );
552         return;
553     }
554
555     while (!RegEnumKeyW( hkey, index++, name, sizeof(name) ))
556     {
557         if (RegOpenKeyW( hkey, name, &skey )) continue;
558         size = sizeof(start);
559         if (!RegQueryValueExW( skey, startW, NULL, &type, (LPBYTE)&start, &size ) && type == REG_DWORD)
560         {
561             if (start == SERVICE_BOOT_START ||
562                 start == SERVICE_SYSTEM_START ||
563                 start == SERVICE_AUTO_START)
564             {
565                 SC_HANDLE handle = OpenServiceW( manager, name, SERVICE_ALL_ACCESS );
566                 if (handle)
567                 {
568                     WINE_TRACE( "starting service %s start %u\n", wine_dbgstr_w(name), start );
569                     StartServiceW( handle, 0, NULL );
570                     CloseServiceHandle( handle );
571                 }
572             }
573         }
574         RegCloseKey( skey );
575     }
576     CloseServiceHandle( manager );
577     RegCloseKey( hkey );
578 }
579
580 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
581  * shell links here to restart themselves after boot. */
582 static BOOL ProcessStartupItems(void)
583 {
584     BOOL ret = FALSE;
585     HRESULT hr;
586     int iRet;
587     IMalloc *ppM = NULL;
588     IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
589     LPITEMIDLIST pidlStartup = NULL, pidlItem;
590     ULONG NumPIDLs;
591     IEnumIDList *iEnumList = NULL;
592     STRRET strret;
593     WCHAR wszCommand[MAX_PATH];
594
595     WINE_TRACE("Processing items in the StartUp folder.\n");
596
597     hr = SHGetMalloc(&ppM);
598     if (FAILED(hr))
599     {
600         WINE_ERR("Couldn't get IMalloc object.\n");
601         goto done;
602     }
603
604     hr = SHGetDesktopFolder(&psfDesktop);
605     if (FAILED(hr))
606     {
607         WINE_ERR("Couldn't get desktop folder.\n");
608         goto done;
609     }
610
611     hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
612     if (FAILED(hr))
613     {
614         WINE_TRACE("Couldn't get StartUp folder location.\n");
615         goto done;
616     }
617
618     hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
619     if (FAILED(hr))
620     {
621         WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
622         goto done;
623     }
624
625     hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
626     if (FAILED(hr))
627     {
628         WINE_TRACE("Unable to enumerate StartUp objects.\n");
629         goto done;
630     }
631
632     while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
633            (NumPIDLs) == 1)
634     {
635         hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
636         if (FAILED(hr))
637             WINE_TRACE("Unable to get display name of enumeration item.\n");
638         else
639         {
640             hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
641             if (FAILED(hr))
642                 WINE_TRACE("Unable to parse display name.\n");
643             else
644                 if ((iRet = (int)ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL)) <= 32)
645                     WINE_WARN("Error %d executing command %s.\n", iRet, wine_dbgstr_w(wszCommand));
646         }
647
648         IMalloc_Free(ppM, pidlItem);
649     }
650
651     /* Return success */
652     ret = TRUE;
653
654 done:
655     if (iEnumList) IEnumIDList_Release(iEnumList);
656     if (psfStartup) IShellFolder_Release(psfStartup);
657     if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
658
659     return ret;
660 }
661
662 static void usage(void)
663 {
664     WINE_MESSAGE( "Usage: wineboot [options]\n" );
665     WINE_MESSAGE( "Options;\n" );
666     WINE_MESSAGE( "    -h,--help         Display this help message\n" );
667     WINE_MESSAGE( "    -e,--end-session  End the current session cleanly\n" );
668     WINE_MESSAGE( "    -f,--force        Force exit for processes that don't exit cleanly\n" );
669     WINE_MESSAGE( "    -k,--kill         Kill running processes without any cleanup\n" );
670     WINE_MESSAGE( "    -r,--restart      Restart only, don't do normal startup operations\n" );
671     WINE_MESSAGE( "    -s,--shutdown     Shutdown only, don't reboot\n" );
672 }
673
674 static const char short_options[] = "efhkrs";
675
676 static const struct option long_options[] =
677 {
678     { "help",        0, 0, 'h' },
679     { "end-session", 0, 0, 'e' },
680     { "force",       0, 0, 'f' },
681     { "kill",        0, 0, 'k' },
682     { "restart",     0, 0, 'r' },
683     { "shutdown",    0, 0, 's' },
684     { NULL,          0, 0, 0 }
685 };
686
687 int main( int argc, char *argv[] )
688 {
689     extern HANDLE __wine_make_process_system(void);
690     static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
691
692     /* First, set the current directory to SystemRoot */
693     int optc;
694     int end_session = 0, force = 0, kill = 0, restart = 0, shutdown = 0;
695     HANDLE event;
696
697     GetWindowsDirectoryW( windowsdir, MAX_PATH );
698     if( !SetCurrentDirectoryW( windowsdir ) )
699     {
700         WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
701         return 100;
702     }
703
704     while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
705     {
706         switch(optc)
707         {
708         case 'e': end_session = 1; break;
709         case 'f': force = 1; break;
710         case 'k': kill = 1; break;
711         case 'r': restart = 1; break;
712         case 's': shutdown = 1; break;
713         case 'h': usage(); return 0;
714         case '?': usage(); return 1;
715         }
716     }
717
718     if (end_session)
719     {
720         if (!shutdown_close_windows( force )) return 1;
721     }
722
723     if (end_session || kill) kill_processes( shutdown );
724
725     if (shutdown) return 0;
726
727     event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW );
728     ResetEvent( event );  /* in case this is a restart */
729
730     wininit();
731     pendingRename();
732
733     ProcessWindowsFileProtection();
734     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
735     if (!restart)
736     {
737         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
738         start_services();
739     }
740     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
741     if (!restart)
742     {
743         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
744         ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
745         ProcessStartupItems();
746     }
747
748     WINE_TRACE("Operation done\n");
749
750     SetEvent( event );
751
752     /* FIXME: the wait is needed to keep services running */
753     /* it should be removed once we have a proper services.exe */
754     WaitForSingleObject( __wine_make_process_system(), INFINITE );
755     return 0;
756 }