shlwapi: Implement SHSendMessageBroadcastA/W.
[wine] / dlls / msi / format.c
index 373e425..454142a 100644 (file)
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
-http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/msiformatrecord.asp 
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  */
 
 #include <stdarg.h>
@@ -33,566 +29,855 @@ http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/msifo
 #include "winerror.h"
 #include "wine/debug.h"
 #include "msi.h"
-#include "msipriv.h"
 #include "winnls.h"
+#include "objbase.h"
+#include "oleauto.h"
+
+#include "msipriv.h"
+#include "msiserver.h"
 #include "wine/unicode.h"
-#include "action.h"
 
 WINE_DEFAULT_DEBUG_CHANNEL(msi);
 
+/* types arranged by precedence */
+#define FORMAT_NULL         0x0001
+#define FORMAT_LITERAL      0x0002
+#define FORMAT_NUMBER       0x0004
+#define FORMAT_LBRACK       0x0010
+#define FORMAT_LBRACE       0x0020
+#define FORMAT_RBRACK       0x0011
+#define FORMAT_RBRACE       0x0021
+#define FORMAT_ESCAPE       0x0040
+#define FORMAT_PROPNULL     0x0080
+#define FORMAT_ERROR        0x1000
+#define FORMAT_FAIL         0x2000
+
+#define left_type(x) (x & 0xF0)
+
+typedef struct _tagFORMAT
+{
+    MSIPACKAGE *package;
+    MSIRECORD *record;
+    LPWSTR deformatted;
+    int len;
+    int n;
+    BOOL propfailed;
+    BOOL groupfailed;
+    int groups;
+} FORMAT;
+
+typedef struct _tagFORMSTR
+{
+    struct list entry;
+    int n;
+    int len;
+    int type;
+    BOOL propfound;
+    BOOL nonprop;
+} FORMSTR;
+
+typedef struct _tagSTACK
+{
+    struct list items;
+} STACK;
 
-static DWORD deformat_string_internal(MSIPACKAGE *package, LPCWSTR ptr, 
-                                     WCHAR** data, DWORD len, MSIRECORD* record,
-                                     BOOL* in_group);
+static STACK *create_stack(void)
+{
+    STACK *stack = msi_alloc(sizeof(STACK));
+    list_init(&stack->items);
+    return stack;
+}
+
+static void free_stack(STACK *stack)
+{
+    while (!list_empty(&stack->items))
+    {
+        FORMSTR *str = LIST_ENTRY(list_head(&stack->items), FORMSTR, entry);
+        list_remove(&str->entry);
+        msi_free(str);
+    }
 
+    msi_free(stack);
+}
 
-static LPWSTR build_default_format(MSIRECORD* record)
+static void stack_push(STACK *stack, FORMSTR *str)
 {
-    int i;  
-    int count;
-    LPWSTR rc;
-    static const WCHAR fmt[] = {'%','i',':',' ','[','%','i',']',' ',0};
-    WCHAR buf[11];
+    list_add_head(&stack->items, &str->entry);
+}
 
-    count = MSI_RecordGetFieldCount(record);
+static FORMSTR *stack_pop(STACK *stack)
+{
+    FORMSTR *ret;
 
-    rc = HeapAlloc(GetProcessHeap(),0,(11*count)*sizeof(WCHAR));
-    rc[0] = 0;
-    for (i = 1; i <= count; i++)
+    if (list_empty(&stack->items))
+        return NULL;
+
+    ret = LIST_ENTRY(list_head(&stack->items), FORMSTR, entry);
+    list_remove(&ret->entry);
+    return ret;
+}
+
+static FORMSTR *stack_find(STACK *stack, int type)
+{
+    FORMSTR *str;
+
+    LIST_FOR_EACH_ENTRY(str, &stack->items, FORMSTR, entry)
     {
-        sprintfW(buf,fmt,i,i); 
-        strcatW(rc,buf);
+        if (str->type == type)
+            return str;
     }
-    return rc;
+
+    return NULL;
 }
 
-static const WCHAR* scanW(LPCWSTR buf, WCHAR token, DWORD len)
+static FORMSTR *stack_peek(STACK *stack)
 {
-    DWORD i;
-    for (i = 0; i < len; i++)
-        if (buf[i] == token)
-            return &buf[i];
-    return NULL;
+    return LIST_ENTRY(list_head(&stack->items), FORMSTR, entry);
 }
 
-/* break out helper functions for deformating */
-static LPWSTR deformat_component(MSIPACKAGE* package, LPCWSTR key, DWORD* sz)
+static LPCWSTR get_formstr_data(FORMAT *format, FORMSTR *str)
 {
-    LPWSTR value = NULL;
-    MSICOMPONENT *comp;
+    return &format->deformatted[str->n];
+}
 
-    *sz = 0;
-    if (!package)
+static LPWSTR dup_formstr(FORMAT *format, FORMSTR *str)
+{
+    LPWSTR val;
+    LPCWSTR data;
+
+    if (str->len == 0)
         return NULL;
 
-    ERR("POORLY HANDLED DEFORMAT.. [$componentkey] \n");
-    comp = get_loaded_component(package,key);
-    if (comp)
+    val = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    data = get_formstr_data(format, str);
+    lstrcpynW(val, data, str->len + 1);
+
+    return val;
+}
+
+static LPWSTR deformat_index(FORMAT *format, FORMSTR *str)
+{
+    LPWSTR val, ret;
+
+    val = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    lstrcpynW(val, get_formstr_data(format, str), str->len + 1);
+
+    ret = msi_dup_record_field(format->record, atoiW(val));
+
+    msi_free(val);
+    return ret;
+}
+
+static LPWSTR deformat_property(FORMAT *format, FORMSTR *str)
+{
+    LPWSTR val, ret;
+
+    val = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    lstrcpynW(val, get_formstr_data(format, str), str->len + 1);
+
+    ret = msi_dup_property(format->package, val);
+
+    msi_free(val);
+    return ret;
+}
+
+static LPWSTR deformat_component(FORMAT *format, FORMSTR *str)
+{
+    LPWSTR key, ret = NULL;
+    MSICOMPONENT *comp;
+    BOOL source;
+
+    key = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    lstrcpynW(key, get_formstr_data(format, str), str->len + 1);
+
+    comp = get_loaded_component(format->package, key);
+    if (!comp)
+        goto done;
+
+    source = (comp->Action == INSTALLSTATE_SOURCE) ? TRUE : FALSE;
+    ret = resolve_folder(format->package, comp->Directory, source, FALSE, TRUE, NULL);
+
+done:
+    msi_free(key);
+    return ret;
+}
+
+static LPWSTR deformat_file(FORMAT *format, FORMSTR *str, BOOL shortname)
+{
+    LPWSTR key, ret = NULL;
+    MSIFILE *file;
+    DWORD size;
+
+    key = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    lstrcpynW(key, get_formstr_data(format, str), str->len + 1);
+
+    file = get_loaded_file(format->package, key);
+    if (!file)
+        goto done;
+
+    if (!shortname)
     {
-        value = resolve_folder(package, comp->Directory, FALSE, FALSE, NULL);
-        *sz = (strlenW(value)) * sizeof(WCHAR);
+        ret = strdupW(file->TargetPath);
+        goto done;
     }
 
-    return value;
+    size = GetShortPathNameW(file->TargetPath, NULL, 0);
+    if (size <= 0)
+    {
+        ret = strdupW(file->TargetPath);
+        goto done;
+    }
+
+    size++;
+    ret = msi_alloc(size * sizeof(WCHAR));
+    GetShortPathNameW(file->TargetPath, ret, size);
+
+done:
+    msi_free(key);
+    return ret;
 }
 
-static LPWSTR deformat_file(MSIPACKAGE* package, LPCWSTR key, DWORD* sz, 
-                            BOOL shortname)
+static LPWSTR deformat_environment(FORMAT *format, FORMSTR *str)
 {
-    LPWSTR value = NULL;
-    INT index;
+    LPWSTR key, ret = NULL;
+    DWORD sz;
 
-    *sz = 0;
+    key = msi_alloc((str->len + 1) * sizeof(WCHAR));
+    lstrcpynW(key, get_formstr_data(format, str), str->len + 1);
 
-    if (!package)
-        return NULL;
+    sz  = GetEnvironmentVariableW(key, NULL ,0);
+    if (sz <= 0)
+        goto done;
 
-    index = get_loaded_file(package,key);
-    if (index >=0)
+    sz++;
+    ret = msi_alloc(sz * sizeof(WCHAR));
+    GetEnvironmentVariableW(key, ret, sz);
+
+done:
+    msi_free(key);
+    return ret;
+}
+
+static LPWSTR deformat_literal(FORMAT *format, FORMSTR *str, BOOL *propfound,
+                               BOOL *nonprop, int *type)
+{
+    LPCWSTR data = get_formstr_data(format, str);
+    LPWSTR replaced = NULL;
+    char ch = data[0];
+
+    if (ch == '\\')
     {
-        if (!shortname)
+        str->n++;
+        if (str->len == 1)
         {
-            value = strdupW(package->files[index].TargetPath);
-            *sz = (strlenW(value)) * sizeof(WCHAR);
+            str->len = 0;
+            replaced = NULL;
         }
         else
         {
-            DWORD size = 0;
-            size = GetShortPathNameW(package->files[index].TargetPath, NULL, 0);
-
-            if (size > 0)
-            {
-                *sz = (size-1) * sizeof (WCHAR);
-                size ++;
-                value = HeapAlloc(GetProcessHeap(),0,size * sizeof(WCHAR));
-                GetShortPathNameW(package->files[index].TargetPath, value, 
-                                  size);
-            }
-            else
-            {
-                ERR("Unable to get ShortPath size (%s)\n", 
-                                debugstr_w(package->files[index].TargetPath));
-                value = NULL;
-                *sz = 0;
-            }
+            str->len = 1;
+            replaced = dup_formstr(format, str);
         }
     }
+    else if (ch == '~')
+    {
+        if (str->len != 1)
+            replaced = NULL;
+        else
+        {
+            replaced = msi_alloc(sizeof(WCHAR));
+            *replaced = '\0';
+        }
+    }
+    else if (ch == '%' || ch == '#' || ch == '!' || ch == '$')
+    {
+        str->n++;
+        str->len--;
 
-    return value;
-}
-
-static LPWSTR deformat_environment(MSIPACKAGE* package, LPCWSTR key, 
-                                   DWORD* chunk)
-{
-    LPWSTR value = NULL;
-    DWORD sz;
+        switch (ch)
+        {
+        case '%':
+            replaced = deformat_environment(format, str); break;
+        case '#':
+            replaced = deformat_file(format, str, FALSE); break;
+        case '!':
+            replaced = deformat_file(format, str, TRUE); break;
+        case '$':
+            replaced = deformat_component(format, str); break;
+        }
 
-    sz  = GetEnvironmentVariableW(key,NULL,0);
-    if (sz > 0)
-    {
-        sz++;
-        value = HeapAlloc(GetProcessHeap(),0,sz * sizeof(WCHAR));
-        GetEnvironmentVariableW(&key[1],value,sz);
-        *chunk = (strlenW(value)) * sizeof(WCHAR);
+        *type = FORMAT_LITERAL;
     }
     else
     {
-        ERR("Unknown environment variable %s\n", debugstr_w(key));
-        *chunk = 0;
-        value = NULL;
+        replaced = deformat_property(format, str);
+        *type = FORMAT_LITERAL;
+
+        if (replaced)
+            *propfound = TRUE;
+        else
+            format->propfailed = TRUE;
     }
-    return value;
+
+    return replaced;
 }
 
-static LPWSTR deformat_NULL(DWORD* chunk)
+static LPWSTR build_default_format(const MSIRECORD* record)
 {
-    LPWSTR value;
+    int i;  
+    int count;
+    LPWSTR rc, buf;
+    static const WCHAR fmt[] = {'%','i',':',' ','%','s',' ',0};
+    static const WCHAR fmt_null[] = {'%','i',':',' ',' ',0};
+    static const WCHAR fmt_index[] = {'%','i',0};
+    LPCWSTR str;
+    WCHAR index[10];
+    DWORD size, max_len, len;
 
-    value = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*2);
-    value[0] =  0;
-    *chunk = sizeof(WCHAR);
-    return value;
-}
+    count = MSI_RecordGetFieldCount(record);
 
-static LPWSTR deformat_escape(LPCWSTR key, DWORD* chunk)
-{
-    LPWSTR value;
+    max_len = MAX_PATH;
+    buf = msi_alloc((max_len + 1) * sizeof(WCHAR));
 
-    value = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*2);
-    value[0] =  key[0];
-    *chunk = sizeof(WCHAR);
+    rc = NULL;
+    size = 1;
+    for (i = 1; i <= count; i++)
+    {
+        sprintfW(index, fmt_index, i);
+        str = MSI_RecordGetString(record, i);
+        len = (str) ? lstrlenW(str) : 0;
+        len += (sizeof(fmt_null)/sizeof(fmt_null[0]) - 3) + lstrlenW(index);
+        size += len;
 
-    return value;
+        if (len > max_len)
+        {
+            max_len = len;
+            buf = msi_realloc(buf, (max_len + 1) * sizeof(WCHAR));
+            if (!buf) return NULL;
+        }
+
+        if (str)
+            sprintfW(buf, fmt, i, str);
+        else
+            sprintfW(buf, fmt_null, i);
+
+        if (!rc)
+        {
+            rc = msi_alloc(size * sizeof(WCHAR));
+            lstrcpyW(rc, buf);
+        }
+        else
+        {
+            rc = msi_realloc(rc, size * sizeof(WCHAR));
+            lstrcatW(rc, buf);
+        }
+    }
+
+    msi_free(buf);
+    return rc;
 }
 
+static BOOL format_is_number(WCHAR x)
+{
+    return ((x >= '0') && (x <= '9'));
+}
 
-static BOOL is_key_number(LPCWSTR key)
+static BOOL format_str_is_number(LPWSTR str)
 {
-    INT index = 0;
-    if (key[0] == 0)
-        return FALSE;
+    LPWSTR ptr;
 
-    while (isdigitW(key[index])) index++;
-    if (key[index] == 0)
-        return TRUE;
-    else
-        return FALSE;
+    for (ptr = str; *ptr; ptr++)
+        if (!format_is_number(*ptr))
+            return FALSE;
+
+    return TRUE;
 }
 
-static LPWSTR deformat_index(MSIRECORD* record, LPCWSTR key, DWORD* chunk )
+static BOOL format_is_alpha(WCHAR x)
 {
-    INT index;
-    LPWSTR value; 
+    return (!format_is_number(x) && x != '\0' &&
+            x != '[' && x != ']' && x != '{' && x != '}');
+}
 
-    index = atoiW(key);
-    TRACE("record index %i\n",index);
-    value = load_dynamic_stringW(record,index);
-    if (value)
-        *chunk = strlenW(value) * sizeof(WCHAR);
-    else
-    {
-        value = NULL;
-        *chunk = 0;
-    }
-    return value;
+static BOOL format_is_literal(WCHAR x)
+{
+    return (format_is_alpha(x) || format_is_number(x));
 }
 
-static LPWSTR deformat_property(MSIPACKAGE* package, LPCWSTR key, DWORD* chunk)
+static int format_lex(FORMAT *format, FORMSTR **out)
 {
-    UINT rc;
-    LPWSTR value;
+    int type, len = 1;
+    FORMSTR *str;
+    LPCWSTR data;
+    WCHAR ch;
 
-    if (!package)
-        return NULL;
+    *out = NULL;
 
-    value = load_dynamic_property(package,key, &rc);
+    if (!format->deformatted)
+        return FORMAT_NULL;
 
-    if (rc == ERROR_SUCCESS)
-        *chunk = (strlenW(value)) * sizeof(WCHAR);
+    *out = msi_alloc_zero(sizeof(FORMSTR));
+    if (!*out)
+        return FORMAT_FAIL;
 
-    return value;
-}
+    str = *out;
+    str->n = format->n;
+    str->len = 1;
+    data = get_formstr_data(format, str);
 
-/*
- * Groups cannot be nested. They are just treated as from { to next } 
- */
-static BOOL find_next_group(LPCWSTR source, DWORD len_remaining,
-                                    LPWSTR *group, LPCWSTR *mark, 
-                                    LPCWSTR* mark2)
-{
-    int i;
-    BOOL found = FALSE;
+    ch = data[0];
+    switch (ch)
+    {
+        case '{': type = FORMAT_LBRACE; break;
+        case '}': type = FORMAT_RBRACE; break;
+        case '[': type = FORMAT_LBRACK; break;
+        case ']': type = FORMAT_RBRACK; break;
+        case '~': type = FORMAT_PROPNULL; break;
+        case '\0': type = FORMAT_NULL; break;
+
+        default:
+            type = 0;
+    }
 
-    *mark = scanW(source,'{',len_remaining);
-    if (!*mark)
-        return FALSE;
+    if (type)
+    {
+        str->type = type;
+        format->n++;
+        return type;
+    }
+
+    if (ch == '\\')
+    {
+        while (data[len] && data[len] != ']')
+            len++;
+
+        type = FORMAT_ESCAPE;
+    }
+    else if (format_is_alpha(ch))
+    {
+        while (format_is_literal(data[len]))
+            len++;
 
-    for (i = 1; (*mark - source) + i < len_remaining; i++)
+        type = FORMAT_LITERAL;
+    }
+    else if (format_is_number(ch))
     {
-        if ((*mark)[i] == '}')
+        while (format_is_number(data[len]))
+            len++;
+
+        type = FORMAT_NUMBER;
+
+        if (data[len] != ']')
         {
-            found = TRUE;
-            break;
+            while (format_is_literal(data[len]))
+                len++;
+
+            type = FORMAT_LITERAL;
         }
     }
-    if (! found)
-        return FALSE;
+    else
+    {
+        ERR("Got unknown character %c(%x)\n", ch, ch);
+        return FORMAT_ERROR;
+    }
 
-    *mark2 = &(*mark)[i]; 
+    format->n += len;
+    str->len = len;
+    str->type = type;
 
-    i = *mark2 - *mark;
-    *group = HeapAlloc(GetProcessHeap(),0,i*sizeof(WCHAR));
+    return type;
+}
 
-    i -= 1;
-    memcpy(*group,&(*mark)[1],i*sizeof(WCHAR));
-    (*group)[i] = 0;
+static FORMSTR *format_replace(FORMAT *format, BOOL propfound, BOOL nonprop,
+                               int oldsize, int type, LPWSTR replace)
+{
+    FORMSTR *ret;
+    LPWSTR str, ptr;
+    DWORD size = 0;
+    int n;
 
-    TRACE("Found group %s\n",debugstr_w(*group));
-    return TRUE;
-}
+    if (replace)
+    {
+        if (!*replace)
+            size = 1;
+        else
+            size = lstrlenW(replace);
+    }
 
+    size -= oldsize;
+    size = format->len + size + 1;
 
-static BOOL find_next_outermost_key(LPCWSTR source, DWORD len_remaining,
-                                    LPWSTR *key, LPCWSTR *mark, LPCWSTR* mark2, 
-                                    BOOL *nested)
-{
-    INT count = 0;
-    INT total_count = 0;
-    int i;
+    if (size <= 1)
+    {
+        msi_free(format->deformatted);
+        format->deformatted = NULL;
+        format->len = 0;
+        return NULL;
+    }
 
-    *mark = scanW(source,'[',len_remaining);
-    if (!*mark)
-        return FALSE;
+    str = msi_alloc(size * sizeof(WCHAR));
+    if (!str)
+        return NULL;
+
+    str[0] = '\0';
+    memcpy(str, format->deformatted, format->n * sizeof(WCHAR));
+    n = format->n;
 
-    count = 1;
-    total_count = 1;
-    *nested = FALSE;
-    for (i = 1; (*mark - source) + i < len_remaining && count > 0; i++)
+    if (replace)
     {
-        if ((*mark)[i] == '[' && (*mark)[i-1] != '\\')
+        if (!*replace)
         {
-            count ++;
-            total_count ++;
-            *nested = TRUE;
+            str[n] = '\0';
+            n++;
         }
-        else if ((*mark)[i] == ']' && (*mark)[i-1] != '\\')
+        else
         {
-            count --;
+            lstrcpyW(&str[n], replace);
+            n += lstrlenW(replace);
         }
     }
 
-    if (count > 0)
-        return FALSE;
+    ptr = &format->deformatted[format->n + oldsize];
+    memcpy(&str[n], ptr, (lstrlenW(ptr) + 1) * sizeof(WCHAR));
 
-    *mark2 = &(*mark)[i-1]; 
+    msi_free(format->deformatted);
+    format->deformatted = str;
+    format->len = size - 1;
 
-    i = *mark2 - *mark;
-    *key = HeapAlloc(GetProcessHeap(),0,i*sizeof(WCHAR));
-    /* do not have the [] in the key */
-    i -= 1;
-    memcpy(*key,&(*mark)[1],i*sizeof(WCHAR));
-    (*key)[i] = 0;
+    /* don't reformat the NULL */
+    if (replace && !*replace)
+        format->n++;
 
-    TRACE("Found Key %s\n",debugstr_w(*key));
-    return TRUE;
+    if (!replace)
+        return NULL;
+
+    ret = msi_alloc_zero(sizeof(FORMSTR));
+    if (!ret)
+        return NULL;
+
+    ret->len = lstrlenW(replace);
+    ret->type = type;
+    ret->n = format->n;
+    ret->propfound = propfound;
+    ret->nonprop = nonprop;
+
+    return ret;
 }
 
-static LPWSTR deformat_group(MSIPACKAGE* package, LPWSTR group, DWORD len, 
-                      MSIRECORD* record, DWORD* size)
+static LPWSTR replace_stack_group(FORMAT *format, STACK *values,
+                                  BOOL *propfound, BOOL *nonprop,
+                                  int *oldsize, int *type)
 {
-    LPWSTR value;
-    LPCWSTR mark, mark2;
-    LPWSTR key;
-    BOOL nested;
-    INT failcount;
-    static const WCHAR fmt[] = {'{','%','s','}',0};
-    UINT sz;
+    LPWSTR replaced = NULL;
+    FORMSTR *content;
+    FORMSTR *node;
+    int n;
+
+    *nonprop = FALSE;
+    *propfound = FALSE;
+
+    node = stack_pop(values);
+    n = node->n;
+    *oldsize = node->len;
+    msi_free(node);
+
+    while ((node = stack_pop(values)))
+    {
+        *oldsize += node->len;
+
+        if (node->nonprop)
+            *nonprop = TRUE;
+
+        if (node->propfound)
+            *propfound = TRUE;
 
-    if (!group || group[0] == 0) 
+        msi_free(node);
+    }
+
+    content = msi_alloc_zero(sizeof(FORMSTR));
+    content->n = n;
+    content->len = *oldsize;
+    content->type = FORMAT_LITERAL;
+
+    if (!format->groupfailed && (*oldsize == 2 ||
+        (format->propfailed && !*nonprop)))
     {
-        *size = 0;
+        msi_free(content);
         return NULL;
     }
-    /* if no [] then group is returned as is */
-
-     if (!find_next_outermost_key(group, len, &key, &mark, &mark2, &nested))
-     {
-         *size = (len+2)*sizeof(WCHAR);
-         value = HeapAlloc(GetProcessHeap(),0,*size);
-         sprintfW(value,fmt,group);
-         /* do not return size of the null at the end */
-         *size = (len+1)*sizeof(WCHAR);
-         return value;
-     }
-
-     HeapFree(GetProcessHeap(),0,key);
-     failcount = 0;
-     sz = deformat_string_internal(package, group, &value, strlenW(group),
-                                     record, &failcount);
-     if (failcount==0)
-     {
-        *size = sz * sizeof(WCHAR);
-        return value;
-     }
-     else if (failcount < 0)
-     {
-         LPWSTR v2;
-
-         v2 = HeapAlloc(GetProcessHeap(),0,(sz+2)*sizeof(WCHAR));
-         v2[0] = '{';
-         memcpy(&v2[1],value,sz*sizeof(WCHAR));
-         v2[sz+1]='}';
-         HeapFree(GetProcessHeap(),0,value);
-
-         *size = (sz+2)*sizeof(WCHAR);
-         return v2;
-     }
-     else
-     {
-         *size = 0;
-         return NULL;
-     }
+    else if (format->deformatted[content->n + 1] == '{' &&
+             format->deformatted[content->n + content->len - 2] == '}')
+    {
+        format->groupfailed = FALSE;
+        content->len = 0;
+    }
+    else if (*propfound && !*nonprop &&
+             !format->groupfailed && format->groups == 0)
+    {
+        content->n++;
+        content->len -= 2;
+    }
+    else
+    {
+        if (format->groups != 0)
+            format->groupfailed = TRUE;
+
+        *nonprop = TRUE;
+    }
+
+    replaced = dup_formstr(format, content);
+    *type = content->type;
+    msi_free(content);
+
+    if (format->groups == 0)
+        format->propfailed = FALSE;
+
+    return replaced;
 }
 
+static LPWSTR replace_stack_prop(FORMAT *format, STACK *values,
+                                 BOOL *propfound, BOOL *nonprop,
+                                 int *oldsize, int *type)
+{
+    LPWSTR replaced = NULL;
+    FORMSTR *content;
+    FORMSTR *node;
+    int n;
 
-/*
- * len is in WCHARs
- * return is also in WCHARs
- */
-static DWORD deformat_string_internal(MSIPACKAGE *package, LPCWSTR ptr, 
-                                     WCHAR** data, DWORD len, MSIRECORD* record,
-                                     INT* failcount)
-{
-    LPCWSTR mark = NULL;
-    LPCWSTR mark2 = NULL;
-    DWORD size=0;
-    DWORD chunk=0;
-    LPWSTR key;
-    LPWSTR value = NULL;
-    DWORD sz;
-    LPBYTE newdata = NULL;
-    const WCHAR* progress = NULL;
-    BOOL nested;
+    *propfound = FALSE;
+    *nonprop = FALSE;
 
-    if (ptr==NULL)
+    node = stack_pop(values);
+    n = node->n;
+    *oldsize = node->len;
+    *type = stack_peek(values)->type;
+    msi_free(node);
+
+    while ((node = stack_pop(values)))
     {
-        TRACE("Deformatting NULL string\n");
-        *data = NULL;
-        return 0;
+        *oldsize += node->len;
+
+        if (*type != FORMAT_ESCAPE &&
+            stack_peek(values) && node->type != *type)
+            *type = FORMAT_LITERAL;
+
+        msi_free(node);
     }
 
-    TRACE("Starting with %s\n",debugstr_wn(ptr,len));
+    content = msi_alloc_zero(sizeof(FORMSTR));
+    content->n = n + 1;
+    content->len = *oldsize - 2;
+    content->type = *type;
+
+    if (*type == FORMAT_NUMBER)
+    {
+        replaced = deformat_index(format, content);
+        if (replaced)
+            *propfound = TRUE;
+        else
+            format->propfailed = TRUE;
 
-    /* scan for special characters... fast exit */
-    if ((!scanW(ptr,'[',len) || (scanW(ptr,'[',len) && !scanW(ptr,']',len))) && 
-        (scanW(ptr,'{',len) && !scanW(ptr,'}',len)))
+        if (replaced)
+            *type = format_str_is_number(replaced) ?
+                FORMAT_NUMBER : FORMAT_LITERAL;
+    }
+    else if (format->package)
     {
-        /* not formatted */
-        *data = HeapAlloc(GetProcessHeap(),0,(len*sizeof(WCHAR)));
-        memcpy(*data,ptr,len*sizeof(WCHAR));
-        TRACE("Returning %s\n",debugstr_wn(*data,len));
-        return len;
+        replaced = deformat_literal(format, content, propfound, nonprop, type);
     }
-  
-    progress = ptr;
+    else
+    {
+        *nonprop = TRUE;
+        content->n--;
+        content->len += 2;
+        replaced = dup_formstr(format, content);
+    }
+
+    msi_free(content);
+    return replaced;
+}
 
-    while (progress - ptr < len)
+static UINT replace_stack(FORMAT *format, STACK *stack, STACK *values)
+{
+    LPWSTR replaced = NULL;
+    FORMSTR *beg;
+    FORMSTR *top;
+    FORMSTR *node;
+    BOOL propfound = FALSE;
+    BOOL nonprop = FALSE;
+    BOOL group = FALSE;
+    int oldsize = 0;
+    int type, n;
+
+    node = stack_peek(values);
+    type = node->type;
+    n = node->n;
+
+    if (type == FORMAT_LBRACK)
+        replaced = replace_stack_prop(format, values, &propfound,
+                                      &nonprop, &oldsize, &type);
+    else if (type == FORMAT_LBRACE)
     {
-        /* seek out first group if existing */
-        if (find_next_group(progress, len - (progress - ptr), &key,
-                                &mark, &mark2))
-        {
-            value = deformat_group(package, key, strlenW(key)+1, record, 
-                            &chunk);
-            key = NULL;
-            nested = FALSE;
-        }
-        /* formatted string located */
-        else if (!find_next_outermost_key(progress, len - (progress - ptr), 
-                                &key, &mark, &mark2, &nested))
-        {
-            LPBYTE nd2;
-
-            TRACE("after value %s \n",debugstr_wn((LPWSTR)newdata,
-                                    size/sizeof(WCHAR)));
-            chunk = (len - (progress - ptr)) * sizeof(WCHAR);
-            TRACE("after chunk is %li + %li\n",size,chunk);
-            if (size)
-                nd2 = HeapReAlloc(GetProcessHeap(),0,newdata,(size+chunk));
-            else
-                nd2 = HeapAlloc(GetProcessHeap(),0,chunk);
-
-            newdata = nd2;
-            memcpy(&newdata[size],progress,chunk);
-            size+=chunk;
-            break;
-        }
+        replaced = replace_stack_group(format, values, &propfound,
+                                       &nonprop, &oldsize, &type);
+        group = TRUE;
+    }
 
-        if (mark != progress)
-        {
-            LPBYTE tgt;
-            DWORD old_size = size;
-            INT cnt = (mark - progress);
-            TRACE("%i  (%i) characters before marker\n",cnt,(mark-progress));
-            size += cnt * sizeof(WCHAR);
-            if (!old_size)
-                tgt = HeapAlloc(GetProcessHeap(),0,size);
-            else
-                tgt = HeapReAlloc(GetProcessHeap(),0,newdata,size);
-            newdata  = tgt;
-            memcpy(&newdata[old_size],progress,(cnt * sizeof(WCHAR)));  
-        }
+    format->n = n;
+    beg = format_replace(format, propfound, nonprop, oldsize, type, replaced);
+    if (!beg)
+        return ERROR_SUCCESS;
 
-        progress = mark;
+    msi_free(replaced);
+    format->n = beg->n + beg->len;
+
+    top = stack_peek(stack);
+    if (top)
+    {
+        type = top->type;
 
-        if (nested)
+        if ((type == FORMAT_LITERAL || type == FORMAT_NUMBER) &&
+            type == beg->type)
         {
-            TRACE("Nested key... %s\n",debugstr_w(key));
-            deformat_string_internal(package, key, &value, strlenW(key)+1,
-                                     record, failcount);
+            top->len += beg->len;
 
-            HeapFree(GetProcessHeap(),0,key);
-            key = value;
+            if (group)
+                top->nonprop = FALSE;
+
+            if (type == FORMAT_LITERAL)
+                top->nonprop = beg->nonprop;
+
+            if (beg->propfound)
+                top->propfound = TRUE;
+
+            msi_free(beg);
+            return ERROR_SUCCESS;
         }
+    }
+
+    stack_push(stack, beg);
+    return ERROR_SUCCESS;
+}
+
+static BOOL verify_format(LPWSTR data)
+{
+    int count = 0;
+
+    while (*data)
+    {
+        if (*data == '[' && *(data - 1) != '\\')
+            count++;
+        else if (*data == ']')
+            count--;
 
-        TRACE("Current %s .. %s\n",debugstr_wn((LPWSTR)newdata, 
-                                size/sizeof(WCHAR)),debugstr_w(key));
+        data++;
+    }
+
+    if (count > 0)
+        return FALSE;
+
+    return TRUE;
+}
+
+static DWORD deformat_string_internal(MSIPACKAGE *package, LPCWSTR ptr, 
+                                      WCHAR** data, DWORD *len,
+                                      MSIRECORD* record, INT* failcount)
+{
+    FORMAT format;
+    FORMSTR *str = NULL;
+    STACK *stack, *temp;
+    FORMSTR *node;
+    int type;
 
-        if (!package)
+    if (!ptr)
+    {
+        *data = NULL;
+        *len = 0;
+        return ERROR_SUCCESS;
+    }
+
+    *data = strdupW(ptr);
+    *len = lstrlenW(ptr);
+
+    ZeroMemory(&format, sizeof(FORMAT));
+    format.package = package;
+    format.record = record;
+    format.deformatted = *data;
+    format.len = *len;
+
+    stack = create_stack();
+    temp = create_stack();
+
+    if (!verify_format(*data))
+        return ERROR_SUCCESS;
+
+    while ((type = format_lex(&format, &str)) != FORMAT_NULL)
+    {
+        if (type == FORMAT_LBRACK || type == FORMAT_LBRACE ||
+            type == FORMAT_LITERAL || type == FORMAT_NUMBER ||
+            type == FORMAT_ESCAPE || type == FORMAT_PROPNULL)
         {
-            /* only deformat number indexs */
-            if (key && is_key_number(key))
+            if (type == FORMAT_LBRACE)
             {
-                value = deformat_index(record,key,&chunk);  
-                if (!chunk && failcount && *failcount >= 0)
-                    (*failcount)++;
+                format.propfailed = FALSE;
+                format.groups++;
             }
-            else
+            else if (type == FORMAT_ESCAPE &&
+                     !stack_find(stack, FORMAT_LBRACK))
             {
-                if (failcount)
-                    *failcount = -1;
-                if(key)
-                {
-                    DWORD keylen = strlenW(key);
-                    chunk = (keylen + 2)*sizeof(WCHAR);
-                    value = HeapAlloc(GetProcessHeap(),0,chunk);
-                    value[0] = '[';
-                    memcpy(&value[1],key,keylen*sizeof(WCHAR));
-                    value[1+keylen] = ']';
-                }
+                format.n -= str->len - 1;
+                str->len = 1;
             }
+
+            stack_push(stack, str);
         }
-        else
+        else if (type == FORMAT_RBRACK || type == FORMAT_RBRACE)
         {
-            sz = 0;
-            if (key) switch (key[0])
-            {
-                case '~':
-                    value = deformat_NULL(&chunk);
-                break;
-                case '$':
-                    value = deformat_component(package,&key[1],&chunk);
-                break;
-                case '#':
-                    value = deformat_file(package,&key[1], &chunk, FALSE);
-                break;
-                case '!': /* should be short path */
-                    value = deformat_file(package,&key[1], &chunk, TRUE);
-                break;
-                case '\\':
-                    value = deformat_escape(&key[1],&chunk);
-                break;
-                case '%':
-                    value = deformat_environment(package,&key[1],&chunk);
-                break;
-                default:
-                    /* index keys cannot be nested */
-                    if (is_key_number(key))
-                        if (!nested)
-                            value = deformat_index(record,key,&chunk);
-                        else
-                        {
-                            static const WCHAR fmt[] = {'[','%','s',']',0};
-                            value = HeapAlloc(GetProcessHeap(),0,10);
-                            sprintfW(value,fmt,key);
-                            chunk = strlenW(value)*sizeof(WCHAR);
-                        }
-                    else
-                        value = deformat_property(package,key,&chunk);
-                break;      
-            }
-        }
+            if (type == FORMAT_RBRACE)
+                format.groups--;
 
-        HeapFree(GetProcessHeap(),0,key);
+            stack_push(stack, str);
 
-        if (value!=NULL)
-        {
-            LPBYTE nd2;
-            TRACE("value %s, chunk %li size %li\n",debugstr_w((LPWSTR)value),
-                    chunk, size);
-            if (size)
-                nd2= HeapReAlloc(GetProcessHeap(),0,newdata,(size + chunk));
-            else
-                nd2= HeapAlloc(GetProcessHeap(),0,chunk);
-            newdata = nd2;
-            memcpy(&newdata[size],value,chunk);
-            size+=chunk;   
-            HeapFree(GetProcessHeap(),0,value);
-        }
-        else if (failcount && *failcount >=0 )
-            (*failcount)++;
+            if (stack_find(stack, left_type(type)))
+            {
+                do
+                {
+                    node = stack_pop(stack);
+                    stack_push(temp, node);
+                } while (node->type != left_type(type));
 
-        progress = mark2+1;
+                replace_stack(&format, stack, temp);
+            }
+        }
     }
 
-    TRACE("after everything %s\n",debugstr_wn((LPWSTR)newdata, 
-                            size/sizeof(WCHAR)));
+    *data = format.deformatted;
+    *len = format.len;
 
-    *data = (LPWSTR)newdata;
-    return size / sizeof(WCHAR);
-}
+    msi_free(str);
+    free_stack(stack);
+    free_stack(temp);
 
+    return ERROR_SUCCESS;
+}
 
 UINT MSI_FormatRecordW( MSIPACKAGE* package, MSIRECORD* record, LPWSTR buffer,
-                        DWORD *size )
+                        LPDWORD size )
 {
     LPWSTR deformated;
     LPWSTR rec;
     DWORD len;
     UINT rc = ERROR_INVALID_PARAMETER;
 
-    TRACE("%p %p %p %li\n",package, record ,buffer, *size);
+    TRACE("%p %p %p %i\n", package, record ,buffer, *size);
 
-    rec = load_dynamic_stringW(record,0);
+    rec = msi_dup_record_field(record,0);
     if (!rec)
         rec = build_default_format(record);
 
     TRACE("(%s)\n",debugstr_w(rec));
 
-    len = deformat_string_internal(package,rec,&deformated,strlenW(rec),
-                                   record, NULL);
-
+    deformat_string_internal(package, rec, &deformated, &len, record, NULL);
     if (buffer)
     {
         if (*size>len)
@@ -616,64 +901,55 @@ UINT MSI_FormatRecordW( MSIPACKAGE* package, MSIRECORD* record, LPWSTR buffer,
 
     *size = len;
 
-    HeapFree(GetProcessHeap(),0,rec);
-    HeapFree(GetProcessHeap(),0,deformated);
+    msi_free(rec);
+    msi_free(deformated);
     return rc;
 }
 
-UINT MSI_FormatRecordA( MSIPACKAGE* package, MSIRECORD* record, LPSTR buffer,
-                        DWORD *size )
+UINT WINAPI MsiFormatRecordW( MSIHANDLE hInstall, MSIHANDLE hRecord, 
+                              LPWSTR szResult, LPDWORD sz )
 {
-    LPWSTR deformated;
-    LPWSTR rec;
-    DWORD len,lenA;
-    UINT rc = ERROR_INVALID_PARAMETER;
-
-    TRACE("%p %p %p %li\n",package, record ,buffer, *size);
-
-    rec = load_dynamic_stringW(record,0);
-    if (!rec)
-        rec = build_default_format(record);
-
-    TRACE("(%s)\n",debugstr_w(rec));
+    UINT r = ERROR_INVALID_HANDLE;
+    MSIPACKAGE *package;
+    MSIRECORD *record;
 
-    len = deformat_string_internal(package,rec,&deformated,strlenW(rec),
-                                   record, NULL);
-    lenA = WideCharToMultiByte(CP_ACP,0,deformated,len,NULL,0,NULL,NULL);
+    TRACE("%ld %ld %p %p\n", hInstall, hRecord, szResult, sz);
 
-    if (buffer)
+    package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
+    if (!package)
     {
-        WideCharToMultiByte(CP_ACP,0,deformated,len,buffer,*size,NULL, NULL);
-        if (*size>lenA)
-        {
-            rc = ERROR_SUCCESS;
-            buffer[lenA] = 0;
-        }
-        else
+        HRESULT hr;
+        IWineMsiRemotePackage *remote_package;
+        BSTR value = NULL;
+        awstring wstr;
+
+        remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
+        if (remote_package)
         {
-            rc = ERROR_MORE_DATA;
-            buffer[(*size)-1] = 0;    
-        }
-    }
-    else
-        rc = ERROR_SUCCESS;
+            hr = IWineMsiRemotePackage_FormatRecord( remote_package, hRecord,
+                                                     &value );
+            if (FAILED(hr))
+                goto done;
 
-    *size = lenA;
+            wstr.unicode = TRUE;
+            wstr.str.w = szResult;
+            r = msi_strcpy_to_awstring( value, &wstr, sz );
 
-    HeapFree(GetProcessHeap(),0,rec);
-    HeapFree(GetProcessHeap(),0,deformated);
-    return rc;
-}
+done:
+            IWineMsiRemotePackage_Release( remote_package );
+            SysFreeString( value );
 
+            if (FAILED(hr))
+            {
+                if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
+                    return HRESULT_CODE(hr);
 
-UINT WINAPI MsiFormatRecordW( MSIHANDLE hInstall, MSIHANDLE hRecord, 
-                              LPWSTR szResult, DWORD *sz )
-{
-    UINT r = ERROR_INVALID_HANDLE;
-    MSIPACKAGE *package;
-    MSIRECORD *record;
+                return ERROR_FUNCTION_FAILED;
+            }
 
-    TRACE("%ld %ld %p %p\n", hInstall, hRecord, szResult, sz);
+            return r;
+        }
+    }
 
     record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
 
@@ -688,8 +964,6 @@ UINT WINAPI MsiFormatRecordW( MSIHANDLE hInstall, MSIHANDLE hRecord,
             return ERROR_SUCCESS;
     }
 
-    package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
-
     r = MSI_FormatRecordW( package, record, szResult, sz );
     msiobj_release( &record->hdr );
     if (package)
@@ -698,32 +972,50 @@ UINT WINAPI MsiFormatRecordW( MSIHANDLE hInstall, MSIHANDLE hRecord,
 }
 
 UINT WINAPI MsiFormatRecordA( MSIHANDLE hInstall, MSIHANDLE hRecord,
-                              LPSTR szResult, DWORD *sz )
+                              LPSTR szResult, LPDWORD sz )
 {
-    UINT r = ERROR_INVALID_HANDLE;
-    MSIPACKAGE *package = NULL;
-    MSIRECORD *record = NULL;
+    UINT r;
+    DWORD len, save;
+    LPWSTR value;
 
     TRACE("%ld %ld %p %p\n", hInstall, hRecord, szResult, sz);
 
-    record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
-
-    if (!record)
+    if (!hRecord)
         return ERROR_INVALID_HANDLE;
+
     if (!sz)
     {
-        msiobj_release( &record->hdr );
         if (szResult)
             return ERROR_INVALID_PARAMETER;
         else
             return ERROR_SUCCESS;
     }
 
-    package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
+    r = MsiFormatRecordW( hInstall, hRecord, NULL, &len );
+    if (r != ERROR_SUCCESS)
+        return r;
 
-    r = MSI_FormatRecordA( package, record, szResult, sz );
-    msiobj_release( &record->hdr );
-    if (package)
-        msiobj_release( &package->hdr );
+    value = msi_alloc(++len * sizeof(WCHAR));
+    if (!value)
+        return ERROR_OUTOFMEMORY;
+
+    r = MsiFormatRecordW( hInstall, hRecord, value, &len );
+    if (r != ERROR_SUCCESS)
+        goto done;
+
+    save = len + 1;
+    len = WideCharToMultiByte(CP_ACP, 0, value, len + 1, NULL, 0, NULL, NULL);
+    WideCharToMultiByte(CP_ACP, 0, value, len, szResult, *sz, NULL, NULL);
+
+    if (szResult && len > *sz)
+    {
+        if (*sz) szResult[*sz - 1] = '\0';
+        r = ERROR_MORE_DATA;
+    }
+
+    *sz = save - 1;
+
+done:
+    msi_free(value);
     return r;
 }