makefiles: Don't use standard libs for programs that specify -nodefaultlibs.
[wine/zf.git] / dlls / kernel32 / profile.c
blobf7d64f16a5f5cd1a0a5ea3e282377d1aae696311
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 (c >= 0x09 && c <= 0x0d) || c == 0x1a || c == 0x20;
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 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 while (next_line < szEnd && *next_line != '\n' && *next_line != '\r') next_line++;
406 while (next_line < szEnd && (*next_line == '\n' || *next_line == '\r')) next_line++;
407 szLineEnd = next_line;
409 /* get rid of white space */
410 while (szLineStart < szLineEnd && PROFILE_isspaceW(*szLineStart)) szLineStart++;
411 while ((szLineEnd > szLineStart) && PROFILE_isspaceW(szLineEnd[-1])) szLineEnd--;
413 if (szLineStart >= szLineEnd) continue;
415 if (*szLineStart == '[') /* section start */
417 for (len = szLineEnd - szLineStart; len > 0; len--) if (szLineStart[len - 1] == ']') break;
418 if (!len)
420 WARN("Invalid section header: %s\n",
421 debugstr_wn(szLineStart, (int)(szLineEnd - szLineStart)) );
423 else
425 szLineStart++;
426 len -= 2;
427 /* no need to allocate +1 for NULL terminating character as
428 * already included in structure */
429 if (!(section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) + len * sizeof(WCHAR) )))
430 break;
431 memcpy(section->name, szLineStart, len * sizeof(WCHAR));
432 section->name[len] = '\0';
433 section->key = NULL;
434 section->next = NULL;
435 *next_section = section;
436 next_section = &section->next;
437 next_key = &section->key;
438 prev_key = NULL;
440 TRACE("New section: %s\n", debugstr_w(section->name));
442 continue;
446 /* get rid of white space after the name and before the start
447 * of the value */
448 len = szLineEnd - szLineStart;
449 for (szValueStart = szLineStart; szValueStart < szLineEnd; szValueStart++) if (*szValueStart == '=') break;
450 if (szValueStart < szLineEnd)
452 const WCHAR *szNameEnd = szValueStart;
453 while ((szNameEnd > szLineStart) && PROFILE_isspaceW(szNameEnd[-1])) szNameEnd--;
454 len = szNameEnd - szLineStart;
455 szValueStart++;
456 while (szValueStart < szLineEnd && PROFILE_isspaceW(*szValueStart)) szValueStart++;
458 else szValueStart = NULL;
460 if (len || !prev_key || *prev_key->name)
462 /* no need to allocate +1 for NULL terminating character as
463 * already included in structure */
464 if (!(key = HeapAlloc( GetProcessHeap(), 0, sizeof(*key) + len * sizeof(WCHAR) ))) break;
465 memcpy(key->name, szLineStart, len * sizeof(WCHAR));
466 key->name[len] = '\0';
467 if (szValueStart)
469 len = (int)(szLineEnd - szValueStart);
470 key->value = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
471 memcpy(key->value, szValueStart, len * sizeof(WCHAR));
472 key->value[len] = '\0';
474 else key->value = NULL;
476 key->next = NULL;
477 *next_key = key;
478 next_key = &key->next;
479 prev_key = key;
481 TRACE("New key: name=%s, value=%s\n",
482 debugstr_w(key->name), key->value ? debugstr_w(key->value) : "(none)");
485 if (szFile != pBuffer)
486 HeapFree(GetProcessHeap(), 0, szFile);
487 HeapFree(GetProcessHeap(), 0, buffer_base);
488 return first_section;
492 /***********************************************************************
493 * PROFILE_DeleteSection
495 * Delete a section from a profile tree.
497 static BOOL PROFILE_DeleteSection( PROFILESECTION **section, LPCWSTR name )
499 while (*section)
501 if (!strcmpiW( (*section)->name, name ))
503 PROFILESECTION *to_del = *section;
504 *section = to_del->next;
505 to_del->next = NULL;
506 PROFILE_Free( to_del );
507 return TRUE;
509 section = &(*section)->next;
511 return FALSE;
515 /***********************************************************************
516 * PROFILE_DeleteKey
518 * Delete a key from a profile tree.
520 static BOOL PROFILE_DeleteKey( PROFILESECTION **section,
521 LPCWSTR section_name, LPCWSTR key_name )
523 while (*section)
525 if (!strcmpiW( (*section)->name, section_name ))
527 PROFILEKEY **key = &(*section)->key;
528 while (*key)
530 if (!strcmpiW( (*key)->name, key_name ))
532 PROFILEKEY *to_del = *key;
533 *key = to_del->next;
534 HeapFree( GetProcessHeap(), 0, to_del->value);
535 HeapFree( GetProcessHeap(), 0, to_del );
536 return TRUE;
538 key = &(*key)->next;
541 section = &(*section)->next;
543 return FALSE;
547 /***********************************************************************
548 * PROFILE_DeleteAllKeys
550 * Delete all keys from a profile tree.
552 static void PROFILE_DeleteAllKeys( LPCWSTR section_name)
554 PROFILESECTION **section= &CurProfile->section;
555 while (*section)
557 if (!strcmpiW( (*section)->name, section_name ))
559 PROFILEKEY **key = &(*section)->key;
560 while (*key)
562 PROFILEKEY *to_del = *key;
563 *key = to_del->next;
564 HeapFree( GetProcessHeap(), 0, to_del->value);
565 HeapFree( GetProcessHeap(), 0, to_del );
566 CurProfile->changed =TRUE;
569 section = &(*section)->next;
574 /***********************************************************************
575 * PROFILE_Find
577 * Find a key in a profile tree, optionally creating it.
579 static PROFILEKEY *PROFILE_Find( PROFILESECTION **section, LPCWSTR section_name,
580 LPCWSTR key_name, BOOL create, BOOL create_always )
582 LPCWSTR p;
583 int seclen = 0, keylen = 0;
585 while (PROFILE_isspaceW(*section_name)) section_name++;
586 if (*section_name)
588 p = section_name + strlenW(section_name) - 1;
589 while ((p > section_name) && PROFILE_isspaceW(*p)) p--;
590 seclen = p - section_name + 1;
593 while (PROFILE_isspaceW(*key_name)) key_name++;
594 if (*key_name)
596 p = key_name + strlenW(key_name) - 1;
597 while ((p > key_name) && PROFILE_isspaceW(*p)) p--;
598 keylen = p - key_name + 1;
601 while (*section)
603 if (!strncmpiW((*section)->name, section_name, seclen) &&
604 ((*section)->name)[seclen] == '\0')
606 PROFILEKEY **key = &(*section)->key;
608 while (*key)
610 /* If create_always is FALSE then we check if the keyname
611 * already exists. Otherwise we add it regardless of its
612 * existence, to allow keys to be added more than once in
613 * some cases.
615 if(!create_always)
617 if ( (!(strncmpiW( (*key)->name, key_name, keylen )))
618 && (((*key)->name)[keylen] == '\0') )
619 return *key;
621 key = &(*key)->next;
623 if (!create) return NULL;
624 if (!(*key = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
625 return NULL;
626 strcpyW( (*key)->name, key_name );
627 (*key)->value = NULL;
628 (*key)->next = NULL;
629 return *key;
631 section = &(*section)->next;
633 if (!create) return NULL;
634 *section = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILESECTION) + strlenW(section_name) * sizeof(WCHAR) );
635 if(*section == NULL) return NULL;
636 strcpyW( (*section)->name, section_name );
637 (*section)->next = NULL;
638 if (!((*section)->key = HeapAlloc( GetProcessHeap(), 0,
639 sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
641 HeapFree(GetProcessHeap(), 0, *section);
642 return NULL;
644 strcpyW( (*section)->key->name, key_name );
645 (*section)->key->value = NULL;
646 (*section)->key->next = NULL;
647 return (*section)->key;
651 /***********************************************************************
652 * PROFILE_FlushFile
654 * Flush the current profile to disk if changed.
656 static BOOL PROFILE_FlushFile(void)
658 HANDLE hFile = NULL;
659 FILETIME LastWriteTime;
661 if(!CurProfile)
663 WARN("No current profile!\n");
664 return FALSE;
667 if (!CurProfile->changed) return TRUE;
669 hFile = CreateFileW(CurProfile->filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
670 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
672 if (hFile == INVALID_HANDLE_VALUE)
674 WARN("could not save profile file %s (error was %d)\n", debugstr_w(CurProfile->filename), GetLastError());
675 return FALSE;
678 TRACE("Saving %s\n", debugstr_w(CurProfile->filename));
679 PROFILE_Save( hFile, CurProfile->section, CurProfile->encoding );
680 if(GetFileTime(hFile, NULL, NULL, &LastWriteTime))
681 CurProfile->LastWriteTime=LastWriteTime;
682 CloseHandle( hFile );
683 CurProfile->changed = FALSE;
684 return TRUE;
688 /***********************************************************************
689 * PROFILE_ReleaseFile
691 * Flush the current profile to disk and remove it from the cache.
693 static void PROFILE_ReleaseFile(void)
695 PROFILE_FlushFile();
696 PROFILE_Free( CurProfile->section );
697 HeapFree( GetProcessHeap(), 0, CurProfile->filename );
698 CurProfile->changed = FALSE;
699 CurProfile->section = NULL;
700 CurProfile->filename = NULL;
701 CurProfile->encoding = ENCODING_ANSI;
702 ZeroMemory(&CurProfile->LastWriteTime, sizeof(CurProfile->LastWriteTime));
705 /***********************************************************************
707 * Compares a file time with the current time. If the file time is
708 * at least 2.1 seconds in the past, return true.
710 * Intended as cache safety measure: The time resolution on FAT is
711 * two seconds, so files that are not at least two seconds old might
712 * keep their time even on modification, so don't cache them.
714 static BOOL is_not_current(FILETIME *ft)
716 LARGE_INTEGER now;
717 LONGLONG ftll;
719 NtQuerySystemTime( &now );
720 ftll = ((LONGLONG)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
721 TRACE("%s; %s\n", wine_dbgstr_longlong(ftll), wine_dbgstr_longlong(now.QuadPart));
722 return ftll + 21000000 < now.QuadPart;
725 /***********************************************************************
726 * PROFILE_Open
728 * Open a profile file, checking the cached file first.
730 static BOOL PROFILE_Open( LPCWSTR filename, BOOL write_access )
732 WCHAR buffer[MAX_PATH];
733 HANDLE hFile = INVALID_HANDLE_VALUE;
734 FILETIME LastWriteTime;
735 int i,j;
736 PROFILE *tempProfile;
738 ZeroMemory(&LastWriteTime, sizeof(LastWriteTime));
740 /* First time around */
742 if(!CurProfile)
743 for(i=0;i<N_CACHED_PROFILES;i++)
745 MRUProfile[i]=HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILE) );
746 if(MRUProfile[i] == NULL) break;
747 MRUProfile[i]->changed=FALSE;
748 MRUProfile[i]->section=NULL;
749 MRUProfile[i]->filename=NULL;
750 MRUProfile[i]->encoding=ENCODING_ANSI;
751 ZeroMemory(&MRUProfile[i]->LastWriteTime, sizeof(FILETIME));
754 if (!filename)
755 filename = wininiW;
757 if ((RtlDetermineDosPathNameType_U(filename) == RELATIVE_PATH) &&
758 !strchrW(filename, '\\') && !strchrW(filename, '/'))
760 static const WCHAR wszSeparator[] = {'\\', 0};
761 WCHAR windirW[MAX_PATH];
762 GetWindowsDirectoryW( windirW, MAX_PATH );
763 strcpyW(buffer, windirW);
764 strcatW(buffer, wszSeparator);
765 strcatW(buffer, filename);
767 else
769 LPWSTR dummy;
770 GetFullPathNameW(filename, ARRAY_SIZE(buffer), buffer, &dummy);
773 TRACE("path: %s\n", debugstr_w(buffer));
775 hFile = CreateFileW(buffer, GENERIC_READ | (write_access ? GENERIC_WRITE : 0),
776 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
777 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
779 if ((hFile == INVALID_HANDLE_VALUE) && (GetLastError() != ERROR_FILE_NOT_FOUND))
781 WARN("Error %d opening file %s\n", GetLastError(), debugstr_w(buffer));
782 return FALSE;
785 for(i=0;i<N_CACHED_PROFILES;i++)
787 if ((MRUProfile[i]->filename && !strcmpiW( buffer, MRUProfile[i]->filename )))
789 TRACE("MRU Filename: %s, new filename: %s\n", debugstr_w(MRUProfile[i]->filename), debugstr_w(buffer));
790 if(i)
792 PROFILE_FlushFile();
793 tempProfile=MRUProfile[i];
794 for(j=i;j>0;j--)
795 MRUProfile[j]=MRUProfile[j-1];
796 CurProfile=tempProfile;
799 if (hFile != INVALID_HANDLE_VALUE)
801 GetFileTime(hFile, NULL, NULL, &LastWriteTime);
802 if (!memcmp( &CurProfile->LastWriteTime, &LastWriteTime, sizeof(FILETIME) ) &&
803 is_not_current(&LastWriteTime))
804 TRACE("(%s): already opened (mru=%d)\n",
805 debugstr_w(buffer), i);
806 else
808 TRACE("(%s): already opened, needs refreshing (mru=%d)\n",
809 debugstr_w(buffer), i);
810 PROFILE_Free(CurProfile->section);
811 CurProfile->section = PROFILE_Load(hFile, &CurProfile->encoding);
812 CurProfile->LastWriteTime = LastWriteTime;
814 CloseHandle(hFile);
815 return TRUE;
817 else TRACE("(%s): already opened, not yet created (mru=%d)\n",
818 debugstr_w(buffer), i);
822 /* Flush the old current profile */
823 PROFILE_FlushFile();
825 /* Make the oldest profile the current one only in order to get rid of it */
826 if(i==N_CACHED_PROFILES)
828 tempProfile=MRUProfile[N_CACHED_PROFILES-1];
829 for(i=N_CACHED_PROFILES-1;i>0;i--)
830 MRUProfile[i]=MRUProfile[i-1];
831 CurProfile=tempProfile;
833 if(CurProfile->filename) PROFILE_ReleaseFile();
835 /* OK, now that CurProfile is definitely free we assign it our new file */
836 CurProfile->filename = HeapAlloc( GetProcessHeap(), 0, (strlenW(buffer)+1) * sizeof(WCHAR) );
837 strcpyW( CurProfile->filename, buffer );
839 if (hFile != INVALID_HANDLE_VALUE)
841 CurProfile->section = PROFILE_Load(hFile, &CurProfile->encoding);
842 GetFileTime(hFile, NULL, NULL, &CurProfile->LastWriteTime);
843 CloseHandle(hFile);
845 else
847 /* Does not exist yet, we will create it in PROFILE_FlushFile */
848 WARN("profile file %s not found\n", debugstr_w(buffer) );
850 return TRUE;
854 /***********************************************************************
855 * PROFILE_GetSection
857 * Returns all keys of a section.
858 * If return_values is TRUE, also include the corresponding values.
860 static INT PROFILE_GetSection( PROFILESECTION *section, LPCWSTR section_name,
861 LPWSTR buffer, UINT len, BOOL return_values )
863 PROFILEKEY *key;
865 if(!buffer) return 0;
867 TRACE("%s,%p,%u\n", debugstr_w(section_name), buffer, len);
869 while (section)
871 if (!strcmpiW( section->name, section_name ))
873 UINT oldlen = len;
874 for (key = section->key; key; key = key->next)
876 if (len <= 2) break;
877 if (!*key->name && !key->value) continue; /* Skip empty lines */
878 if (IS_ENTRY_COMMENT(key->name)) continue; /* Skip comments */
879 if (!return_values && !key->value) continue; /* Skip lines w.o. '=' */
880 PROFILE_CopyEntry( buffer, key->name, len - 1, 0 );
881 len -= strlenW(buffer) + 1;
882 buffer += strlenW(buffer) + 1;
883 if (len < 2)
884 break;
885 if (return_values && key->value) {
886 buffer[-1] = '=';
887 PROFILE_CopyEntry ( buffer, key->value, len - 1, 0 );
888 len -= strlenW(buffer) + 1;
889 buffer += strlenW(buffer) + 1;
892 *buffer = '\0';
893 if (len <= 1)
894 /*If either lpszSection or lpszKey is NULL and the supplied
895 destination buffer is too small to hold all the strings,
896 the last string is truncated and followed by two null characters.
897 In this case, the return value is equal to cchReturnBuffer
898 minus two. */
900 buffer[-1] = '\0';
901 return oldlen - 2;
903 return oldlen - len;
905 section = section->next;
907 buffer[0] = buffer[1] = '\0';
908 return 0;
911 /* See GetPrivateProfileSectionNamesA for documentation */
912 static INT PROFILE_GetSectionNames( LPWSTR buffer, UINT len )
914 LPWSTR buf;
915 UINT buflen,tmplen;
916 PROFILESECTION *section;
918 TRACE("(%p, %d)\n", buffer, len);
920 if (!buffer || !len)
921 return 0;
922 if (len==1) {
923 *buffer='\0';
924 return 0;
927 buflen=len-1;
928 buf=buffer;
929 section = CurProfile->section;
930 while ((section!=NULL)) {
931 if (section->name[0]) {
932 tmplen = strlenW(section->name)+1;
933 if (tmplen >= buflen) {
934 if (buflen > 0) {
935 memcpy(buf, section->name, (buflen-1) * sizeof(WCHAR));
936 buf += buflen-1;
937 *buf++='\0';
939 *buf='\0';
940 return len-2;
942 memcpy(buf, section->name, tmplen * sizeof(WCHAR));
943 buf += tmplen;
944 buflen -= tmplen;
946 section = section->next;
948 *buf='\0';
949 return buf-buffer;
953 /***********************************************************************
954 * PROFILE_GetString
956 * Get a profile string.
958 * Tests with GetPrivateProfileString16, W95a,
959 * with filled buffer ("****...") and section "set1" and key_name "1" valid:
960 * section key_name def_val res buffer
961 * "set1" "1" "x" 43 [data]
962 * "set1" "1 " "x" 43 [data] (!)
963 * "set1" " 1 "' "x" 43 [data] (!)
964 * "set1" "" "x" 1 "x"
965 * "set1" "" "x " 1 "x" (!)
966 * "set1" "" " x " 3 " x" (!)
967 * "set1" NULL "x" 6 "1\02\03\0\0"
968 * "set1" "" "x" 1 "x"
969 * NULL "1" "x" 0 "" (!)
970 * "" "1" "x" 1 "x"
971 * NULL NULL "" 0 ""
975 static INT PROFILE_GetString( LPCWSTR section, LPCWSTR key_name,
976 LPCWSTR def_val, LPWSTR buffer, UINT len )
978 PROFILEKEY *key = NULL;
979 static const WCHAR empty_strW[] = { 0 };
981 if(!buffer || !len) return 0;
983 if (!def_val) def_val = empty_strW;
984 if (key_name)
986 key = PROFILE_Find( &CurProfile->section, section, key_name, FALSE, FALSE);
987 PROFILE_CopyEntry( buffer, (key && key->value) ? key->value : def_val,
988 len, TRUE );
989 TRACE("(%s,%s,%s): returning %s\n",
990 debugstr_w(section), debugstr_w(key_name),
991 debugstr_w(def_val), debugstr_w(buffer) );
992 return strlenW( buffer );
994 /* no "else" here ! */
995 if (section)
997 INT ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, FALSE);
998 if (!buffer[0]) /* no luck -> def_val */
1000 PROFILE_CopyEntry(buffer, def_val, len, TRUE);
1001 ret = strlenW(buffer);
1003 return ret;
1005 buffer[0] = '\0';
1006 return 0;
1010 /***********************************************************************
1011 * PROFILE_SetString
1013 * Set a profile string.
1015 static BOOL PROFILE_SetString( LPCWSTR section_name, LPCWSTR key_name,
1016 LPCWSTR value, BOOL create_always )
1018 if (!key_name) /* Delete a whole section */
1020 TRACE("(%s)\n", debugstr_w(section_name));
1021 CurProfile->changed |= PROFILE_DeleteSection( &CurProfile->section,
1022 section_name );
1023 return TRUE; /* Even if PROFILE_DeleteSection() has failed,
1024 this is not an error on application's level.*/
1026 else if (!value) /* Delete a key */
1028 TRACE("(%s,%s)\n", debugstr_w(section_name), debugstr_w(key_name) );
1029 CurProfile->changed |= PROFILE_DeleteKey( &CurProfile->section,
1030 section_name, key_name );
1031 return TRUE; /* same error handling as above */
1033 else /* Set the key value */
1035 PROFILEKEY *key = PROFILE_Find(&CurProfile->section, section_name,
1036 key_name, TRUE, create_always );
1037 TRACE("(%s,%s,%s):\n",
1038 debugstr_w(section_name), debugstr_w(key_name), debugstr_w(value) );
1039 if (!key) return FALSE;
1041 /* strip the leading spaces. We can safely strip \n\r and
1042 * friends too, they should not happen here anyway. */
1043 while (PROFILE_isspaceW(*value)) value++;
1045 if (key->value)
1047 if (!strcmpW( key->value, value ))
1049 TRACE(" no change needed\n" );
1050 return TRUE; /* No change needed */
1052 TRACE(" replacing %s\n", debugstr_w(key->value) );
1053 HeapFree( GetProcessHeap(), 0, key->value );
1055 else TRACE(" creating key\n" );
1056 key->value = HeapAlloc( GetProcessHeap(), 0, (strlenW(value)+1) * sizeof(WCHAR) );
1057 strcpyW( key->value, value );
1058 CurProfile->changed = TRUE;
1060 return TRUE;
1064 /********************* API functions **********************************/
1067 /***********************************************************************
1068 * GetProfileIntA (KERNEL32.@)
1070 UINT WINAPI GetProfileIntA( LPCSTR section, LPCSTR entry, INT def_val )
1072 return GetPrivateProfileIntA( section, entry, def_val, "win.ini" );
1075 /***********************************************************************
1076 * GetProfileIntW (KERNEL32.@)
1078 UINT WINAPI GetProfileIntW( LPCWSTR section, LPCWSTR entry, INT def_val )
1080 return GetPrivateProfileIntW( section, entry, def_val, wininiW );
1083 /***********************************************************************
1084 * GetPrivateProfileStringW (KERNEL32.@)
1086 INT WINAPI GetPrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1087 LPCWSTR def_val, LPWSTR buffer,
1088 UINT len, LPCWSTR filename )
1090 int ret;
1091 LPWSTR defval_tmp = NULL;
1093 TRACE("%s,%s,%s,%p,%u,%s\n", debugstr_w(section), debugstr_w(entry),
1094 debugstr_w(def_val), buffer, len, debugstr_w(filename));
1096 /* strip any trailing ' ' of def_val. */
1097 if (def_val)
1099 LPCWSTR p = def_val + strlenW(def_val) - 1;
1101 while (p > def_val && *p == ' ')
1102 p--;
1104 if (p >= def_val)
1106 int vlen = (int)(p - def_val) + 1;
1108 defval_tmp = HeapAlloc(GetProcessHeap(), 0, (vlen + 1) * sizeof(WCHAR));
1109 memcpy(defval_tmp, def_val, vlen * sizeof(WCHAR));
1110 defval_tmp[vlen] = '\0';
1111 def_val = defval_tmp;
1115 RtlEnterCriticalSection( &PROFILE_CritSect );
1117 if (PROFILE_Open( filename, FALSE )) {
1118 if (section == NULL)
1119 ret = PROFILE_GetSectionNames(buffer, len);
1120 else
1121 /* PROFILE_GetString can handle the 'entry == NULL' case */
1122 ret = PROFILE_GetString( section, entry, def_val, buffer, len );
1123 } else if (buffer && def_val) {
1124 lstrcpynW( buffer, def_val, len );
1125 ret = strlenW( buffer );
1127 else
1128 ret = 0;
1130 RtlLeaveCriticalSection( &PROFILE_CritSect );
1132 HeapFree(GetProcessHeap(), 0, defval_tmp);
1134 TRACE("returning %s, %d\n", debugstr_w(buffer), ret);
1136 return ret;
1139 /***********************************************************************
1140 * GetPrivateProfileStringA (KERNEL32.@)
1142 INT WINAPI GetPrivateProfileStringA( LPCSTR section, LPCSTR entry,
1143 LPCSTR def_val, LPSTR buffer,
1144 UINT len, LPCSTR filename )
1146 UNICODE_STRING sectionW, entryW, def_valW, filenameW;
1147 LPWSTR bufferW;
1148 INT retW, ret = 0;
1150 bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)) : NULL;
1151 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1152 else sectionW.Buffer = NULL;
1153 if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1154 else entryW.Buffer = NULL;
1155 if (def_val) RtlCreateUnicodeStringFromAsciiz(&def_valW, def_val);
1156 else def_valW.Buffer = NULL;
1157 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1158 else filenameW.Buffer = NULL;
1160 retW = GetPrivateProfileStringW( sectionW.Buffer, entryW.Buffer,
1161 def_valW.Buffer, bufferW, len,
1162 filenameW.Buffer);
1163 if (len && buffer)
1165 if (retW)
1167 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW, buffer, len - 1, NULL, NULL);
1168 if (!ret)
1169 ret = len - 1;
1171 buffer[ret] = 0;
1174 RtlFreeUnicodeString(&sectionW);
1175 RtlFreeUnicodeString(&entryW);
1176 RtlFreeUnicodeString(&def_valW);
1177 RtlFreeUnicodeString(&filenameW);
1178 HeapFree(GetProcessHeap(), 0, bufferW);
1179 return ret;
1182 /***********************************************************************
1183 * GetProfileStringA (KERNEL32.@)
1185 INT WINAPI GetProfileStringA( LPCSTR section, LPCSTR entry, LPCSTR def_val,
1186 LPSTR buffer, UINT len )
1188 return GetPrivateProfileStringA( section, entry, def_val,
1189 buffer, len, "win.ini" );
1192 /***********************************************************************
1193 * GetProfileStringW (KERNEL32.@)
1195 INT WINAPI GetProfileStringW( LPCWSTR section, LPCWSTR entry,
1196 LPCWSTR def_val, LPWSTR buffer, UINT len )
1198 return GetPrivateProfileStringW( section, entry, def_val,
1199 buffer, len, wininiW );
1202 /***********************************************************************
1203 * WriteProfileStringA (KERNEL32.@)
1205 BOOL WINAPI WriteProfileStringA( LPCSTR section, LPCSTR entry,
1206 LPCSTR string )
1208 return WritePrivateProfileStringA( section, entry, string, "win.ini" );
1211 /***********************************************************************
1212 * WriteProfileStringW (KERNEL32.@)
1214 BOOL WINAPI WriteProfileStringW( LPCWSTR section, LPCWSTR entry,
1215 LPCWSTR string )
1217 return WritePrivateProfileStringW( section, entry, string, wininiW );
1221 /***********************************************************************
1222 * GetPrivateProfileIntW (KERNEL32.@)
1224 UINT WINAPI GetPrivateProfileIntW( LPCWSTR section, LPCWSTR entry,
1225 INT def_val, LPCWSTR filename )
1227 WCHAR buffer[30];
1228 UNICODE_STRING bufferW;
1229 ULONG result;
1231 if (GetPrivateProfileStringW( section, entry, emptystringW, buffer, ARRAY_SIZE( buffer ),
1232 filename ) == 0)
1233 return def_val;
1235 /* FIXME: if entry can be found but it's empty, then Win16 is
1236 * supposed to return 0 instead of def_val ! Difficult/problematic
1237 * to implement (every other failure also returns zero buffer),
1238 * thus wait until testing framework avail for making sure nothing
1239 * else gets broken that way. */
1240 if (!buffer[0]) return (UINT)def_val;
1242 RtlInitUnicodeString( &bufferW, buffer );
1243 RtlUnicodeStringToInteger( &bufferW, 0, &result);
1244 return result;
1247 /***********************************************************************
1248 * GetPrivateProfileIntA (KERNEL32.@)
1250 * FIXME: rewrite using unicode
1252 UINT WINAPI GetPrivateProfileIntA( LPCSTR section, LPCSTR entry,
1253 INT def_val, LPCSTR filename )
1255 UNICODE_STRING entryW, filenameW, sectionW;
1256 UINT res;
1257 if(entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1258 else entryW.Buffer = NULL;
1259 if(filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1260 else filenameW.Buffer = NULL;
1261 if(section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1262 else sectionW.Buffer = NULL;
1263 res = GetPrivateProfileIntW(sectionW.Buffer, entryW.Buffer, def_val,
1264 filenameW.Buffer);
1265 RtlFreeUnicodeString(&sectionW);
1266 RtlFreeUnicodeString(&filenameW);
1267 RtlFreeUnicodeString(&entryW);
1268 return res;
1271 /***********************************************************************
1272 * GetPrivateProfileSectionW (KERNEL32.@)
1274 INT WINAPI GetPrivateProfileSectionW( LPCWSTR section, LPWSTR buffer,
1275 DWORD len, LPCWSTR filename )
1277 int ret = 0;
1279 if (!section || !buffer)
1281 SetLastError(ERROR_INVALID_PARAMETER);
1282 return 0;
1285 TRACE("(%s, %p, %d, %s)\n", debugstr_w(section), buffer, len, debugstr_w(filename));
1287 RtlEnterCriticalSection( &PROFILE_CritSect );
1289 if (PROFILE_Open( filename, FALSE ))
1290 ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, TRUE);
1292 RtlLeaveCriticalSection( &PROFILE_CritSect );
1294 return ret;
1297 /***********************************************************************
1298 * GetPrivateProfileSectionA (KERNEL32.@)
1300 INT WINAPI GetPrivateProfileSectionA( LPCSTR section, LPSTR buffer,
1301 DWORD len, LPCSTR filename )
1303 UNICODE_STRING sectionW, filenameW;
1304 LPWSTR bufferW;
1305 INT retW, ret = 0;
1307 if (!section || !buffer)
1309 SetLastError(ERROR_INVALID_PARAMETER);
1310 return 0;
1313 bufferW = HeapAlloc(GetProcessHeap(), 0, len * 2 * sizeof(WCHAR));
1314 RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1315 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1316 else filenameW.Buffer = NULL;
1318 retW = GetPrivateProfileSectionW(sectionW.Buffer, bufferW, len * 2, filenameW.Buffer);
1319 if (retW)
1321 if (retW == len * 2 - 2) retW++; /* overflow */
1322 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW + 1, buffer, len, NULL, NULL);
1323 if (!ret || ret == len) /* overflow */
1325 ret = len - 2;
1326 buffer[len-2] = 0;
1327 buffer[len-1] = 0;
1329 else ret--;
1331 else
1333 buffer[0] = 0;
1334 buffer[1] = 0;
1337 RtlFreeUnicodeString(&sectionW);
1338 RtlFreeUnicodeString(&filenameW);
1339 HeapFree(GetProcessHeap(), 0, bufferW);
1340 return ret;
1343 /***********************************************************************
1344 * GetProfileSectionA (KERNEL32.@)
1346 INT WINAPI GetProfileSectionA( LPCSTR section, LPSTR buffer, DWORD len )
1348 return GetPrivateProfileSectionA( section, buffer, len, "win.ini" );
1351 /***********************************************************************
1352 * GetProfileSectionW (KERNEL32.@)
1354 INT WINAPI GetProfileSectionW( LPCWSTR section, LPWSTR buffer, DWORD len )
1356 return GetPrivateProfileSectionW( section, buffer, len, wininiW );
1360 /***********************************************************************
1361 * WritePrivateProfileStringW (KERNEL32.@)
1363 BOOL WINAPI WritePrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1364 LPCWSTR string, LPCWSTR filename )
1366 BOOL ret = FALSE;
1368 RtlEnterCriticalSection( &PROFILE_CritSect );
1370 if (!section && !entry && !string) /* documented "file flush" case */
1372 if (!filename || PROFILE_Open( filename, TRUE ))
1374 if (CurProfile) PROFILE_ReleaseFile(); /* always return FALSE in this case */
1377 else if (PROFILE_Open( filename, TRUE ))
1379 if (!section) {
1380 SetLastError(ERROR_FILE_NOT_FOUND);
1381 } else {
1382 ret = PROFILE_SetString( section, entry, string, FALSE);
1383 if (ret) ret = PROFILE_FlushFile();
1387 RtlLeaveCriticalSection( &PROFILE_CritSect );
1388 return ret;
1391 /***********************************************************************
1392 * WritePrivateProfileStringA (KERNEL32.@)
1394 BOOL WINAPI DECLSPEC_HOTPATCH WritePrivateProfileStringA( LPCSTR section, LPCSTR entry,
1395 LPCSTR string, LPCSTR filename )
1397 UNICODE_STRING sectionW, entryW, stringW, filenameW;
1398 BOOL ret;
1400 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1401 else sectionW.Buffer = NULL;
1402 if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1403 else entryW.Buffer = NULL;
1404 if (string) RtlCreateUnicodeStringFromAsciiz(&stringW, string);
1405 else stringW.Buffer = NULL;
1406 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1407 else filenameW.Buffer = NULL;
1409 ret = WritePrivateProfileStringW(sectionW.Buffer, entryW.Buffer,
1410 stringW.Buffer, filenameW.Buffer);
1411 RtlFreeUnicodeString(&sectionW);
1412 RtlFreeUnicodeString(&entryW);
1413 RtlFreeUnicodeString(&stringW);
1414 RtlFreeUnicodeString(&filenameW);
1415 return ret;
1418 /***********************************************************************
1419 * WritePrivateProfileSectionW (KERNEL32.@)
1421 BOOL WINAPI WritePrivateProfileSectionW( LPCWSTR section,
1422 LPCWSTR string, LPCWSTR filename )
1424 BOOL ret = FALSE;
1425 LPWSTR p;
1427 RtlEnterCriticalSection( &PROFILE_CritSect );
1429 if (!section && !string)
1431 if (!filename || PROFILE_Open( filename, TRUE ))
1433 if (CurProfile) PROFILE_ReleaseFile(); /* always return FALSE in this case */
1436 else if (PROFILE_Open( filename, TRUE )) {
1437 if (!string) {/* delete the named section*/
1438 ret = PROFILE_SetString(section,NULL,NULL, FALSE);
1439 } else {
1440 PROFILE_DeleteAllKeys(section);
1441 ret = TRUE;
1442 while(*string && ret) {
1443 LPWSTR buf = HeapAlloc( GetProcessHeap(), 0, (strlenW(string)+1) * sizeof(WCHAR) );
1444 strcpyW( buf, string );
1445 if((p = strchrW( buf, '='))) {
1446 *p='\0';
1447 ret = PROFILE_SetString( section, buf, p+1, TRUE);
1449 HeapFree( GetProcessHeap(), 0, buf );
1450 string += strlenW(string)+1;
1453 if (ret) ret = PROFILE_FlushFile();
1456 RtlLeaveCriticalSection( &PROFILE_CritSect );
1457 return ret;
1460 /***********************************************************************
1461 * WritePrivateProfileSectionA (KERNEL32.@)
1463 BOOL WINAPI WritePrivateProfileSectionA( LPCSTR section,
1464 LPCSTR string, LPCSTR filename)
1467 UNICODE_STRING sectionW, filenameW;
1468 LPWSTR stringW;
1469 BOOL ret;
1471 if (string)
1473 INT lenA, lenW;
1474 LPCSTR p = string;
1476 while(*p) p += strlen(p) + 1;
1477 lenA = p - string + 1;
1478 lenW = MultiByteToWideChar(CP_ACP, 0, string, lenA, NULL, 0);
1479 if ((stringW = HeapAlloc(GetProcessHeap(), 0, lenW * sizeof(WCHAR))))
1480 MultiByteToWideChar(CP_ACP, 0, string, lenA, stringW, lenW);
1482 else stringW = NULL;
1483 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1484 else sectionW.Buffer = NULL;
1485 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1486 else filenameW.Buffer = NULL;
1488 ret = WritePrivateProfileSectionW(sectionW.Buffer, stringW, filenameW.Buffer);
1490 HeapFree(GetProcessHeap(), 0, stringW);
1491 RtlFreeUnicodeString(&sectionW);
1492 RtlFreeUnicodeString(&filenameW);
1493 return ret;
1496 /***********************************************************************
1497 * WriteProfileSectionA (KERNEL32.@)
1499 BOOL WINAPI WriteProfileSectionA( LPCSTR section, LPCSTR keys_n_values)
1502 return WritePrivateProfileSectionA( section, keys_n_values, "win.ini");
1505 /***********************************************************************
1506 * WriteProfileSectionW (KERNEL32.@)
1508 BOOL WINAPI WriteProfileSectionW( LPCWSTR section, LPCWSTR keys_n_values)
1510 return WritePrivateProfileSectionW(section, keys_n_values, wininiW);
1514 /***********************************************************************
1515 * GetPrivateProfileSectionNamesW (KERNEL32.@)
1517 * Returns the section names contained in the specified file.
1518 * FIXME: Where do we find this file when the path is relative?
1519 * The section names are returned as a list of strings with an extra
1520 * '\0' to mark the end of the list. Except for that the behavior
1521 * depends on the Windows version.
1523 * Win95:
1524 * - if the buffer is 0 or 1 character long then it is as if it was of
1525 * infinite length.
1526 * - otherwise, if the buffer is too small only the section names that fit
1527 * are returned.
1528 * - note that this means if the buffer was too small to return even just
1529 * the first section name then a single '\0' will be returned.
1530 * - the return value is the number of characters written in the buffer,
1531 * except if the buffer was too small in which case len-2 is returned
1533 * Win2000:
1534 * - if the buffer is 0, 1 or 2 characters long then it is filled with
1535 * '\0' and the return value is 0
1536 * - otherwise if the buffer is too small then the first section name that
1537 * does not fit is truncated so that the string list can be terminated
1538 * correctly (double '\0')
1539 * - the return value is the number of characters written in the buffer
1540 * except for the trailing '\0'. If the buffer is too small, then the
1541 * return value is len-2
1542 * - Win2000 has a bug that triggers when the section names and the
1543 * trailing '\0' fit exactly in the buffer. In that case the trailing
1544 * '\0' is missing.
1546 * Wine implements the observed Win2000 behavior (except for the bug).
1548 * Note that when the buffer is big enough then the return value may be any
1549 * value between 1 and len-1 (or len in Win95), including len-2.
1551 DWORD WINAPI GetPrivateProfileSectionNamesW( LPWSTR buffer, DWORD size,
1552 LPCWSTR filename)
1554 DWORD ret = 0;
1556 RtlEnterCriticalSection( &PROFILE_CritSect );
1558 if (PROFILE_Open( filename, FALSE ))
1559 ret = PROFILE_GetSectionNames(buffer, size);
1561 RtlLeaveCriticalSection( &PROFILE_CritSect );
1563 return ret;
1567 /***********************************************************************
1568 * GetPrivateProfileSectionNamesA (KERNEL32.@)
1570 DWORD WINAPI GetPrivateProfileSectionNamesA( LPSTR buffer, DWORD size,
1571 LPCSTR filename)
1573 UNICODE_STRING filenameW;
1574 LPWSTR bufferW;
1575 INT retW, ret = 0;
1577 bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)) : NULL;
1578 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1579 else filenameW.Buffer = NULL;
1581 retW = GetPrivateProfileSectionNamesW(bufferW, size, filenameW.Buffer);
1582 if (retW && size)
1584 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW+1, buffer, size-1, NULL, NULL);
1585 if (!ret)
1587 ret = size-2;
1588 buffer[size-1] = 0;
1590 else
1591 ret = ret-1;
1593 else if(size)
1594 buffer[0] = '\0';
1596 RtlFreeUnicodeString(&filenameW);
1597 HeapFree(GetProcessHeap(), 0, bufferW);
1598 return ret;
1601 static int get_hex_byte( const WCHAR *p )
1603 int val;
1605 if (*p >= '0' && *p <= '9') val = *p - '0';
1606 else if (*p >= 'A' && *p <= 'Z') val = *p - 'A' + 10;
1607 else if (*p >= 'a' && *p <= 'z') val = *p - 'a' + 10;
1608 else return -1;
1609 val <<= 4;
1610 p++;
1611 if (*p >= '0' && *p <= '9') val += *p - '0';
1612 else if (*p >= 'A' && *p <= 'Z') val += *p - 'A' + 10;
1613 else if (*p >= 'a' && *p <= 'z') val += *p - 'a' + 10;
1614 else return -1;
1615 return val;
1618 /***********************************************************************
1619 * GetPrivateProfileStructW (KERNEL32.@)
1621 * Should match Win95's behaviour pretty much
1623 BOOL WINAPI GetPrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1624 LPVOID buf, UINT len, LPCWSTR filename)
1626 BOOL ret = FALSE;
1627 LPBYTE data = buf;
1628 BYTE chksum = 0;
1629 int val;
1630 WCHAR *p, *buffer;
1632 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, (2 * len + 3) * sizeof(WCHAR) ))) return FALSE;
1634 if (GetPrivateProfileStringW( section, key, NULL, buffer, 2 * len + 3, filename ) != 2 * len + 2)
1635 goto done;
1637 for (p = buffer; len; p += 2, len--)
1639 if ((val = get_hex_byte( p )) == -1) goto done;
1640 *data++ = val;
1641 chksum += val;
1643 /* retrieve stored checksum value */
1644 if ((val = get_hex_byte( p )) == -1) goto done;
1645 ret = ((BYTE)val == chksum);
1647 done:
1648 HeapFree( GetProcessHeap(), 0, buffer );
1649 return ret;
1652 /***********************************************************************
1653 * GetPrivateProfileStructA (KERNEL32.@)
1655 BOOL WINAPI GetPrivateProfileStructA (LPCSTR section, LPCSTR key,
1656 LPVOID buffer, UINT len, LPCSTR filename)
1658 UNICODE_STRING sectionW, keyW, filenameW;
1659 INT ret;
1661 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1662 else sectionW.Buffer = NULL;
1663 if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1664 else keyW.Buffer = NULL;
1665 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1666 else filenameW.Buffer = NULL;
1668 ret = GetPrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buffer, len,
1669 filenameW.Buffer);
1670 /* Do not translate binary data. */
1672 RtlFreeUnicodeString(&sectionW);
1673 RtlFreeUnicodeString(&keyW);
1674 RtlFreeUnicodeString(&filenameW);
1675 return ret;
1680 /***********************************************************************
1681 * WritePrivateProfileStructW (KERNEL32.@)
1683 BOOL WINAPI WritePrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1684 LPVOID buf, UINT bufsize, LPCWSTR filename)
1686 BOOL ret = FALSE;
1687 LPBYTE binbuf;
1688 LPWSTR outstring, p;
1689 DWORD sum = 0;
1691 if (!section && !key && !buf) /* flush the cache */
1692 return WritePrivateProfileStringW( NULL, NULL, NULL, filename );
1694 /* allocate string buffer for hex chars + checksum hex char + '\0' */
1695 outstring = HeapAlloc( GetProcessHeap(), 0, (bufsize*2 + 2 + 1) * sizeof(WCHAR) );
1696 p = outstring;
1697 for (binbuf = (LPBYTE)buf; binbuf < (LPBYTE)buf+bufsize; binbuf++) {
1698 *p++ = hex[*binbuf >> 4];
1699 *p++ = hex[*binbuf & 0xf];
1700 sum += *binbuf;
1702 /* checksum is sum & 0xff */
1703 *p++ = hex[(sum & 0xf0) >> 4];
1704 *p++ = hex[sum & 0xf];
1705 *p++ = '\0';
1707 ret = WritePrivateProfileStringW( section, key, outstring, filename );
1708 HeapFree( GetProcessHeap(), 0, outstring );
1709 return ret;
1712 /***********************************************************************
1713 * WritePrivateProfileStructA (KERNEL32.@)
1715 BOOL WINAPI WritePrivateProfileStructA (LPCSTR section, LPCSTR key,
1716 LPVOID buf, UINT bufsize, LPCSTR filename)
1718 UNICODE_STRING sectionW, keyW, filenameW;
1719 INT ret;
1721 if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1722 else sectionW.Buffer = NULL;
1723 if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1724 else keyW.Buffer = NULL;
1725 if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1726 else filenameW.Buffer = NULL;
1728 /* Do not translate binary data. */
1729 ret = WritePrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buf, bufsize,
1730 filenameW.Buffer);
1732 RtlFreeUnicodeString(&sectionW);
1733 RtlFreeUnicodeString(&keyW);
1734 RtlFreeUnicodeString(&filenameW);
1735 return ret;
1739 /***********************************************************************
1740 * OpenProfileUserMapping (KERNEL32.@)
1742 BOOL WINAPI OpenProfileUserMapping(void) {
1743 FIXME("(), stub!\n");
1744 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1745 return FALSE;
1748 /***********************************************************************
1749 * CloseProfileUserMapping (KERNEL32.@)
1751 BOOL WINAPI CloseProfileUserMapping(void) {
1752 FIXME("(), stub!\n");
1753 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1754 return FALSE;