urlmon: Added ibind argument handling in CreateAsyncBindCtx.
[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         if( res==ERROR_FILE_NOT_FOUND )
164         {
165             WINE_TRACE("The key was not found - skipping\n");
166             res=TRUE;
167         }
168         else
169         {
170             WINE_ERR("Couldn't open key, error %d\n", res );
171             res=FALSE;
172         }
173
174         goto end;
175     }
176
177     res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
178                                                              truly a REG_MULTI_SZ anyways */,
179             NULL, &dataLength );
180     if( res==ERROR_FILE_NOT_FOUND )
181     {
182         /* No value - nothing to do. Great! */
183         WINE_TRACE("Value not present - nothing to rename\n");
184         res=TRUE;
185         goto end;
186     }
187
188     if( res!=ERROR_SUCCESS )
189     {
190         WINE_ERR("Couldn't query value's length (%d)\n", res );
191         res=FALSE;
192         goto end;
193     }
194
195     buffer=HeapAlloc( GetProcessHeap(),0,dataLength );
196     if( buffer==NULL )
197     {
198         WINE_ERR("Couldn't allocate %u bytes for the value\n", dataLength );
199         res=FALSE;
200         goto end;
201     }
202
203     res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
204     if( res!=ERROR_SUCCESS )
205     {
206         WINE_ERR("Couldn't query value after successfully querying before (%u),\n"
207                 "please report to wine-devel@winehq.org\n", res);
208         res=FALSE;
209         goto end;
210     }
211
212     /* Make sure that the data is long enough and ends with two NULLs. This
213      * simplifies the code later on.
214      */
215     if( dataLength<2*sizeof(buffer[0]) ||
216             buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
217             buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
218     {
219         WINE_ERR("Improper value format - doesn't end with NULL\n");
220         res=FALSE;
221         goto end;
222     }
223
224     for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
225             src=dst+lstrlenW(dst)+1 )
226     {
227         DWORD dwFlags=0;
228
229         WINE_TRACE("processing next command\n");
230
231         dst=src+lstrlenW(src)+1;
232
233         /* We need to skip the \??\ header */
234         if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
235             src+=4;
236
237         if( dst[0]=='!' )
238         {
239             dwFlags|=MOVEFILE_REPLACE_EXISTING;
240             dst++;
241         }
242
243         if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
244             dst+=4;
245
246         if( *dst!='\0' )
247         {
248             /* Rename the file */
249             MoveFileExW( src, dst, dwFlags );
250         } else
251         {
252             /* Delete the file or directory */
253             if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
254             {
255                 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
256                 {
257                     /* It's a file */
258                     DeleteFileW(src);
259                 } else
260                 {
261                     /* It's a directory */
262                     RemoveDirectoryW(src);
263                 }
264             } else
265             {
266                 WINE_ERR("couldn't get file attributes (%d)\n", GetLastError() );
267             }
268         }
269     }
270
271     if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
272     {
273         WINE_ERR("Error deleting the value (%u)\n", GetLastError() );
274         res=FALSE;
275     } else
276         res=TRUE;
277     
278 end:
279     HeapFree(GetProcessHeap(), 0, buffer);
280
281     if( hSession!=NULL )
282         RegCloseKey( hSession );
283
284     return res;
285 }
286
287 enum runkeys {
288     RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
289 };
290
291 const WCHAR runkeys_names[][30]=
292 {
293     {'R','u','n',0},
294     {'R','u','n','O','n','c','e',0},
295     {'R','u','n','S','e','r','v','i','c','e','s',0},
296     {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
297 };
298
299 #define INVALID_RUNCMD_RETURN -1
300 /*
301  * This function runs the specified command in the specified dir.
302  * [in,out] cmdline - the command line to run. The function may change the passed buffer.
303  * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
304  * [in] wait - whether to wait for the run program to finish before returning.
305  * [in] minimized - Whether to ask the program to run minimized.
306  *
307  * Returns:
308  * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
309  * If wait is FALSE - returns 0 if successful.
310  * If wait is TRUE - returns the program's return value.
311  */
312 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
313 {
314     STARTUPINFOW si;
315     PROCESS_INFORMATION info;
316     DWORD exit_code=0;
317
318     memset(&si, 0, sizeof(si));
319     si.cb=sizeof(si);
320     if( minimized )
321     {
322         si.dwFlags=STARTF_USESHOWWINDOW;
323         si.wShowWindow=SW_MINIMIZE;
324     }
325     memset(&info, 0, sizeof(info));
326
327     if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
328     {
329         WINE_ERR("Failed to run command %s (%d)\n", wine_dbgstr_w(cmdline),
330                  GetLastError() );
331
332         return INVALID_RUNCMD_RETURN;
333     }
334
335     WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
336                wine_dbgstr_w(cmdline), info.hProcess );
337
338     if(wait)
339     {   /* wait for the process to exit */
340         WaitForSingleObject(info.hProcess, INFINITE);
341         GetExitCodeProcess(info.hProcess, &exit_code);
342     }
343
344     CloseHandle( info.hProcess );
345
346     return exit_code;
347 }
348
349 /*
350  * Process a "Run" type registry key.
351  * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
352  *      opened.
353  * szKeyName is the key holding the actual entries.
354  * bDelete tells whether we should delete each value right before executing it.
355  * bSynchronous tells whether we should wait for the prog to complete before
356  *      going on to the next prog.
357  */
358 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
359         BOOL bSynchronous )
360 {
361     static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
362         'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
363         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
364     HKEY hkWin=NULL, hkRun=NULL;
365     DWORD res=ERROR_SUCCESS;
366     DWORD i, nMaxCmdLine=0, nMaxValue=0;
367     WCHAR *szCmdLine=NULL;
368     WCHAR *szValue=NULL;
369
370     if (hkRoot==HKEY_LOCAL_MACHINE)
371         WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
372     else
373         WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
374
375     if( (res=RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ))!=ERROR_SUCCESS )
376     {
377         WINE_ERR("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%d)\n",
378                 res);
379
380         goto end;
381     }
382
383     if( (res=RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ))!=
384             ERROR_SUCCESS)
385     {
386         if( res==ERROR_FILE_NOT_FOUND )
387         {
388             WINE_TRACE("Key doesn't exist - nothing to be done\n");
389
390             res=ERROR_SUCCESS;
391         }
392         else
393             WINE_ERR("RegOpenKey failed on run key (%d)\n", res);
394
395         goto end;
396     }
397     
398     if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
399                     &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
400     {
401         WINE_ERR("Couldn't query key info (%d)\n", res );
402
403         goto end;
404     }
405
406     if( i==0 )
407     {
408         WINE_TRACE("No commands to execute.\n");
409
410         res=ERROR_SUCCESS;
411         goto end;
412     }
413     
414     if( (szCmdLine=HeapAlloc(GetProcessHeap(),0,nMaxCmdLine))==NULL )
415     {
416         WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
417
418         res=ERROR_NOT_ENOUGH_MEMORY;
419         goto end;
420     }
421
422     if( (szValue=HeapAlloc(GetProcessHeap(),0,(++nMaxValue)*sizeof(*szValue)))==NULL )
423     {
424         WINE_ERR("Couldn't allocate memory for the value names\n");
425
426         res=ERROR_NOT_ENOUGH_MEMORY;
427         goto end;
428     }
429     
430     while( i>0 )
431     {
432         DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
433         DWORD type;
434
435         --i;
436
437         if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
438                         (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
439         {
440             WINE_ERR("Couldn't read in value %d - %d\n", i, res );
441
442             continue;
443         }
444
445         if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
446         {
447             WINE_ERR("Couldn't delete value - %d, %d. Running command anyways.\n", i, res );
448         }
449         
450         if( type!=REG_SZ )
451         {
452             WINE_ERR("Incorrect type of value #%d (%d)\n", i, type );
453
454             continue;
455         }
456
457         if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
458         {
459             WINE_ERR("Error running cmd #%d (%d)\n", i, GetLastError() );
460         }
461
462         WINE_TRACE("Done processing cmd #%d\n", i);
463     }
464
465     res=ERROR_SUCCESS;
466
467 end:
468     HeapFree( GetProcessHeap(), 0, szValue );
469     HeapFree( GetProcessHeap(), 0, szCmdLine );
470
471     if( hkRun!=NULL )
472         RegCloseKey( hkRun );
473     if( hkWin!=NULL )
474         RegCloseKey( hkWin );
475
476     WINE_TRACE("done\n");
477
478     return res==ERROR_SUCCESS?TRUE:FALSE;
479 }
480
481 /*
482  * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
483  * of known good dlls and scans through and replaces corrupted DLLs with these
484  * known good versions. The only programs that should install into this dll
485  * cache are Windows Updates and IE (which is treated like a Windows Update)
486  *
487  * Implementing this allows installing ie in win2k mode to actually install the
488  * system dlls that we expect and need
489  */
490 static int ProcessWindowsFileProtection(void)
491 {
492     static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
493                                       'M','i','c','r','o','s','o','f','t','\\',
494                                       'W','i','n','d','o','w','s',' ','N','T','\\',
495                                       'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
496                                       'W','i','n','l','o','g','o','n',0};
497     static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
498     static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
499     static const WCHAR wildcardW[] = {'\\','*',0};
500     WIN32_FIND_DATAW finddata;
501     HANDLE find_handle;
502     BOOL find_rc;
503     DWORD rc;
504     HKEY hkey;
505     LPWSTR dllcache = NULL;
506
507     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
508     {
509         DWORD sz = 0;
510         if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
511         {
512             sz += sizeof(WCHAR);
513             dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
514             RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
515             strcatW( dllcache, wildcardW );
516         }
517     }
518     RegCloseKey(hkey);
519
520     if (!dllcache)
521     {
522         DWORD sz = GetSystemDirectoryW( NULL, 0 );
523         dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
524         GetSystemDirectoryW( dllcache, sz );
525         strcatW( dllcache, dllcacheW );
526     }
527
528     find_handle = FindFirstFileW(dllcache,&finddata);
529     find_rc = find_handle != INVALID_HANDLE_VALUE;
530     while (find_rc)
531     {
532         static const WCHAR dotW[] = {'.',0};
533         static const WCHAR dotdotW[] = {'.','.',0};
534         WCHAR targetpath[MAX_PATH];
535         WCHAR currentpath[MAX_PATH];
536         UINT sz;
537         UINT sz2;
538         WCHAR tempfile[MAX_PATH];
539
540         if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
541         {
542             find_rc = FindNextFileW(find_handle,&finddata);
543             continue;
544         }
545
546         sz = MAX_PATH;
547         sz2 = MAX_PATH;
548         VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
549                      windowsdir, currentpath, &sz, targetpath, &sz2);
550         sz = MAX_PATH;
551         rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
552                              dllcache, targetpath, currentpath, tempfile, &sz);
553         if (rc != ERROR_SUCCESS)
554         {
555             WINE_ERR("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
556             DeleteFileW(tempfile);
557         }
558         find_rc = FindNextFileW(find_handle,&finddata);
559     }
560     FindClose(find_handle);
561     HeapFree(GetProcessHeap(),0,dllcache);
562     return 1;
563 }
564
565 /* start services */
566 static void start_services(void)
567 {
568     static const WCHAR servicesW[] = {'S','y','s','t','e','m','\\',
569                                       'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
570                                       'S','e','r','v','i','c','e','s',0};
571     static const WCHAR startW[] = {'S','t','a','r','t',0};
572     HKEY hkey, skey;
573     DWORD type, size, start, index = 0;
574     WCHAR name[MAX_PATH];
575     SC_HANDLE manager;
576
577     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, servicesW, &hkey )) return;
578
579     if (!(manager = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS )))
580     {
581         RegCloseKey( hkey );
582         return;
583     }
584
585     while (!RegEnumKeyW( hkey, index++, name, sizeof(name) ))
586     {
587         if (RegOpenKeyW( hkey, name, &skey )) continue;
588         size = sizeof(start);
589         if (!RegQueryValueExW( skey, startW, NULL, &type, (LPBYTE)&start, &size ) && type == REG_DWORD)
590         {
591             if (start == SERVICE_BOOT_START ||
592                 start == SERVICE_SYSTEM_START ||
593                 start == SERVICE_AUTO_START)
594             {
595                 SC_HANDLE handle = OpenServiceW( manager, name, SERVICE_ALL_ACCESS );
596                 if (handle)
597                 {
598                     WINE_TRACE( "starting service %s start %u\n", wine_dbgstr_w(name), start );
599                     StartServiceW( handle, 0, NULL );
600                     CloseServiceHandle( handle );
601                 }
602             }
603         }
604         RegCloseKey( skey );
605     }
606     CloseServiceHandle( manager );
607     RegCloseKey( hkey );
608 }
609
610 /* Process items in the StartUp group of the user's Programs under the Start Menu. Some installers put
611  * shell links here to restart themselves after boot. */
612 static BOOL ProcessStartupItems(void)
613 {
614     BOOL ret = FALSE;
615     HRESULT hr;
616     int iRet;
617     IMalloc *ppM = NULL;
618     IShellFolder *psfDesktop = NULL, *psfStartup = NULL;
619     LPITEMIDLIST pidlStartup = NULL, pidlItem;
620     ULONG NumPIDLs;
621     IEnumIDList *iEnumList = NULL;
622     STRRET strret;
623     WCHAR wszCommand[MAX_PATH];
624
625     WINE_TRACE("Processing items in the StartUp folder.\n");
626
627     hr = SHGetMalloc(&ppM);
628     if (FAILED(hr))
629     {
630         WINE_ERR("Couldn't get IMalloc object.\n");
631         goto done;
632     }
633
634     hr = SHGetDesktopFolder(&psfDesktop);
635     if (FAILED(hr))
636     {
637         WINE_ERR("Couldn't get desktop folder.\n");
638         goto done;
639     }
640
641     hr = SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidlStartup);
642     if (FAILED(hr))
643     {
644         WINE_TRACE("Couldn't get StartUp folder location.\n");
645         goto done;
646     }
647
648     hr = IShellFolder_BindToObject(psfDesktop, pidlStartup, NULL, &IID_IShellFolder, (LPVOID*)&psfStartup);
649     if (FAILED(hr))
650     {
651         WINE_TRACE("Couldn't bind IShellFolder to StartUp folder.\n");
652         goto done;
653     }
654
655     hr = IShellFolder_EnumObjects(psfStartup, NULL, SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &iEnumList);
656     if (FAILED(hr))
657     {
658         WINE_TRACE("Unable to enumerate StartUp objects.\n");
659         goto done;
660     }
661
662     while (IEnumIDList_Next(iEnumList, 1, &pidlItem, &NumPIDLs) == S_OK &&
663            (NumPIDLs) == 1)
664     {
665         hr = IShellFolder_GetDisplayNameOf(psfStartup, pidlItem, SHGDN_FORPARSING, &strret);
666         if (FAILED(hr))
667             WINE_TRACE("Unable to get display name of enumeration item.\n");
668         else
669         {
670             hr = StrRetToBufW(&strret, pidlItem, wszCommand, MAX_PATH);
671             if (FAILED(hr))
672                 WINE_TRACE("Unable to parse display name.\n");
673             else
674                 if ((iRet = (int)ShellExecuteW(NULL, NULL, wszCommand, NULL, NULL, SW_SHOWNORMAL)) <= 32)
675                     WINE_ERR("Error %d executing command %s.\n", iRet, wine_dbgstr_w(wszCommand));
676         }
677
678         IMalloc_Free(ppM, pidlItem);
679     }
680
681     /* Return success */
682     ret = TRUE;
683
684 done:
685     if (iEnumList) IEnumIDList_Release(iEnumList);
686     if (psfStartup) IShellFolder_Release(psfStartup);
687     if (pidlStartup) IMalloc_Free(ppM, pidlStartup);
688
689     return ret;
690 }
691
692 static void usage(void)
693 {
694     WINE_MESSAGE( "Usage: wineboot [options]\n" );
695     WINE_MESSAGE( "Options;\n" );
696     WINE_MESSAGE( "    -h,--help         Display this help message\n" );
697     WINE_MESSAGE( "    -e,--end-session  End the current session cleanly\n" );
698     WINE_MESSAGE( "    -f,--force        Force exit for processes that don't exit cleanly\n" );
699     WINE_MESSAGE( "    -k,--kill         Kill running processes without any cleanup\n" );
700     WINE_MESSAGE( "    -r,--restart      Restart only, don't do normal startup operations\n" );
701     WINE_MESSAGE( "    -s,--shutdown     Shutdown only, don't reboot\n" );
702 }
703
704 static const char short_options[] = "efhkrs";
705
706 static const struct option long_options[] =
707 {
708     { "help",        0, 0, 'h' },
709     { "end-session", 0, 0, 'e' },
710     { "force",       0, 0, 'f' },
711     { "kill",        0, 0, 'k' },
712     { "restart",     0, 0, 'r' },
713     { "shutdown",    0, 0, 's' },
714     { NULL,          0, 0, 0 }
715 };
716
717 int main( int argc, char *argv[] )
718 {
719     /* First, set the current directory to SystemRoot */
720     int optc;
721     int end_session = 0, force = 0, kill = 0, restart = 0, shutdown = 0;
722
723     GetWindowsDirectoryW( windowsdir, MAX_PATH );
724     if( !SetCurrentDirectoryW( windowsdir ) )
725     {
726         WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );
727         return 100;
728     }
729
730     while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
731     {
732         switch(optc)
733         {
734         case 'e': end_session = 1; break;
735         case 'f': force = 1; break;
736         case 'k': kill = 1; break;
737         case 'r': restart = 1; break;
738         case 's': shutdown = 1; break;
739         case 'h': usage(); return 0;
740         case '?': usage(); return 1;
741         }
742     }
743
744     if (end_session)
745     {
746         if (!shutdown_close_windows( force )) return 1;
747     }
748
749     if (end_session || kill) kill_processes( shutdown );
750
751     if (shutdown) return 0;
752
753     wininit();
754     pendingRename();
755
756     ProcessWindowsFileProtection();
757     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE );
758     if (!restart)
759     {
760         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE );
761         start_services();
762     }
763     ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE );
764     if (!restart)
765     {
766         ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
767         ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE );
768         ProcessStartupItems();
769     }
770
771     WINE_TRACE("Operation done\n");
772     return 0;
773 }