ntdll: Translate signal to trap when trap code is 0 on ARM.
[wine.git] / dlls / kernel32 / profile.c
blob027693e5dae9c504cdce263b0494ad83f9eab634
1 /*
2 * Profile functions
4 * Copyright 1993 Miguel de Icaza
5 * Copyright 1996 Alexandre Julliard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <string.h>
26 #include <stdarg.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winnls.h"
31 #include "winerror.h"
32 #include "winternl.h"
33 #include "wine/unicode.h"
34 #include "wine/library.h"
35 #include "wine/debug.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(profile);
39 static const char bom_utf8[] = {0xEF,0xBB,0xBF};
41 typedef enum
43 ENCODING_ANSI = 1,
44 ENCODING_UTF8,
45 ENCODING_UTF16LE,
46 ENCODING_UTF16BE
47 } ENCODING;
49 typedef struct tagPROFILEKEY
51 WCHAR *value;
52 struct tagPROFILEKEY *next;
53 WCHAR name[1];
54 } PROFILEKEY;
56 typedef struct tagPROFILESECTION
58 struct tagPROFILEKEY *key;
59 struct tagPROFILESECTION *next;
60 WCHAR name[1];
61 } PROFILESECTION;
64 typedef struct
66 BOOL changed;
67 PROFILESECTION *section;
68 WCHAR *filename;
69 FILETIME LastWriteTime;
70 ENCODING encoding;
71 } PROFILE;
74 #define N_CACHED_PROFILES 10
76 /* Cached profile files */
77 static PROFILE *MRUProfile[N_CACHED_PROFILES]={NULL};
79 #define CurProfile (MRUProfile[0])
81 /* Check for comments in profile */
82 #define IS_ENTRY_COMMENT(str) ((str)[0] == ';')
84 static const WCHAR emptystringW[] = {0};
85 static const WCHAR wininiW[] = { 'w','i','n','.','i','n','i',0 };
87 static CRITICAL_SECTION PROFILE_CritSect;
88 static CRITICAL_SECTION_DEBUG critsect_debug =
90 0, 0, &PROFILE_CritSect,
91 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
92 0, 0, { (DWORD_PTR)(__FILE__ ": PROFILE_CritSect") }
94 static CRITICAL_SECTION PROFILE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
96 static const char hex[16] = "0123456789ABCDEF";
98 /***********************************************************************
99 * PROFILE_CopyEntry
101 * Copy the content of an entry into a buffer, removing quotes, and possibly
102 * translating environment variables.
104 static void PROFILE_CopyEntry( LPWSTR buffer, LPCWSTR value, int len,
105 BOOL strip_quote )
107 WCHAR quote = '\0';
109 if(!buffer) return;
111 if (strip_quote && ((*value == '\'') || (*value == '\"')))
113 if (value[1] && (value[strlenW(value)-1] == *value)) quote = *value++;
116 lstrcpynW( buffer, value, len );
117 if (quote && (len >= lstrlenW(value))) buffer[strlenW(buffer)-1] = '\0';
120 /* byte-swaps shorts in-place in a buffer. len is in WCHARs */
121 static inline void PROFILE_ByteSwapShortBuffer(WCHAR * buffer, int len)
123 int i;
124 USHORT * shortbuffer = buffer;
125 for (i = 0; i < len; i++)
126 shortbuffer[i] = RtlUshortByteSwap(shortbuffer[i]);
129 /* writes any necessary encoding marker to the file */
130 static inline void PROFILE_WriteMarker(HANDLE hFile, ENCODING encoding)
132 DWORD dwBytesWritten;
133 WCHAR bom;
134 switch (encoding)
136 case ENCODING_ANSI:
137 break;
138 case ENCODING_UTF8:
139 WriteFile(hFile, bom_utf8, sizeof(bom_utf8), &dwBytesWritten, NULL);
140 break;
141 case ENCODING_UTF16LE:
142 bom = 0xFEFF;
143 WriteFile(hFile, &bom, sizeof(bom), &dwBytesWritten, NULL);
144 break;
145 case ENCODING_UTF16BE:
146 bom = 0xFFFE;
147 WriteFile(hFile, &bom, sizeof(bom), &dwBytesWritten, NULL);
148 break;
152 static void PROFILE_WriteLine( HANDLE hFile, WCHAR * szLine, int len, ENCODING encoding)
154 char * write_buffer;
155 int write_buffer_len;
156 DWORD dwBytesWritten;
158 TRACE("writing: %s\n", debugstr_wn(szLine, len));
160 switch (encoding)
162 case ENCODING_ANSI:
163 write_buffer_len = WideCharToMultiByte(CP_ACP, 0, szLine, len, NULL, 0, NULL, NULL);
164 write_buffer = HeapAlloc(GetProcessHeap(), 0, write_buffer_len);
165 if (!write_buffer) return;
166 len = WideCharToMultiByte(CP_ACP, 0, szLine, len, write_buffer, write_buffer_len, NULL, NULL);
167 WriteFile(hFile, write_buffer, len, &dwBytesWritten, NULL);
168 HeapFree(GetProcessHeap(), 0, write_buffer);
169 break;
170 case ENCODING_UTF8:
171 write_buffer_len = WideCharToMultiByte(CP_UTF8, 0, szLine, len, NULL, 0, NULL, NULL);
172 write_buffer = HeapAlloc(GetProcessHeap(), 0, write_buffer_len);
173 if (!write_buffer) return;
174 len = WideCharToMultiByte(CP_UTF8, 0, szLine, len, write_buffer, write_buffer_len, NULL, NULL);
175 WriteFile(hFile, write_buffer, len, &dwBytesWritten, NULL);
176 HeapFree(GetProcessHeap(), 0, write_buffer);
177 break;
178 case ENCODING_UTF16LE:
179 WriteFile(hFile, szLine, len * sizeof(WCHAR), &dwBytesWritten, NULL);
180 break;
181 case ENCODING_UTF16BE:
182 PROFILE_ByteSwapShortBuffer(szLine, len);
183 WriteFile(hFile, szLine, len * sizeof(WCHAR), &dwBytesWritten, NULL);
184 break;
185 default:
186 FIXME("encoding type %d not implemented\n", encoding);
190 /***********************************************************************
191 * PROFILE_Save
193 * Save a profile tree to a file.
195 static void PROFILE_Save( HANDLE hFile, const PROFILESECTION *section, ENCODING encoding )
197 PROFILEKEY *key;
198 WCHAR *buffer, *p;
200 PROFILE_WriteMarker(hFile, encoding);
202 for ( ; section; section = section->next)
204 int len = 0;
206 if (section->name[0]) len += strlenW(section->name) + 4;
208 for (key = section->key; key; key = key->next)
210 len += strlenW(key->name) + 2;
211 if (key->value) len += strlenW(key->value) + 1;
214 buffer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
215 if (!buffer) return;
217 p = buffer;
218 if (section->name[0])
220 *p++ = '[';
221 strcpyW( p, section->name );
222 p += strlenW(p);
223 *p++ = ']';
224 *p++ = '\r';
225 *p++ = '\n';
228 for (key = section->key; key; key = key->next)
230 strcpyW( p, key->name );
231 p += strlenW(p);
232 if (key->value)
234 *p++ = '=';
235 strcpyW( p, key->value );
236 p += strlenW(p);
238 *p++ = '\r';
239 *p++ = '\n';
241 PROFILE_WriteLine( hFile, buffer, len, encoding );
242 HeapFree(GetProcessHeap(), 0, buffer);
247 /***********************************************************************
248 * PROFILE_Free
250 * Free a profile tree.
252 static void PROFILE_Free( PROFILESECTION *section )
254 PROFILESECTION *next_section;
255 PROFILEKEY *key, *next_key;
257 for ( ; section; section = next_section)
259 for (key = section->key; key; key = next_key)
261 next_key = key->next;
262 HeapFree( GetProcessHeap(), 0, key->value );
263 HeapFree( GetProcessHeap(), 0, key );
265 next_section = section->next;
266 HeapFree( GetProcessHeap(), 0, section );
270 /* returns TRUE if a whitespace character, else FALSE */
271 static inline BOOL PROFILE_isspaceW(WCHAR c)
273 /* ^Z (DOS EOF) is a space too (found on CD-ROMs) */
274 return isspaceW(c) || c == 0x1a;
277 static inline ENCODING PROFILE_DetectTextEncoding(const void * buffer, int * len)
279 int flags = IS_TEXT_UNICODE_SIGNATURE |
280 IS_TEXT_UNICODE_REVERSE_SIGNATURE |
281 IS_TEXT_UNICODE_ODD_LENGTH;
282 if (*len >= sizeof(bom_utf8) && !memcmp(buffer, bom_utf8, sizeof(bom_utf8)))
284 *len = sizeof(bom_utf8);
285 return ENCODING_UTF8;
287 RtlIsTextUnicode(buffer, *len, &flags);
288 if (flags & IS_TEXT_UNICODE_SIGNATURE)
290 *len = sizeof(WCHAR);
291 return ENCODING_UTF16LE;
293 if (flags & IS_TEXT_UNICODE_REVERSE_SIGNATURE)
295 *len = sizeof(WCHAR);
296 return ENCODING_UTF16BE;
298 *len = 0;
299 return ENCODING_ANSI;
303 /***********************************************************************
304 * PROFILE_Load
306 * Load a profile tree from a file.
308 static PROFILESECTION *PROFILE_Load(HANDLE hFile, ENCODING * pEncoding)
310 void *buffer_base, *pBuffer;
311 WCHAR * szFile;
312 const WCHAR *szLineStart, *szLineEnd;
313 const WCHAR *szValueStart, *szEnd, *next_line;
314 int line = 0, len;
315 PROFILESECTION *section, *first_section;
316 PROFILESECTION **next_section;
317 PROFILEKEY *key, *prev_key, **next_key;
318 DWORD dwFileSize;
320 TRACE("%p\n", hFile);
322 dwFileSize = GetFileSize(hFile, NULL);
323 if (dwFileSize == INVALID_FILE_SIZE || dwFileSize == 0)
324 return NULL;
326 buffer_base = HeapAlloc(GetProcessHeap(), 0 , dwFileSize);
327 if (!buffer_base) return NULL;
329 if (!ReadFile(hFile, buffer_base, dwFileSize, &dwFileSize, NULL))
331 HeapFree(GetProcessHeap(), 0, buffer_base);
332 WARN("Error %d reading file\n", GetLastError());
333 return NULL;
335 len = dwFileSize;
336 *pEncoding = PROFILE_DetectTextEncoding(buffer_base, &len);
337 /* len is set to the number of bytes in the character marker.
338 * we want to skip these bytes */
339 pBuffer = (char *)buffer_base + len;
340 dwFileSize -= len;
341 switch (*pEncoding)
343 case ENCODING_ANSI:
344 TRACE("ANSI encoding\n");
346 len = MultiByteToWideChar(CP_ACP, 0, pBuffer, dwFileSize, NULL, 0);
347 szFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
348 if (!szFile)
350 HeapFree(GetProcessHeap(), 0, buffer_base);
351 return NULL;
353 MultiByteToWideChar(CP_ACP, 0, pBuffer, dwFileSize, szFile, len);
354 szEnd = szFile + len;
355 break;
356 case ENCODING_UTF8:
357 TRACE("UTF8 encoding\n");
359 len = MultiByteToWideChar(CP_UTF8, 0, pBuffer, dwFileSize, NULL, 0);
360 szFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
361 if (!szFile)
363 HeapFree(GetProcessHeap(), 0, buffer_base);
364 return NULL;
366 MultiByteToWideChar(CP_UTF8, 0, pBuffer, dwFileSize, szFile, len);
367 szEnd = szFile + len;
368 break;
369 case ENCODING_UTF16LE:
370 TRACE("UTF16 Little Endian encoding\n");
371 szFile = pBuffer;
372 szEnd = (WCHAR *)((char *)pBuffer + dwFileSize);
373 break;
374 case ENCODING_UTF16BE:
375 TRACE("UTF16 Big Endian encoding\n");
376 szFile = pBuffer;
377 szEnd = (WCHAR *)((char *)pBuffer + dwFileSize);
378 PROFILE_ByteSwapShortBuffer(szFile, dwFileSize / sizeof(WCHAR));
379 break;
380 default:
381 FIXME("encoding type %d not implemented\n", *pEncoding);
382 HeapFree(GetProcessHeap(), 0, buffer_base);
383 return NULL;
386 first_section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) );
387 if(first_section == NULL)
389 if (szFile != pBuffer)
390 HeapFree(GetProcessHeap(), 0, szFile);
391 HeapFree(GetProcessHeap(), 0, buffer_base);
392 return NULL;
394 first_section->name[0] = 0;
395 first_section->key = NULL;
396 first_section->next = NULL;
397 next_section = &first_section->next;
398 next_key = &first_section->key;
399 prev_key = NULL;
400 next_line = szFile;
402 while (next_line < szEnd)
404 szLineStart = next_line;
405 next_line = memchrW(szLineStart, '\n', szEnd - szLineStart);
406 if (!next_line) next_line = memchrW(szLineStart, '\r', szEnd - szLineStart);
407 if (!next_line) next_line = szEnd;
408 else next_line++;
409 szLineEnd = next_line;
411 line++;
413 /* get rid of white space */
414 while (szLineStart < szLineEnd && PROFILE_isspaceW(*szLineStart)) szLineStart++;
415 while ((szLineEnd > szLineStart) && PROFILE_isspaceW(szLineEnd[-1])) szLineEnd--;
417 if (szLineStart >= szLineEnd) continue;
419 if (*szLineStart == '[') /* section start */
421 const WCHAR * szSectionEnd;
422 if (!(szSectionEnd = memrchrW( szLineStart, ']', szLineEnd - szLineStart )))
424 WARN("Invalid section header at line %d: %s\n",
425 line, debugstr_wn(szLineStart, (int)(szLineEnd - szLineStart)) );
427 else
429 szLineStart++;
430 len = (int)(szSectionEnd - szLineStart);
431 /* no need to allocate +1 for NULL terminating character as
432 * already included in structure */
433 if (!(section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) + len * sizeof(WCHAR) )))
434 break;
435 memcpy(section->name, szLineStart, len * sizeof(WCHAR));
436 section->name[len] = '\0';
437 section->key = NULL;
438 section->next = NULL;
439 *next_section = section;
440 next_section = &section->next;
441 next_key = &section->key;
442 prev_key = NULL;
444 TRACE("New section: %s\n", debugstr_w(section->name));
446 continue;
450 /* get rid of white space after the name and before the start
451 * of the value */
452 len = szLineEnd - szLineStart;
453 if ((szValueStart = memchrW( szLineStart, '=', szLineEnd - szLineStart )) != NULL)
455 const WCHAR *szNameEnd = szValueStart;
456 while ((szNameEnd > szLineStart) && PROFILE_isspaceW(szNameEnd[-1])) szNameEnd--;
457 len = szNameEnd - szLineStart;
458 szValueStart++;
459 while (szValueStart < szLineEnd && PROFILE_isspaceW(*szValueStart)) szValueStart++;
462 if (len || !prev_key || *prev_key->name)
464 /* no need to allocate +1 for NULL terminating character as
465 * already included in structure */
466 if (!(key = HeapAlloc( GetProcessHeap(), 0, sizeof(*key) + len * sizeof(WCHAR) ))) break;
467 memcpy(key->name, szLineStart, len * sizeof(WCHAR));
468 key->name[len] = '\0';
469 if (szValueStart)
471 len = (int)(szLineEnd - szValueStart);
472 key->value = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
473 memcpy(key->value, szValueStart, len * sizeof(WCHAR));
474 key->value[len] = '\0';
476 else key->value = NULL;
478 key->next = NULL;
479 *next_key = key;
480 next_key = &key->next;
481 prev_key = key;
483 TRACE("New key: name=%s, value=%s\n",
484 debugstr_w(key->name), key->value ? debugstr_w(key->value) : "(none)");
487 if (szFile != pBuffer)
488 HeapFree(GetProcessHeap(), 0, szFile);
489 HeapFree(GetProcessHeap(), 0, buffer_base);
490 return first_section;
494 /***********************************************************************
495 * PROFILE_DeleteSection
497 * Delete a section from a profile tree.
499 static BOOL PROFILE_DeleteSection( PROFILESECTION **section, LPCWSTR name )
501 while (*section)
503 if (!strcmpiW( (*section)->name, name ))
505 PROFILESECTION *to_del = *section;
506 *section = to_del->next;
507 to_del->next = NULL;
508 PROFILE_Free( to_del );
509 return TRUE;
511 section = &(*section)->next;
513 return FALSE;
517 /***********************************************************************
518 * PROFILE_DeleteKey
520 * Delete a key from a profile tree.
522 static BOOL PROFILE_DeleteKey( PROFILESECTION **section,
523 LPCWSTR section_name, LPCWSTR key_name )
525 while (*section)
527 if (!strcmpiW( (*section)->name, section_name ))
529 PROFILEKEY **key = &(*section)->key;
530 while (*key)
532 if (!strcmpiW( (*key)->name, key_name ))
534 PROFILEKEY *to_del = *key;
535 *key = to_del->next;
536 HeapFree( GetProcessHeap(), 0, to_del->value);
537 HeapFree( GetProcessHeap(), 0, to_del );
538 return TRUE;
540 key = &(*key)->next;
543 section = &(*section)->next;
545 return FALSE;
549 /***********************************************************************
550 * PROFILE_DeleteAllKeys
552 * Delete all keys from a profile tree.
554 static void PROFILE_DeleteAllKeys( LPCWSTR section_name)
556 PROFILESECTION **section= &CurProfile->section;
557 while (*section)
559 if (!strcmpiW( (*section)->name, section_name ))
561 PROFILEKEY **key = &(*section)->key;
562 while (*key)
564 PROFILEKEY *to_del = *key;
565 *key = to_del->next;
566 HeapFree( GetProcessHeap(), 0, to_del->value);
567 HeapFree( GetProcessHeap(), 0, to_del );
568 CurProfile->changed =TRUE;
571 section = &(*section)->next;
576 /***********************************************************************
577 * PROFILE_Find
579 * Find a key in a profile tree, optionally creating it.
581 static PROFILEKEY *PROFILE_Find( PROFILESECTION **section, LPCWSTR section_name,
582 LPCWSTR key_name, BOOL create, BOOL create_always )
584 LPCWSTR p;
585 int seclen = 0, keylen = 0;
587 while (PROFILE_isspaceW(*section_name)) section_name++;
588 if (*section_name)
590 p = section_name + strlenW(section_name) - 1;
591 while ((p > section_name) && PROFILE_isspaceW(*p)) p--;
592 seclen = p - section_name + 1;
595 while (PROFILE_isspaceW(*key_name)) key_name++;
596 if (*key_name)
598 p = key_name + strlenW(key_name) - 1;
599 while ((p > key_name) && PROFILE_isspaceW(*p)) p--;
600 keylen = p - key_name + 1;
603 while (*section)
605 if (!strncmpiW((*section)->name, section_name, seclen) &&
606 ((*section)->name)[seclen] == '\0')
608 PROFILEKEY **key = &(*section)->key;
610 while (*key)
612 /* If create_always is FALSE then we check if the keyname
613 * already exists. Otherwise we add it regardless of its
614 * existence, to allow keys to be added more than once in
615 * some cases.
617 if(!create_always)
619 if ( (!(strncmpiW( (*key)->name, key_name, keylen )))
620 && (((*key)->name)[keylen] == '\0') )
621 return *key;
623 key = &(*key)->next;
625 if (!create) return NULL;
626 if (!(*key = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
627 return NULL;
628 strcpyW( (*key)->name, key_name );
629 (*key)->value = NULL;
630 (*key)->next = NULL;
631 return *key;
633 section = &(*section)->next;
635 if (!create) return NULL;
636 *section = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILESECTION) + strlenW(section_name) * sizeof(WCHAR) );
637 if(*section == NULL) return NULL;
638 strcpyW( (*section)->name, section_name );
639 (*section)->next = NULL;
640 if (!((*section)->key = HeapAlloc( GetProcessHeap(), 0,
641 sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
643 HeapFree(GetProcessHeap(), 0, *section);
644 return NULL;
646 strcpyW( (*section)->key->name, key_name );
647 (*section)->key->value = NULL;
648 (*section)->key->next = NULL;
649 return (*section)->key;
653 /***********************************************************************
654 * PROFILE_FlushFile
656 * Flush the current profile to disk if changed.
658 static BOOL PROFILE_FlushFile(void)
660 HANDLE hFile = NULL;
661 FILETIME LastWriteTime;
663 if(!CurProfile)
665 WARN("No current profile!\n");
666 return FALSE;
669 if (!CurProfile->changed) return TRUE;
671 hFile = CreateFileW(CurProfile->filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
672 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
674 if (hFile == INVALID_HANDLE_VALUE)
676 WARN("could not save profile file %s (error was %d)\n", debugstr_w(CurProfile->filename), GetLastError());
677 return FALSE;
680 TRACE("Saving %s\n", debugstr_w(CurProfile->filename));
681 PROFILE_Save( hFile, CurProfile->section, CurProfile->encoding );
682 if(GetFileTime(hFile, NULL, NULL, &LastWriteTime))
683 CurProfile->LastWriteTime=LastWriteTime;
684 CloseHandle( hFile );
685 CurProfile->changed = FALSE;
686 return TRUE;
690 /***********************************************************************
691 * PROFILE_ReleaseFile
693 * Flush the current profile to disk and remove it from the cache.
695 static void PROFILE_ReleaseFile(void)
697 PROFILE_FlushFile();
698 PROFILE_Free( CurProfile->section );
699 HeapFree( GetProcessHeap(), 0, CurProfile->filename );
700 CurProfile->changed = FALSE;
701 CurProfile->section = NULL;
702 CurProfile->filename = NULL;
703 CurProfile->encoding = ENCODING_ANSI;
704 ZeroMemory(&CurProfile->LastWriteTime, sizeof(CurProfile->LastWriteTime));
707 /***********************************************************************
709 * Compares a file time with the current time. If the file time is
710 * at least 2.1 seconds in the past, return true.
712 * Intended as cache safety measure: The time resolution on FAT is
713 * two seconds, so files that are not at least two seconds old might
714 * keep their time even on modification, so don't cache them.
716 static BOOL is_not_current(FILETIME * ft)
718 FILETIME Now;
719 LONGLONG ftll, nowll;
720 GetSystemTimeAsFileTime(&Now);
721 ftll = ((LONGLONG)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
722 nowll = ((LONGLONG)Now.dwHighDateTime << 32) + Now.dwLowDateTime;
723 TRACE("%08x;%08x\n",(unsigned)ftll+21000000,(unsigned)nowll);
724 return ftll + 21000000 < nowll;
727 /***********************************************************************
728 * PROFILE_Open
730 * Open a profile file, checking the cached file first.
732 static BOOL PROFILE_Open( LPCWSTR filename, BOOL write_access )
734 WCHAR buffer[MAX_PATH];
735 HANDLE hFile = INVALID_HANDLE_VALUE;
736 FILETIME LastWriteTime;
737 int i,j;
738 PROFILE *tempProfile;
740 ZeroMemory(&LastWriteTime, sizeof(LastWriteTime));
742 /* First time around */
744 if(!CurProfile)
745 for(i=0;i<N_CACHED_PROFILES;i++)
747 MRUProfile[i]=HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILE) );
748 if(MRUProfile[i] == NULL) break;
749 MRUProfile[i]->changed=FALSE;
750 MRUProfile[i]->section=NULL;
751 MRUProfile[i]->filename=NULL;
752 MRUProfile[i]->encoding=ENCODING_ANSI;
753 ZeroMemory(&MRUProfile[i]->LastWriteTime, sizeof(FILETIME));
756 if (!filename)
757 filename = wininiW;
759 if ((RtlDetermineDosPathNameType_U(filename) == RELATIVE_PATH) &&
760 !strchrW(filename, '\\') && !strchrW(filename, '/'))
762 static const WCHAR wszSeparator[] = {'\\', 0};
763 WCHAR windirW[MAX_PATH];
764 GetWindowsDirectoryW( windirW, MAX_PATH );
765 strcpyW(buffer, windirW);
766 strcatW(buffer, wszSeparator);
767 strcatW(buffer, filename);
769 else
771 LPWSTR dummy;
772 GetFullPathNameW(filename, ARRAY_SIZE(buffer), buffer, &dummy);
775 TRACE("path: %s\n", debugstr_w(buffer));
777 hFile = CreateFileW(buffer, GENERIC_READ | (write_access ? GENERIC_WRITE : 0),
778 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
779 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
781 if ((hFile == INVALID_HANDLE_VALUE) && (GetLastError() != ERROR_FILE_NOT_FOUND))
783 WARN("Error %d opening file %s\n", GetLastError(), debugstr_w(buffer));
784 return FALSE;
787 for(i=0;i<N_CACHED_PROFILES;i++)
789 if ((MRUProfile[i]->filename && !strcmpiW( buffer, MRUProfile[i]->filename )))
791 TRACE("MRU Filename: %s, new filename: %s\n", debugstr_w(MRUProfile[i]->filename), debugstr_w(buffer));
792 if(i)
794 PROFILE_FlushFile();
795 tempProfile=MRUProfile[i];
796 for(j=i;j>0;j--)
797 MRUProfile[j]=MRUProfile[j-1];
798 CurProfile=tempProfile;
801 if (hFile != INVALID_HANDLE_VALUE)
803 GetFileTime(hFile, NULL, NULL, &LastWriteTime);
804 if (!memcmp( &CurProfile->LastWriteTime, &LastWriteTime, sizeof(FILETIME) ) &&
805 is_not_current(&LastWriteTime))
806 TRACE("(%s): already opened (mru=%d)\n",
807 debugstr_w(buffer), i);
808 else
810 TRACE("(%s): already opened, needs refreshing (mru=%d)\n",
811 debugstr_w(buffer), i);
812 PROFILE_Free(CurProfile->section);
813 CurProfile->section = PROFILE_Load(hFile, &CurProfile->encoding);
814 CurProfile->LastWriteTime = LastWriteTime;
816 CloseHandle(hFile);
817 return TRUE;
819 else TRACE("(%s): already opened, not yet created (mru=%d)\n",
820 debugstr_w(buffer), i);
824 /* Flush the old current profile */
825 PROFILE_FlushFile();
827 /* Make the oldest profile the current one only in order to get rid of it */
828 if(i==N_CACHED_PROFILES)
830 tempProfile=MRUProfile[N_CACHED_PROFILES-1];
831 for(i=N_CACHED_PROFILES-1;i>0;i--)
832 MRUProfile[i]=MRUProfile[i-1];
833 CurProfile=tempProfile;
835 if(CurProfile->filename) PROFILE_ReleaseFile();
837 /* OK, now that CurProfile is definitely free we assign it our new file */
838 CurProfile->filename = HeapAlloc( GetProcessHeap(), 0, (strlenW(buffer)+1) * sizeof(WCHAR) );
839 strcpyW( CurProfile->filename, buffer );
841 if (hFile != INVALID_HANDLE_VALUE)
843 CurProfile->section = PROFILE_Load(hFile, &CurProfile->encoding);
844 GetFileTime(hFile, NULL, NULL, &CurProfile->LastWriteTime);
845 CloseHandle(hFile);
847 else
849 /* Does not exist yet, we will create it in PROFILE_FlushFile */
850 WARN("profile file %s not found\n", debugstr_w(buffer) );
852 return TRUE;
856 /***********************************************************************
857 * PROFILE_GetSection
859 * Returns all keys of a section.
860 * If return_values is TRUE, also include the corresponding values.
862 static INT PROFILE_GetSection( PROFILESECTION *section, LPCWSTR section_name,
863 LPWSTR buffer, UINT len, BOOL return_values )
865 PROFILEKEY *key;
867 if(!buffer) return 0;
869 TRACE("%s,%p,%u\n", debugstr_w(section_name), buffer, len);
871 while (section)
873 if (!strcmpiW( section->name, section_name ))
875 UINT oldlen = len;
876 for (key = section->key; key; key = key->next)
878 if (len <= 2) break;
879 if (!*key->name && !key->value) continue; /* Skip empty lines */
880 if (IS_ENTRY_COMMENT(key->name)) continue; /* Skip comments */
881 if (!return_values && !key->value) continue; /* Skip lines w.o. '=' */
882 PROFILE_CopyEntry( buffer, key->name, len - 1, 0 );
883 len -= strlenW(buffer) + 1;
884 buffer += strlenW(buffer) + 1;
885 if (len < 2)
886 break;
887 if (return_values && key->value) {
888 buffer[-1] = '=';
889 PROFILE_CopyEntry ( buffer, key->value, len - 1, 0 );
890 len -= strlenW(buffer) + 1;
891 buffer += strlenW(buffer) + 1;
894 *buffer = '\0';
895 if (len <= 1)
896 /*If either lpszSection or lpszKey is NULL and the supplied
897 destination buffer is too small to hold all the strings,
898 the last string is truncated and followed by two null characters.
899 In this case, the return value is equal to cchReturnBuffer
900 minus two. */
902 buffer[-1] = '\0';
903 return oldlen - 2;
905 return oldlen - len;
907 section = section->next;
909 buffer[0] = buffer[1] = '\0';
910 return 0;
913 /* See GetPrivateProfileSectionNamesA for documentation */
914 static INT PROFILE_GetSectionNames( LPWSTR buffer, UINT len )
916 LPWSTR buf;
917 UINT buflen,tmplen;
918 PROFILESECTION *section;
920 TRACE("(%p, %d)\n", buffer, len);
922 if (!buffer || !len)
923 return 0;
924 if (len==1) {
925 *buffer='\0';
926 return 0;
929 buflen=len-1;
930 buf=buffer;
931 section = CurProfile->section;
932 while ((section!=NULL)) {
933 if (section->name[0]) {
934 tmplen = strlenW(section->name)+1;
935 if (tmplen >= buflen) {
936 if (buflen > 0) {
937 memcpy(buf, section->name, (buflen-1) * sizeof(WCHAR));
938 buf += buflen-1;
939 *buf++='\0';
941 *buf='\0';
942 return len-2;
944 memcpy(buf, section->name, tmplen * sizeof(WCHAR));
945 buf += tmplen;
946 buflen -= tmplen;
948 section = section->next;
950 *buf='\0';
951 return buf-buffer;
955 /***********************************************************************
956 * PROFILE_GetString
958 * Get a profile string.
960 * Tests with GetPrivateProfileString16, W95a,
961 * with filled buffer ("****...") and section "set1" and key_name "1" valid:
962 * section key_name def_val res buffer
963 * "set1" "1" "x" 43 [data]
964 * "set1" "1 " "x" 43 [data] (!)
965 * "set1" " 1 "' "x" 43 [data] (!)
966 * "set1" "" "x" 1 "x"
967 * "set1" "" "x " 1 "x" (!)
968 * "set1" "" " x " 3 " x" (!)
969 * "set1" NULL "x" 6 "1\02\03\0\0"
970 * "set1" "" "x" 1 "x"
971 * NULL "1" "x" 0 "" (!)
972 * "" "1" "x" 1 "x"
973 * NULL NULL "" 0 ""
977 static INT PROFILE_GetString( LPCWSTR section, LPCWSTR key_name,
978 LPCWSTR def_val, LPWSTR buffer, UINT len )
980 PROFILEKEY *key = NULL;
981 static const WCHAR empty_strW[] = { 0 };
983 if(!buffer || !len) return 0;
985 if (!def_val) def_val = empty_strW;
986 if (key_name)
988 key = PROFILE_Find( &CurProfile->section, section, key_name, FALSE, FALSE);
989 PROFILE_CopyEntry( buffer, (key && key->value) ? key->value : def_val,
990 len, TRUE );
991 TRACE("(%s,%s,%s): returning %s\n",
992 debugstr_w(section), debugstr_w(key_name),
993 debugstr_w(def_val), debugstr_w(buffer) );
994 return strlenW( buffer );
996 /* no "else" here ! */
997 if (section)
999 INT ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, FALSE);
1000 if (!buffer[0]) /* no luck -> def_val */
1002 PROFILE_CopyEntry(buffer, def_val, len, TRUE);
1003 ret = strlenW(buffer);
1005 return ret;
1007 buffer[0] = '\0';
1008 return 0;
1012 /***********************************************************************
1013 * PROFILE_SetString
1015 * Set a profile string.
1017 static BOOL PROFILE_SetString( LPCWSTR section_name, LPCWSTR key_name,
1018 LPCWSTR value, BOOL create_always )
1020 if (!key_name) /* Delete a whole section */
1022 TRACE("(%s)\n", debugstr_w(section_name));
1023 CurProfile->changed |= PROFILE_DeleteSection( &CurProfile->section,
1024 section_name );
1025 return TRUE; /* Even if PROFILE_DeleteSection() has failed,
1026 this is not an error on application's level.*/
1028 else if (!value) /* Delete a key */
1030 TRACE("(%s,%s)\n", debugstr_w(section_name), debugstr_w(key_name) );
1031 CurProfile->changed |= PROFILE_DeleteKey( &CurProfile->section,
1032 section_name, key_name );
1033 return TRUE; /* same error handling as above */
1035 else /* Set the key value */
1037 PROFILEKEY *key = PROFILE_Find(&CurProfile->section, section_name,
1038 key_name, TRUE, create_always );
1039 TRACE("(%s,%s,%s):\n",
1040 debugstr_w(section_name), debugstr_w(key_name), debugstr_w(value) );
1041 if (!key) return FALSE;
1043 /* strip the leading spaces. We can safely strip \n\r and
1044 * friends too, they should not happen here anyway. */
1045 while (PROFILE_isspaceW(*value)) value++;
1047 if (key->value)
1049 if (!strcmpW( key->value, value ))
1051 TRACE(" no change needed\n" );
1052 return TRUE; /* No change needed */
1054 TRACE(" replacing %s\n", debugstr_w(key->value) );
1055 HeapFree( GetProcessHeap(), 0, key->value );
1057 else TRACE(" creating key\n" );
1058 key->value = HeapAlloc( GetProcessHeap(), 0, (strlenW(value)+1) * sizeof(WCHAR) );
1059 strcpyW( key->value, value );
1060 CurProfile->changed = TRUE;
1062 return TRUE;
1066 /********************* API functions **********************************/
1069 /***********************************************************************
1070 * GetProfileIntA (KERNEL32.@)
1072 UINT WINAPI GetProfileIntA( LPCSTR section, LPCSTR entry, INT def_val )
1074 return GetPrivateProfileIntA( section, entry, def_val, "win.ini" );
1077 /***********************************************************************
1078 * GetProfileIntW (KERNEL32.@)
1080 UINT WINAPI GetProfileIntW( LPCWSTR section, LPCWSTR entry, INT def_val )
1082 return GetPrivateProfileIntW( section, entry, def_val, wininiW );
1085 /***********************************************************************
1086 * GetPrivateProfileStringW (KERNEL32.@)
1088 INT WINAPI GetPrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1089 LPCWSTR def_val, LPWSTR buffer,
1090 UINT len, LPCWSTR filename )
1092 int ret;
1093 LPWSTR defval_tmp = NULL;
1095 TRACE("%s,%s,%s,%p,%u,%s\n", debugstr_w(section), debugstr_w(entry),
1096 debugstr_w(def_val), buffer, len, debugstr_w(filename));
1098 /* strip any trailing ' ' of def_val. */
1099 if (def_val)
1101 LPCWSTR p = def_val + strlenW(def_val) - 1;
1103 while (p > def_val && *p == ' ')
1104 p--;
1106 if (p >= def_val)
1108 int vlen = (int)(p - def_val) + 1;
1110 defval_tmp = HeapAlloc(GetProcessHeap(), 0, (vlen + 1) * sizeof(WCHAR));
1111 memcpy(defval_tmp, def_val, vlen * sizeof(WCHAR));
1112 defval_tmp[vlen] = '\0';
1113 def_val = defval_tmp;
1117 RtlEnterCriticalSection( &PROFILE_CritSect );
1119 if (PROFILE_Open( filename, FALSE )) {
1120 if (section == NULL)
1121 ret = PROFILE_GetSectionNames(buffer, len);
1122 else
1123 /* PROFILE_GetString can handle the 'entry == NULL' case */
1124 ret = PROFILE_GetString( section, entry, def_val, buffer, len );
1125 } else if (buffer && def_val) {
1126 lstrcpynW( buffer, def_val, len );
1127 ret = strlenW( buffer );
1129 else
1130 ret = 0;
1132 RtlLeaveCriticalSection( &PROFILE_CritSect );
1134 HeapFree(GetProcessHeap(), 0, defval_tmp);
1136 TRACE("returning %s, %d\n", debugstr_w(buffer), ret);
1138 return ret;
1141 /***********************************************************************
1142 * GetPrivateProfileStringA (KERNEL32.@)
1144 INT WINAPI GetPrivateProfileStringA( LPCSTR section, LPCSTR entry,
1145 LPCSTR def_val, LPSTR buffer,
1146 UINT len, LPCSTR filename )
1148 UNICODE_STRING sectionW, entryW, def_valW, filenameW;
1149 LPWSTR bufferW;
1150 INT retW, ret = 0;
1152 bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)) : NULL;
1153 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1154 else sectionW.Buffer = NULL;
1155 if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1156 else entryW.Buffer = NULL;
1157 if (def_val) RtlCreateUnicodeStringFromAsciiz(&def_valW, def_val);
1158 else def_valW.Buffer = NULL;
1159 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1160 else filenameW.Buffer = NULL;
1162 retW = GetPrivateProfileStringW( sectionW.Buffer, entryW.Buffer,
1163 def_valW.Buffer, bufferW, len,
1164 filenameW.Buffer);
1165 if (len && buffer)
1167 if (retW)
1169 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW, buffer, len - 1, NULL, NULL);
1170 if (!ret)
1171 ret = len - 1;
1173 buffer[ret] = 0;
1176 RtlFreeUnicodeString(&sectionW);
1177 RtlFreeUnicodeString(&entryW);
1178 RtlFreeUnicodeString(&def_valW);
1179 RtlFreeUnicodeString(&filenameW);
1180 HeapFree(GetProcessHeap(), 0, bufferW);
1181 return ret;
1184 /***********************************************************************
1185 * GetProfileStringA (KERNEL32.@)
1187 INT WINAPI GetProfileStringA( LPCSTR section, LPCSTR entry, LPCSTR def_val,
1188 LPSTR buffer, UINT len )
1190 return GetPrivateProfileStringA( section, entry, def_val,
1191 buffer, len, "win.ini" );
1194 /***********************************************************************
1195 * GetProfileStringW (KERNEL32.@)
1197 INT WINAPI GetProfileStringW( LPCWSTR section, LPCWSTR entry,
1198 LPCWSTR def_val, LPWSTR buffer, UINT len )
1200 return GetPrivateProfileStringW( section, entry, def_val,
1201 buffer, len, wininiW );
1204 /***********************************************************************
1205 * WriteProfileStringA (KERNEL32.@)
1207 BOOL WINAPI WriteProfileStringA( LPCSTR section, LPCSTR entry,
1208 LPCSTR string )
1210 return WritePrivateProfileStringA( section, entry, string, "win.ini" );
1213 /***********************************************************************
1214 * WriteProfileStringW (KERNEL32.@)
1216 BOOL WINAPI WriteProfileStringW( LPCWSTR section, LPCWSTR entry,
1217 LPCWSTR string )
1219 return WritePrivateProfileStringW( section, entry, string, wininiW );
1223 /***********************************************************************
1224 * GetPrivateProfileIntW (KERNEL32.@)
1226 UINT WINAPI GetPrivateProfileIntW( LPCWSTR section, LPCWSTR entry,
1227 INT def_val, LPCWSTR filename )
1229 WCHAR buffer[30];
1230 UNICODE_STRING bufferW;
1231 ULONG result;
1233 if (GetPrivateProfileStringW( section, entry, emptystringW, buffer, ARRAY_SIZE( buffer ),
1234 filename ) == 0)
1235 return def_val;
1237 /* FIXME: if entry can be found but it's empty, then Win16 is
1238 * supposed to return 0 instead of def_val ! Difficult/problematic
1239 * to implement (every other failure also returns zero buffer),
1240 * thus wait until testing framework avail for making sure nothing
1241 * else gets broken that way. */
1242 if (!buffer[0]) return (UINT)def_val;
1244 RtlInitUnicodeString( &bufferW, buffer );
1245 RtlUnicodeStringToInteger( &bufferW, 0, &result);
1246 return result;
1249 /***********************************************************************
1250 * GetPrivateProfileIntA (KERNEL32.@)
1252 * FIXME: rewrite using unicode
1254 UINT WINAPI GetPrivateProfileIntA( LPCSTR section, LPCSTR entry,
1255 INT def_val, LPCSTR filename )
1257 UNICODE_STRING entryW, filenameW, sectionW;
1258 UINT res;
1259 if(entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1260 else entryW.Buffer = NULL;
1261 if(filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1262 else filenameW.Buffer = NULL;
1263 if(section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1264 else sectionW.Buffer = NULL;
1265 res = GetPrivateProfileIntW(sectionW.Buffer, entryW.Buffer, def_val,
1266 filenameW.Buffer);
1267 RtlFreeUnicodeString(&sectionW);
1268 RtlFreeUnicodeString(&filenameW);
1269 RtlFreeUnicodeString(&entryW);
1270 return res;
1273 /***********************************************************************
1274 * GetPrivateProfileSectionW (KERNEL32.@)
1276 INT WINAPI GetPrivateProfileSectionW( LPCWSTR section, LPWSTR buffer,
1277 DWORD len, LPCWSTR filename )
1279 int ret = 0;
1281 if (!section || !buffer)
1283 SetLastError(ERROR_INVALID_PARAMETER);
1284 return 0;
1287 TRACE("(%s, %p, %d, %s)\n", debugstr_w(section), buffer, len, debugstr_w(filename));
1289 RtlEnterCriticalSection( &PROFILE_CritSect );
1291 if (PROFILE_Open( filename, FALSE ))
1292 ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, TRUE);
1294 RtlLeaveCriticalSection( &PROFILE_CritSect );
1296 return ret;
1299 /***********************************************************************
1300 * GetPrivateProfileSectionA (KERNEL32.@)
1302 INT WINAPI GetPrivateProfileSectionA( LPCSTR section, LPSTR buffer,
1303 DWORD len, LPCSTR filename )
1305 UNICODE_STRING sectionW, filenameW;
1306 LPWSTR bufferW;
1307 INT retW, ret = 0;
1309 if (!section || !buffer)
1311 SetLastError(ERROR_INVALID_PARAMETER);
1312 return 0;
1315 bufferW = HeapAlloc(GetProcessHeap(), 0, len * 2 * sizeof(WCHAR));
1316 RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1317 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1318 else filenameW.Buffer = NULL;
1320 retW = GetPrivateProfileSectionW(sectionW.Buffer, bufferW, len * 2, filenameW.Buffer);
1321 if (retW)
1323 if (retW == len * 2 - 2) retW++; /* overflow */
1324 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW + 1, buffer, len, NULL, NULL);
1325 if (!ret || ret == len) /* overflow */
1327 ret = len - 2;
1328 buffer[len-2] = 0;
1329 buffer[len-1] = 0;
1331 else ret--;
1333 else
1335 buffer[0] = 0;
1336 buffer[1] = 0;
1339 RtlFreeUnicodeString(&sectionW);
1340 RtlFreeUnicodeString(&filenameW);
1341 HeapFree(GetProcessHeap(), 0, bufferW);
1342 return ret;
1345 /***********************************************************************
1346 * GetProfileSectionA (KERNEL32.@)
1348 INT WINAPI GetProfileSectionA( LPCSTR section, LPSTR buffer, DWORD len )
1350 return GetPrivateProfileSectionA( section, buffer, len, "win.ini" );
1353 /***********************************************************************
1354 * GetProfileSectionW (KERNEL32.@)
1356 INT WINAPI GetProfileSectionW( LPCWSTR section, LPWSTR buffer, DWORD len )
1358 return GetPrivateProfileSectionW( section, buffer, len, wininiW );
1362 /***********************************************************************
1363 * WritePrivateProfileStringW (KERNEL32.@)
1365 BOOL WINAPI WritePrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1366 LPCWSTR string, LPCWSTR filename )
1368 BOOL ret = FALSE;
1370 RtlEnterCriticalSection( &PROFILE_CritSect );
1372 if (!section && !entry && !string) /* documented "file flush" case */
1374 if (!filename || PROFILE_Open( filename, TRUE ))
1376 if (CurProfile) PROFILE_ReleaseFile(); /* always return FALSE in this case */
1379 else if (PROFILE_Open( filename, TRUE ))
1381 if (!section) {
1382 SetLastError(ERROR_FILE_NOT_FOUND);
1383 } else {
1384 ret = PROFILE_SetString( section, entry, string, FALSE);
1385 if (ret) ret = PROFILE_FlushFile();
1389 RtlLeaveCriticalSection( &PROFILE_CritSect );
1390 return ret;
1393 /***********************************************************************
1394 * WritePrivateProfileStringA (KERNEL32.@)
1396 BOOL WINAPI DECLSPEC_HOTPATCH WritePrivateProfileStringA( LPCSTR section, LPCSTR entry,
1397 LPCSTR string, LPCSTR filename )
1399 UNICODE_STRING sectionW, entryW, stringW, filenameW;
1400 BOOL ret;
1402 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1403 else sectionW.Buffer = NULL;
1404 if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1405 else entryW.Buffer = NULL;
1406 if (string) RtlCreateUnicodeStringFromAsciiz(&stringW, string);
1407 else stringW.Buffer = NULL;
1408 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1409 else filenameW.Buffer = NULL;
1411 ret = WritePrivateProfileStringW(sectionW.Buffer, entryW.Buffer,
1412 stringW.Buffer, filenameW.Buffer);
1413 RtlFreeUnicodeString(&sectionW);
1414 RtlFreeUnicodeString(&entryW);
1415 RtlFreeUnicodeString(&stringW);
1416 RtlFreeUnicodeString(&filenameW);
1417 return ret;
1420 /***********************************************************************
1421 * WritePrivateProfileSectionW (KERNEL32.@)
1423 BOOL WINAPI WritePrivateProfileSectionW( LPCWSTR section,
1424 LPCWSTR string, LPCWSTR filename )
1426 BOOL ret = FALSE;
1427 LPWSTR p;
1429 RtlEnterCriticalSection( &PROFILE_CritSect );
1431 if (!section && !string)
1433 if (!filename || PROFILE_Open( filename, TRUE ))
1435 if (CurProfile) PROFILE_ReleaseFile(); /* always return FALSE in this case */
1438 else if (PROFILE_Open( filename, TRUE )) {
1439 if (!string) {/* delete the named section*/
1440 ret = PROFILE_SetString(section,NULL,NULL, FALSE);
1441 } else {
1442 PROFILE_DeleteAllKeys(section);
1443 ret = TRUE;
1444 while(*string && ret) {
1445 LPWSTR buf = HeapAlloc( GetProcessHeap(), 0, (strlenW(string)+1) * sizeof(WCHAR) );
1446 strcpyW( buf, string );
1447 if((p = strchrW( buf, '='))) {
1448 *p='\0';
1449 ret = PROFILE_SetString( section, buf, p+1, TRUE);
1451 HeapFree( GetProcessHeap(), 0, buf );
1452 string += strlenW(string)+1;
1455 if (ret) ret = PROFILE_FlushFile();
1458 RtlLeaveCriticalSection( &PROFILE_CritSect );
1459 return ret;
1462 /***********************************************************************
1463 * WritePrivateProfileSectionA (KERNEL32.@)
1465 BOOL WINAPI WritePrivateProfileSectionA( LPCSTR section,
1466 LPCSTR string, LPCSTR filename)
1469 UNICODE_STRING sectionW, filenameW;
1470 LPWSTR stringW;
1471 BOOL ret;
1473 if (string)
1475 INT lenA, lenW;
1476 LPCSTR p = string;
1478 while(*p) p += strlen(p) + 1;
1479 lenA = p - string + 1;
1480 lenW = MultiByteToWideChar(CP_ACP, 0, string, lenA, NULL, 0);
1481 if ((stringW = HeapAlloc(GetProcessHeap(), 0, lenW * sizeof(WCHAR))))
1482 MultiByteToWideChar(CP_ACP, 0, string, lenA, stringW, lenW);
1484 else stringW = NULL;
1485 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1486 else sectionW.Buffer = NULL;
1487 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1488 else filenameW.Buffer = NULL;
1490 ret = WritePrivateProfileSectionW(sectionW.Buffer, stringW, filenameW.Buffer);
1492 HeapFree(GetProcessHeap(), 0, stringW);
1493 RtlFreeUnicodeString(&sectionW);
1494 RtlFreeUnicodeString(&filenameW);
1495 return ret;
1498 /***********************************************************************
1499 * WriteProfileSectionA (KERNEL32.@)
1501 BOOL WINAPI WriteProfileSectionA( LPCSTR section, LPCSTR keys_n_values)
1504 return WritePrivateProfileSectionA( section, keys_n_values, "win.ini");
1507 /***********************************************************************
1508 * WriteProfileSectionW (KERNEL32.@)
1510 BOOL WINAPI WriteProfileSectionW( LPCWSTR section, LPCWSTR keys_n_values)
1512 return WritePrivateProfileSectionW(section, keys_n_values, wininiW);
1516 /***********************************************************************
1517 * GetPrivateProfileSectionNamesW (KERNEL32.@)
1519 * Returns the section names contained in the specified file.
1520 * FIXME: Where do we find this file when the path is relative?
1521 * The section names are returned as a list of strings with an extra
1522 * '\0' to mark the end of the list. Except for that the behavior
1523 * depends on the Windows version.
1525 * Win95:
1526 * - if the buffer is 0 or 1 character long then it is as if it was of
1527 * infinite length.
1528 * - otherwise, if the buffer is too small only the section names that fit
1529 * are returned.
1530 * - note that this means if the buffer was too small to return even just
1531 * the first section name then a single '\0' will be returned.
1532 * - the return value is the number of characters written in the buffer,
1533 * except if the buffer was too small in which case len-2 is returned
1535 * Win2000:
1536 * - if the buffer is 0, 1 or 2 characters long then it is filled with
1537 * '\0' and the return value is 0
1538 * - otherwise if the buffer is too small then the first section name that
1539 * does not fit is truncated so that the string list can be terminated
1540 * correctly (double '\0')
1541 * - the return value is the number of characters written in the buffer
1542 * except for the trailing '\0'. If the buffer is too small, then the
1543 * return value is len-2
1544 * - Win2000 has a bug that triggers when the section names and the
1545 * trailing '\0' fit exactly in the buffer. In that case the trailing
1546 * '\0' is missing.
1548 * Wine implements the observed Win2000 behavior (except for the bug).
1550 * Note that when the buffer is big enough then the return value may be any
1551 * value between 1 and len-1 (or len in Win95), including len-2.
1553 DWORD WINAPI GetPrivateProfileSectionNamesW( LPWSTR buffer, DWORD size,
1554 LPCWSTR filename)
1556 DWORD ret = 0;
1558 RtlEnterCriticalSection( &PROFILE_CritSect );
1560 if (PROFILE_Open( filename, FALSE ))
1561 ret = PROFILE_GetSectionNames(buffer, size);
1563 RtlLeaveCriticalSection( &PROFILE_CritSect );
1565 return ret;
1569 /***********************************************************************
1570 * GetPrivateProfileSectionNamesA (KERNEL32.@)
1572 DWORD WINAPI GetPrivateProfileSectionNamesA( LPSTR buffer, DWORD size,
1573 LPCSTR filename)
1575 UNICODE_STRING filenameW;
1576 LPWSTR bufferW;
1577 INT retW, ret = 0;
1579 bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)) : NULL;
1580 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1581 else filenameW.Buffer = NULL;
1583 retW = GetPrivateProfileSectionNamesW(bufferW, size, filenameW.Buffer);
1584 if (retW && size)
1586 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW+1, buffer, size-1, NULL, NULL);
1587 if (!ret)
1589 ret = size-2;
1590 buffer[size-1] = 0;
1592 else
1593 ret = ret-1;
1595 else if(size)
1596 buffer[0] = '\0';
1598 RtlFreeUnicodeString(&filenameW);
1599 HeapFree(GetProcessHeap(), 0, bufferW);
1600 return ret;
1603 /***********************************************************************
1604 * GetPrivateProfileStructW (KERNEL32.@)
1606 * Should match Win95's behaviour pretty much
1608 BOOL WINAPI GetPrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1609 LPVOID buf, UINT len, LPCWSTR filename)
1611 BOOL ret = FALSE;
1613 RtlEnterCriticalSection( &PROFILE_CritSect );
1615 if (PROFILE_Open( filename, FALSE )) {
1616 PROFILEKEY *k = PROFILE_Find ( &CurProfile->section, section, key, FALSE, FALSE);
1617 if (k) {
1618 TRACE("value (at %p): %s\n", k->value, debugstr_w(k->value));
1619 if (((strlenW(k->value) - 2) / 2) == len)
1621 LPWSTR end, p;
1622 BOOL valid = TRUE;
1623 WCHAR c;
1624 DWORD chksum = 0;
1626 end = k->value + strlenW(k->value); /* -> '\0' */
1627 /* check for invalid chars in ASCII coded hex string */
1628 for (p=k->value; p < end; p++)
1630 if (!isxdigitW(*p))
1632 WARN("invalid char '%x' in file %s->[%s]->%s !\n",
1633 *p, debugstr_w(filename), debugstr_w(section), debugstr_w(key));
1634 valid = FALSE;
1635 break;
1638 if (valid)
1640 BOOL highnibble = TRUE;
1641 BYTE b = 0, val;
1642 LPBYTE binbuf = buf;
1644 end -= 2; /* don't include checksum in output data */
1645 /* translate ASCII hex format into binary data */
1646 for (p=k->value; p < end; p++)
1648 c = toupperW(*p);
1649 val = (c > '9') ?
1650 (c - 'A' + 10) : (c - '0');
1652 if (highnibble)
1653 b = val << 4;
1654 else
1656 b += val;
1657 *binbuf++ = b; /* feed binary data into output */
1658 chksum += b; /* calculate checksum */
1660 highnibble ^= 1; /* toggle */
1662 /* retrieve stored checksum value */
1663 c = toupperW(*p++);
1664 b = ( (c > '9') ? (c - 'A' + 10) : (c - '0') ) << 4;
1665 c = toupperW(*p);
1666 b += (c > '9') ? (c - 'A' + 10) : (c - '0');
1667 if (b == (chksum & 0xff)) /* checksums match ? */
1668 ret = TRUE;
1673 RtlLeaveCriticalSection( &PROFILE_CritSect );
1675 return ret;
1678 /***********************************************************************
1679 * GetPrivateProfileStructA (KERNEL32.@)
1681 BOOL WINAPI GetPrivateProfileStructA (LPCSTR section, LPCSTR key,
1682 LPVOID buffer, UINT len, LPCSTR filename)
1684 UNICODE_STRING sectionW, keyW, filenameW;
1685 INT ret;
1687 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1688 else sectionW.Buffer = NULL;
1689 if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1690 else keyW.Buffer = NULL;
1691 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1692 else filenameW.Buffer = NULL;
1694 ret = GetPrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buffer, len,
1695 filenameW.Buffer);
1696 /* Do not translate binary data. */
1698 RtlFreeUnicodeString(&sectionW);
1699 RtlFreeUnicodeString(&keyW);
1700 RtlFreeUnicodeString(&filenameW);
1701 return ret;
1706 /***********************************************************************
1707 * WritePrivateProfileStructW (KERNEL32.@)
1709 BOOL WINAPI WritePrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1710 LPVOID buf, UINT bufsize, LPCWSTR filename)
1712 BOOL ret = FALSE;
1713 LPBYTE binbuf;
1714 LPWSTR outstring, p;
1715 DWORD sum = 0;
1717 if (!section && !key && !buf) /* flush the cache */
1718 return WritePrivateProfileStringW( NULL, NULL, NULL, filename );
1720 /* allocate string buffer for hex chars + checksum hex char + '\0' */
1721 outstring = HeapAlloc( GetProcessHeap(), 0, (bufsize*2 + 2 + 1) * sizeof(WCHAR) );
1722 p = outstring;
1723 for (binbuf = (LPBYTE)buf; binbuf < (LPBYTE)buf+bufsize; binbuf++) {
1724 *p++ = hex[*binbuf >> 4];
1725 *p++ = hex[*binbuf & 0xf];
1726 sum += *binbuf;
1728 /* checksum is sum & 0xff */
1729 *p++ = hex[(sum & 0xf0) >> 4];
1730 *p++ = hex[sum & 0xf];
1731 *p++ = '\0';
1733 RtlEnterCriticalSection( &PROFILE_CritSect );
1735 if (PROFILE_Open( filename, TRUE )) {
1736 ret = PROFILE_SetString( section, key, outstring, FALSE);
1737 if (ret) ret = PROFILE_FlushFile();
1740 RtlLeaveCriticalSection( &PROFILE_CritSect );
1742 HeapFree( GetProcessHeap(), 0, outstring );
1744 return ret;
1747 /***********************************************************************
1748 * WritePrivateProfileStructA (KERNEL32.@)
1750 BOOL WINAPI WritePrivateProfileStructA (LPCSTR section, LPCSTR key,
1751 LPVOID buf, UINT bufsize, LPCSTR filename)
1753 UNICODE_STRING sectionW, keyW, filenameW;
1754 INT ret;
1756 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1757 else sectionW.Buffer = NULL;
1758 if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1759 else keyW.Buffer = NULL;
1760 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1761 else filenameW.Buffer = NULL;
1763 /* Do not translate binary data. */
1764 ret = WritePrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buf, bufsize,
1765 filenameW.Buffer);
1767 RtlFreeUnicodeString(&sectionW);
1768 RtlFreeUnicodeString(&keyW);
1769 RtlFreeUnicodeString(&filenameW);
1770 return ret;
1774 /***********************************************************************
1775 * OpenProfileUserMapping (KERNEL32.@)
1777 BOOL WINAPI OpenProfileUserMapping(void) {
1778 FIXME("(), stub!\n");
1779 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1780 return FALSE;
1783 /***********************************************************************
1784 * CloseProfileUserMapping (KERNEL32.@)
1786 BOOL WINAPI CloseProfileUserMapping(void) {
1787 FIXME("(), stub!\n");
1788 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1789 return FALSE;