wineboot: Start items in StartUp folder on boot.
[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. Theses are roughly devided 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, ?semi-synchronous?, not implemented yet)
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/debug.h>
65
66 #define COBJMACROS
67 #include <shlobj.h>
68 #include <shobjidl.h>
69 #include <shlwapi.h>
70 #include <shellapi.h>
71
72 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
73
74 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
75
76 extern BOOL shutdown_close_windows( BOOL force );
77 extern void kill_processes( BOOL kill_desktop );
78
79 static BOOL GetLine( HANDLE hFile, char *buf, size_t buflen )
80 {
81     unsigned int i=0;
82     DWORD r;
83     buf[0]='\0';
84
85     do
86     {
87         DWORD read;
88         if( !ReadFile( hFile, buf, 1, &read, NULL ) || read!=1 )
89         {
90             return FALSE;
91         }
92
93     } while( isspace( *buf ) );
94
95     while( buf[i]!='\n' && i<=buflen &&
96             ReadFile( hFile, buf+i+1, 1, &r, NULL ) )
97     {
98         ++i;
99     }
100
101
102     if( buf[i]!='\n' )
103     {
104         return FALSE;
105     }
106
107     if( i>0 && buf[i-1]=='\r' )
108         --i;
109
110     buf[i]='\0';
111
112     return TRUE;
113 }
114
115 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
116  * Returns FALSE if there was an error, or otherwise if all is ok.
117  */
118 static BOOL wininit(void)
119 {
120     const char * const RENAME_FILE="wininit.ini";
121     const char * const RENAME_FILE_TO="wininit.bak";
122     const char * const RENAME_FILE_SECTION="[rename]";
123     char buffer[MAX_LINE_LENGTH];
124     HANDLE hFile;
125
126
127     hFile=CreateFileA(RENAME_FILE, GENERIC_READ,
128                     FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
129                     NULL );
130     
131     if( hFile==INVALID_HANDLE_VALUE )
132     {
133         DWORD err=GetLastError();
134         
135         if( err==ERROR_FILE_NOT_FOUND )
136         {
137             /* No file - nothing to do. Great! */
138             WINE_TRACE("Wininit.ini not present - no renaming to do\n");
139
140             return TRUE;
141         }
142
143         WINE_ERR("There was an error in reading wininit.ini file - %d\n",
144                 GetLastError() );
145
146         return FALSE;
147     }
148
149     printf("Wine is finalizing your software installation. This may take a few minutes,\n");
150     printf("though it never actually does.\n");
151
152     while( GetLine( hFile, buffer, sizeof(buffer) ) &&
153             lstrcmpiA(buffer,RENAME_FILE_SECTION)!=0  )
154         ; /* Read the lines until we match the rename section */
155
156     while( GetLine( hFile, buffer, sizeof(buffer) ) && buffer[0]!='[' )
157     {
158         /* First, make sure this is not a comment */
159         if( buffer[0]!=';' && buffer[0]!='\0' )
160         {
161             char * value;
162
163             value=strchr(buffer, '=');
164
165             if( value==NULL )
166             {
167                 WINE_WARN("Line with no \"=\" in it in wininit.ini - %s\n",
168                         buffer);
169             } else
170             {
171                 /* split the line into key and value */
172                 *(value++)='\0';
173
174                 if( lstrcmpiA( "NUL", buffer )==0 )
175                 {
176                     WINE_TRACE("Deleting file \"%s\"\n", value );
177                     /* A file to delete */
178                     if( !DeleteFileA( value ) )
179                         WINE_WARN("Error deleting file \"%s\"\n", value);
180                 } else
181                 {
182                     WINE_TRACE("Renaming file \"%s\" to \"%s\"\n", value,
183                             buffer );
184
185                     if( !MoveFileExA(value, buffer, MOVEFILE_COPY_ALLOWED|
186                             MOVEFILE_REPLACE_EXISTING) )
187                     {
188                         WINE_WARN("Error renaming \"%s\" to \"%s\"\n", value,
189                                 buffer );
190                     }
191                 }
192             }
193         }
194     }
195
196     CloseHandle( hFile );
197
198     if( !MoveFileExA( RENAME_FILE, RENAME_FILE_TO, MOVEFILE_REPLACE_EXISTING) )
199     {
200         WINE_ERR("Couldn't rename wininit.ini, error %d\n", GetLastError() );
201
202         return FALSE;
203     }
204
205     return TRUE;
206 }
207
208 static BOOL pendingRename(void)
209 {
210     static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
211                                       'F','i','l','e','R','e','n','a','m','e',
212                                       'O','p','e','r','a','t','i','o','n','s',0};
213     static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
214                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
215                                      'C','o','n','t','r','o','l','\\',
216                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
217     WCHAR *buffer=NULL;
218     const WCHAR *src=NULL, *dst=NULL;
219     DWORD dataLength=0;
220     HKEY hSession=NULL;
221     DWORD res;
222
223     WINE_TRACE("Entered\n");
224
225     if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
226             !=ERROR_SUCCESS )
227     {
228         if( res==ERROR_FILE_NOT_FOUND )
229         {
230             WINE_TRACE("The key was not found - skipping\n");
231             res=TRUE;
232         }
233         else
234         {
235             WINE_ERR("Couldn't open key, error %d\n", res );
236             res=FALSE;
237         }
238
239         goto end;
240     }
241
242     res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
243                                                              truly a REG_MULTI_SZ anyways */,
244             NULL, &dataLength );
245     if( res==ERROR_FILE_NOT_FOUND )
246     {
247         /* No value - nothing to do. Great! */
248         WINE_TRACE("Value not present - nothing to rename\n");
249         res=TRUE;
250         goto end;
251     }
252
253     if( res!=ERROR_SUCCESS )
254     {
255         WINE_ERR("Couldn't query value's length (%d)\n", res );
256         res=FALSE;
257         goto end;
258     }
259
260     buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
261     if( buffer==NULL )
262     {
263         WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
264         res=FALSE;
265         goto end;
266     }
267
268     res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
269     if( res!=ERROR_SUCCESS )
270     {
271         WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
272                 "please report to wine-devel@winehq.org\n", res);
273         res=FALSE;
274         goto end;
275     }
276
277     /* Make sure that the data is long enough and ends with two NULLs. This
278      * simplifies the code later on.
279      */
280     if( dataLength<2*sizeof(buffer[0]) ||
281             buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
282             buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
283     {
284         WINE_ERR("Improper value format - doesn't end with NULL\n");
285         res=FALSE;
286         goto end;
287     }
288
289     for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
290             src=dst+lstrlenW(dst)+1 )
291     {
292         DWORD dwFlags=0;
293
294         WINE_TRACE("processing next command\n");
295
296         dst=src+lstrlenW(src)+1;
297
298         /* We need to skip the \??\ header */
299         if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
300             src+=4;
301
302         if( dst[0]=='!' )
303         {
304             dwFlags|=MOVEFILE_REPLACE_EXISTING;
305             dst++;
306         }
307
308         if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
309             dst+=4;
310
311         if( *dst!='\0' )
312         {
313             /* Rename the file */
314             MoveFileExW( src, dst, dwFlags );
315         } else
316         {
317             /* Delete the file or directory */
318             if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
319             {
320                 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
321                 {
322                     /* It's a file */
323                     DeleteFileW(src);
324                 } else
325                 {
326                     /* It's a directory */
327                     RemoveDirectoryW(src);
328                 }
329             } else
330             {
331                 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
332             }
333         }
334     }
335
336     if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
337     {
338         WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
339         res=FALSE;
340     } else
341         res=TRUE;
342     
343 end:
344     HeapFree(GetProcessHeap(), 0, buffer);
345
346     if( hSession!=NULL )
347         RegCloseKey( hSession );
348
349     return res;
350 }
351
352 enum runkeys {
353     RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
354 };
355
356 const WCHAR runkeys_names[][30]=
357 {
358     {'R','u','n',0},
359     {'R','u','n','O','n','c','e',0},
360     {'R','u','n','S','e','r','v','i','c','e','s',0},
361     {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
362 };
363
364 #define INVALID_RUNCMD_RETURN -1
365 /*
366  * This function runs the specified command in the specified dir.
367  * [in,out] cmdline - the command line to run. The function may change the passed buffer.
368  * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
369  * [in] wait - whether to wait for the run program to finish before returning.
370  * [in] minimized - Whether to ask the program to run minimized.
371  *
372  * Returns:
373  * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
374  * If wait is FALSE - returns 0 if successful.
375  * If wait is TRUE - returns the program's return value.
376  */
377 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
378 {
379     STARTUPINFOW si;
380     PROCESS_INFORMATION info;
381     DWORD exit_code=0;
382
383     memset(&si, 0, sizeof(si));
384     si.cb=sizeof(si);
385     if( minimized )
386     {
387         si.dwFlags=STARTF_USESHOWWINDOW;
388         si.wShowWindow=SW_MINIMIZE;
389     }
390     memset(&info, 0, sizeof(info));
391
392     if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
393     {
394         WINE_ERR("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline),
395                  GetLastError() );
396
397         return INVALID_RUNCMD_RETURN;
398     }
399
400     WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
401                wine_dbgstr_w(cmdline), info.hProcess );
402
403     if(wait)
404     {   /* wait for the process to exit */
405         WaitForSingleObject(info.hProcess, INFINITE);
406         GetExitCodeProcess(info.hProcess, &exit_code);
407     }
408
409     CloseHandle( info.hProcess );
410
411     return exit_code;
412 }
413
414 /*
415  * Process a "Run" type registry key.
416  * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
417  *      opened.
418  * szKeyName is the key holding the actual entries.
419  * bDelete tells whether we should delete each value right before executing it.
420  * bSynchronous tells whether we should wait for the prog to complete before
421  *      going on to the next prog.
422  */
423 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
424         BOOL bSynchronous )
425 {
426     static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
427         'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
428         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
429     HKEY hkWin=NULL, hkRun=NULL;
430     DWORD res=ERROR_SUCCESS;
431     DWORD i, nMaxCmdLine=0, nMaxValue=0;
432     WCHAR *szCmdLine=NULL;
433     WCHAR *szValue=NULL;
434
435     if (hkRoot==HKEY_LOCAL_MACHINE)
436         WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
437     else
438         WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
439
440     if( (res=RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ))!=ERROR_SUCCESS )
441     {
442         WINE_ERR("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%d)\n",
443                 res);
444
445         goto end;
446     }
447
448     if( (res=RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ))!=
449             ERROR_SUCCESS)
450     {
451         if( res==ERROR_FILE_NOT_FOUND )
452         {
453             WINE_TRACE("Key doesn't exist - nothing to be done\n");
454
455             res=ERROR_SUCCESS;
456         }
457         else
458             WINE_ERR("RegOpenKey failed on run key (%d)\n", res);
459
460         goto end;
461     }
462     
463     if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
464                     &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
465     {
466         WINE_ERR("Couldn't query key info (%d)\n", res );
467
468         goto end;
469     }
470
471     if( i==0 )
472     {
473         WINE_TRACE("No commands to execute.\n");
474
475         res=ERROR_SUCCESS;
476         goto end;
477     }
478     
479     if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
480     {
481         WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
482
483         res=ERROR_NOT_ENOUGH_MEMORY;
484         goto end;
485     }
486
487     if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
488     {
489         WINE_ERR("Couldn't allocate memory for the value names\n");
490
491         res=ERROR_NOT_ENOUGH_MEMORY;
492         goto end;
493     }
494     
495     while( i>0 )
496     {
497         DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
498         DWORD type;
499
500         --i;
501
502         if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
503                         (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
504         {
505             WINE_ERR("Couldn't read in value %d - %d\n", i, res );
506
507             continue;
508         }
509
510         if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
511         {
512             WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
513         }
514         
515         if( type!=REG_SZ )
516         {
517             WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
518
519             continue;
520         }
521
522         if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
523         {
524             WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
525         }
526
527         WINE_TRACE("Done processing cmd #%d\n", i);
528     }
529
530     res=ERROR_SUCCESS;
531
532 end:
533     if( hkRun!=NULL )
534         RegCloseKey( hkRun );
535     if( hkWin!=NULL )
536         RegCloseKey( hkWin );
537
538     WINE_TRACE("done\n");
539
540     return res==ERROR_SUCCESS?TRUE:FALSE;
541 }
542
543 /*
544  * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
545  * of known good dlls and scans through and replaces corrupted DLLs with these
546  * known good versions. The only programs that should install into this dll
547  * cache are Windows Updates and IE (which is treated like a Windows Update)
548  *
549  * Implementing this allows installing ie in win2k mode to actaully install the
550  * system dlls that we expect and need
551  */
552 static int ProcessWindowsFileProtection(void)
553 {
554     WIN32_FIND_DATA finddata;
555     LPSTR custom_dllcache = NULL;
556     static CHAR default_dllcache[] = "C:\\Windows\\System32\\dllcache";
557     HANDLE find_handle;
558     BOOL find_rc;
559     DWORD rc;
560     HKEY hkey;
561     LPSTR dllcache;
562     CHAR find_string[MAX_PATH];
563     CHAR windowsdir[MAX_PATH];
564
565     rc = RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", &hkey );
566     if (rc == ERROR_SUCCESS)
567     {
568         DWORD sz = 0;
569         rc = RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, NULL, &sz);
570         if (rc == ERROR_MORE_DATA)
571         {
572             sz++;
573             custom_dllcache = HeapAlloc(GetProcessHeap(),0,sz);
574             RegQueryValueEx( hkey, "SFCDllCacheDir", 0, NULL, (LPBYTE)custom_dllcache, &sz);
575         }
576     }
577     RegCloseKey(hkey);
578
579     if (custom_dllcache)
580         dllcache = custom_dllcache;
581     else
582         dllcache = default_dllcache;
583
584     strcpy(find_string,dllcache);
585     strcat(find_string,"\\*.*");
586
587     GetWindowsDirectory(windowsdir,MAX_PATH);
588
589     find_handle = FindFirstFile(find_string,&finddata);
590     find_rc = find_handle != INVALID_HANDLE_VALUE;
591     while (find_rc)
592     {
593         CHAR targetpath[MAX_PATH];
594         CHAR currentpath[MAX_PATH];
595         UINT sz;
596         UINT sz2;
597         CHAR tempfile[MAX_PATH];
598
599         if (strcmp(finddata.cFileName,".") == 0 ||
600             strcmp(finddata.cFileName,"..") == 0)
601         {
602             find_rc = FindNextFile(find_handle,&finddata);
603             continue;
604         }
605
606         sz = MAX_PATH;
607         sz2 = MAX_PATH;
608         VerFindFile(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir, 
609                 windowsdir, currentpath, &sz, targetpath,&sz2);
610         sz = MAX_PATH;
611         rc = VerInstallFile(0, finddata.cFileName, finddata.cFileName,
612                             dllcache, targetpath, currentpath, tempfile,&sz);
613         if (rc != ERROR_SUCCESS)
614         {
615             WINE_ERR("WFP: %s error 0x%x\n",finddata.cFileName,rc);
616             DeleteFile(tempfile);
617         }
618         find_rc = FindNextFile(find_handle,&finddata);
619     }
620     FindClose(find_handle);
621     HeapFree(GetProcessHeap(),0,custom_dllcache);
622     return 1;
623 }
624
625 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
626  * shell links here to restart themselves after boot. */
627 static BOOL ProcessStartupItems(void)
628 {
629     BOOL ret = FALSE;
630     HRESULT hr;
631     int iRet;
632     IMalloc *ppM = NULL;
633     IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
634     LPITEMIDLIST pidlStartup = NULL, pidlItem;
635     ULONG NumPIDLs;
636     IEnumIDList *iEnumList = NULL;
637     STRRET strret;
638     WCHAR wszCommand[MAX_PATH];
639
640     WINE_TRACE("Processing items in the StartUp folder.\n");
641
642     hr = SHGetMalloc(&ppM);
643     if (FAILED(hr))
644     {
645         WINE_ERR("Couldn't get IMalloc object.\n");
646         goto done;
647     }
648
649     hr = SHGetDesktopFolder(&psfDesktop);
650     if (FAILED(hr))
651     {
652         WINE_ERR("Couldn't get desktop folder.\n");
653         goto done;
654     }
655
656     hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
657     if (FAILED(hr))
658     {
659         WINE_TRACE("Couldn't get StartUp folder location.\n");
660         goto done;
661     }
662
663     hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
664     if (FAILED(hr))
665     {
666         WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
667         goto done;
668     }
669
670     hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
671     if (FAILED(hr))
672     {
673         WINE_TRACE("Unable to enumerate StartUp objects.\n");
674         goto done;
675     }
676
677     while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
678            (NumPIDLs) == 1)
679     {
680         hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
681         if (FAILED(hr))
682             WINE_TRACE("Unable to get display name of enumeration item.\n");
683         else
684         {
685             hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
686             if (FAILED(hr))
687                 WINE_TRACE("Unable to parse display name.\n");
688             else
689                 if ((iRet = (int)ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL)) <= 32)
690                     WINE_ERR("Error %d executing command %s.\n", iRet, wine_dbgstr_w(wszCommand));
691         }
692
693         IMalloc_Free(ppM, pidlItem);
694     }
695
696     /* Return success */
697     ret = TRUE;
698
699 done:
700     if (iEnumList) IEnumIDList_Release(iEnumList);
701     if (psfStartup) IShellFolder_Release(psfStartup);
702     if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
703
704     return ret;
705 }
706
707 static void usage(void)
708 {
709     WINE_MESSAGE( "Usage: wineboot [options]\n" );
710     WINE_MESSAGE( "Options;\n" );
711     WINE_MESSAGE( "    -h,--help         Display this help message\n" );
712     WINE_MESSAGE( "    -e,--end-session  End the current session cleanly\n" );
713     WINE_MESSAGE( "    -f,--force        Force exit for processes that don't exit cleanly\n" );
714     WINE_MESSAGE( "    -k,--kill         Kill running processes without any cleanup\n" );
715     WINE_MESSAGE( "    -r,--restart      Restart only, don't do normal startup operations\n" );
716     WINE_MESSAGE( "    -s,--shutdown     Shutdown only, don't reboot\n" );
717 }
718
719 static const char short_options[] = "efhkrs";
720
721 static const struct option long_options[] =
722 {
723     { "help",        0, 0, 'h' },
724     { "end-session", 0, 0, 'e' },
725     { "force",       0, 0, 'f' },
726     { "kill",        0, 0, 'k' },
727     { "restart",     0, 0, 'r' },
728     { "shutdown",    0, 0, 's' },
729     { NULL,          0, 0, 0 }
730 };
731
732 struct op_mask {
733     BOOL w9xonly; /* Perform only operations done on Windows 9x */
734     BOOL ntonly; /* Perform only operations done on Windows NT */
735     BOOL startup; /* Perform the operations that are performed every boot */
736     BOOL preboot; /* Perform file renames typically done before the system starts */
737     BOOL prelogin; /* Perform the operations typically done before the user logs in */
738     BOOL postlogin; /* Operations done after login */
739 };
740
741 static const struct op_mask SESSION_START={FALSE, FALSE, TRUE, TRUE, TRUE, TRUE},
742     SETUP={FALSE, FALSE, FALSE, TRUE, TRUE, TRUE};
743
744 int main( int argc, char *argv[] )
745 {
746     struct op_mask ops = SESSION_START; /* Which of the ops do we want to perform? */
747     /* First, set the current directory to SystemRoot */
748     TCHAR gen_path[MAX_PATH];
749     DWORD res;
750     int optc;
751     int end_session = 0, force = 0, kill = 0, restart = 0, shutdown = 0;
752
753     res=GetWindowsDirectory( gen_path, sizeof(gen_path) );
754     
755     if( res==0 )
756     {
757         WINE_ERR("Couldn't get the windows directory - error %d\n",
758                 GetLastError() );
759
760         return 100;
761     }
762
763     if( res>=sizeof(gen_path) )
764     {
765         WINE_ERR("Windows path too long (%d)\n", res );
766
767         return 100;
768     }
769
770     if( !SetCurrentDirectory( gen_path ) )
771     {
772         WINE_ERR("Cannot set the dir to %s (%d)\n", gen_path, GetLastError() );
773
774         return 100;
775     }
776
777
778     while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
779     {
780         switch(optc)
781         {
782         case 'e': end_session = 1; break;
783         case 'f': force = 1; break;
784         case 'k': kill = 1; break;
785         case 'r': restart = 1; break;
786         case 's': shutdown = 1; break;
787         case 'h': usage(); return 0;
788         case '?': usage(); return 1;
789         }
790     }
791
792     if (end_session)
793     {
794         if (!shutdown_close_windows( force )) return 1;
795     }
796
797     if (end_session || kill) kill_processes( shutdown );
798
799     if (shutdown) return 0;
800
801     if (restart) ops = SETUP;
802
803     /* Perform the ops by order, stopping if one fails, skipping if necessary */
804     /* Shachar: Sorry for the perl syntax */
805     res=(ops.ntonly || !ops.preboot || wininit())&&
806         (ops.w9xonly || !ops.preboot || pendingRename()) &&
807         (ops.ntonly || !ops.prelogin ||
808          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE],
809                 TRUE, FALSE )) &&
810         (ops.ntonly || !ops.prelogin ||
811          ProcessWindowsFileProtection()) &&
812         (ops.ntonly || !ops.prelogin || !ops.startup ||
813          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES],
814                 FALSE, FALSE )) &&
815         (!ops.postlogin ||
816          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE],
817                 TRUE, TRUE )) &&
818         (!ops.postlogin || !ops.startup ||
819          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN],
820                 FALSE, FALSE )) &&
821         (!ops.postlogin || !ops.startup ||
822          ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN],
823                 FALSE, FALSE )) &&
824         (!ops.postlogin || !ops.startup ||
825          ProcessStartupItems( ));
826
827     WINE_TRACE("Operation done\n");
828
829     return res?0:101;
830 }