dinput8: DirectInput8Create rewrite.
[wine] / dlls / oleaut32 / safearray.c
1 /*************************************************************************
2  * OLE Automation - SafeArray
3  *
4  * This file contains the implementation of the SafeArray functions.
5  *
6  * Copyright 1999 Sylvain St-Germain
7  * Copyright 2002-2003 Marcus Meissner
8  * Copyright 2003 Jon Griffiths
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 /* Memory Layout of a SafeArray:
25  *
26  * -0x10: start of memory.
27  * -0x10: GUID for VT_DISPATCH and VT_UNKNOWN safearrays (if FADF_HAVEIID)
28  * -0x04: DWORD varianttype; (for all others, except VT_RECORD) (if FADF_HAVEVARTYPE)
29  *  -0x4: IRecordInfo* iface;  (if FADF_RECORD, for VT_RECORD (can be NULL))
30  *  0x00: SAFEARRAY,
31  *  0x10: SAFEARRAYBOUNDS[0...]
32  */
33
34 #include "config.h"
35
36 #include <string.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39
40 #define COBJMACROS
41
42 #include "windef.h"
43 #include "winerror.h"
44 #include "winbase.h"
45 #include "variant.h"
46 #include "wine/debug.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(variant);
49
50 /************************************************************************
51  * SafeArray {OLEAUT32}
52  *
53  * NOTES
54  * The SafeArray data type provides the underlying interface for Ole
55  * Automations arrays, used for example to represent array types in
56  * Visual Basic(tm) and to gather user defined parameters for invocation through
57  * an IDispatch interface.
58  *
59  * Safe arrays provide bounds checking and automatically manage the data
60  * types they contain, for example handing reference counting and copying
61  * of interface pointers. User defined types can be stored in arrays
62  * using the IRecordInfo interface.
63  *
64  * There are two types of SafeArray, normal and vectors. Normal arrays can have
65  * multiple dimensions and the data for the array is allocated separately from
66  * the array header. This is the most flexible type of array. Vectors, on the
67  * other hand, are fixed in size and consist of a single allocated block, and a
68  * single dimension.
69  *
70  * DATATYPES
71  * The following types of data can be stored within a SafeArray.
72  * Numeric:
73  *|  VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_I8, VT_UI8, VT_INT, VT_UINT,
74  *|  VT_R4, VT_R8, VT_CY, VT_DECIMAL
75  * Interfaces:
76  *|  VT_DISPATCH, VT_UNKNOWN, VT_RECORD
77  * Other:
78  *|  VT_VARIANT, VT_INT_PTR, VT_UINT_PTR, VT_BOOL, VT_ERROR, VT_DATE, VT_BSTR
79  *
80  * FUNCTIONS
81  *  BstrFromVector()
82  *  VectorFromBstr()
83  */
84
85 /* Undocumented hidden space before the start of a SafeArray descriptor */
86 #define SAFEARRAY_HIDDEN_SIZE sizeof(GUID)
87
88 /* Allocate memory */
89 static inline LPVOID SAFEARRAY_Malloc(ULONG ulSize)
90 {
91   /* FIXME: Memory should be allocated and freed using a per-thread IMalloc
92    *        instance returned from CoGetMalloc().
93    */
94   return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulSize);
95 }
96
97 /* Free memory */
98 static inline BOOL SAFEARRAY_Free(LPVOID lpData)
99 {
100   return HeapFree(GetProcessHeap(), 0, lpData);
101 }
102
103 /* Get the size of a supported VT type (0 means unsupported) */
104 static DWORD SAFEARRAY_GetVTSize(VARTYPE vt)
105 {
106   switch (vt)
107   {
108     case VT_I1:
109     case VT_UI1:      return sizeof(BYTE);
110     case VT_BOOL:
111     case VT_I2:
112     case VT_UI2:      return sizeof(SHORT);
113     case VT_I4:
114     case VT_UI4:
115     case VT_R4:
116     case VT_ERROR:    return sizeof(LONG);
117     case VT_R8:
118     case VT_I8:
119     case VT_UI8:      return sizeof(LONG64);
120     case VT_INT:
121     case VT_UINT:     return sizeof(INT);
122     case VT_INT_PTR:
123     case VT_UINT_PTR: return sizeof(UINT_PTR);
124     case VT_CY:       return sizeof(CY);
125     case VT_DATE:     return sizeof(DATE);
126     case VT_BSTR:     return sizeof(BSTR);
127     case VT_DISPATCH: return sizeof(LPDISPATCH);
128     case VT_VARIANT:  return sizeof(VARIANT);
129     case VT_UNKNOWN:  return sizeof(LPUNKNOWN);
130     case VT_DECIMAL:  return sizeof(DECIMAL);
131     /* Note: Return a non-zero size to indicate vt is valid. The actual size
132      * of a UDT is taken from the result of IRecordInfo_GetSize().
133      */
134     case VT_RECORD:   return 32;
135   }
136   return 0;
137 }
138
139 /* Set the hidden data for an array */
140 static inline void SAFEARRAY_SetHiddenDWORD(SAFEARRAY* psa, DWORD dw)
141 {
142   /* Implementation data is stored in the 4 bytes before the header */
143   LPDWORD lpDw = (LPDWORD)psa;
144   lpDw[-1] = dw;
145 }
146
147 /* Get the hidden data from an array */
148 static inline DWORD SAFEARRAY_GetHiddenDWORD(SAFEARRAY* psa)
149 {
150   LPDWORD lpDw = (LPDWORD)psa;
151   return lpDw[-1];
152 }
153
154 /* Get the number of cells in a SafeArray */
155 static ULONG SAFEARRAY_GetCellCount(const SAFEARRAY *psa)
156 {
157   const SAFEARRAYBOUND* psab = psa->rgsabound;
158   USHORT cCount = psa->cDims;
159   ULONG ulNumCells = 1;
160
161   while (cCount--)
162   {
163     /* This is a valid bordercase. See testcases. -Marcus */
164     if (!psab->cElements)
165       return 0;
166     ulNumCells *= psab->cElements;
167     psab++;
168   }
169   return ulNumCells;
170 }
171
172 /* Allocate a descriptor for an array */
173 static HRESULT SAFEARRAY_AllocDescriptor(ULONG ulSize, SAFEARRAY **ppsaOut)
174 {
175   *ppsaOut = (SAFEARRAY*)((char*)SAFEARRAY_Malloc(ulSize + SAFEARRAY_HIDDEN_SIZE) + SAFEARRAY_HIDDEN_SIZE);
176
177   if (!*ppsaOut)
178     return E_UNEXPECTED;
179
180   return S_OK;
181 }
182
183 /* Set the features of an array */
184 static void SAFEARRAY_SetFeatures(VARTYPE vt, SAFEARRAY *psa)
185 {
186   /* Set the IID if we have one, otherwise set the type */
187   if (vt == VT_DISPATCH)
188   {
189     psa->fFeatures = FADF_HAVEIID;
190     SafeArraySetIID(psa, &IID_IDispatch);
191   }
192   else if (vt == VT_UNKNOWN)
193   {
194     psa->fFeatures = FADF_HAVEIID;
195     SafeArraySetIID(psa, &IID_IUnknown);
196   }
197   else if (vt == VT_RECORD)
198     psa->fFeatures = FADF_RECORD;
199   else
200   {
201     psa->fFeatures = FADF_HAVEVARTYPE;
202     SAFEARRAY_SetHiddenDWORD(psa, vt);
203   }
204 }
205
206 /* Create an array */
207 static SAFEARRAY* SAFEARRAY_Create(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, ULONG ulSize)
208 {
209   SAFEARRAY *psa = NULL;
210   int i;
211
212   if (!rgsabound)
213     return NULL;
214
215   if (SUCCEEDED(SafeArrayAllocDescriptorEx(vt, cDims, &psa)))
216   {
217     switch (vt)
218     {
219       case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
220       case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
221       case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
222       case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
223     }
224
225     for (i = 0; i < cDims; i++)
226       memcpy(psa->rgsabound + i, rgsabound + cDims - 1 - i, sizeof(SAFEARRAYBOUND));
227
228     if (ulSize)
229       psa->cbElements = ulSize;
230
231     if (FAILED(SafeArrayAllocData(psa)))
232     {
233       SafeArrayDestroyDescriptor(psa);
234       psa = NULL;
235     }
236   }
237   return psa;
238 }
239
240 /* Create an array as a vector */
241 static SAFEARRAY* SAFEARRAY_CreateVector(VARTYPE vt, LONG lLbound, ULONG cElements, ULONG ulSize)
242 {
243   SAFEARRAY *psa = NULL;
244
245   if (ulSize || (vt == VT_RECORD))
246   {
247     /* Allocate the header and data together */
248     if (SUCCEEDED(SAFEARRAY_AllocDescriptor(sizeof(SAFEARRAY) + ulSize * cElements, &psa)))
249     {
250       SAFEARRAY_SetFeatures(vt, psa);
251
252       psa->cDims = 1;
253       psa->fFeatures |= FADF_CREATEVECTOR;
254       psa->pvData = &psa[1]; /* Data follows the header */
255       psa->cbElements = ulSize;
256       psa->rgsabound[0].cElements = cElements;
257       psa->rgsabound[0].lLbound = lLbound;
258
259       switch (vt)
260       {
261         case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
262         case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
263         case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
264         case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
265       }
266     }
267   }
268   return psa;
269 }
270
271 /* Free data items in an array */
272 static HRESULT SAFEARRAY_DestroyData(SAFEARRAY *psa, ULONG ulStartCell)
273 {
274   if (psa->pvData && !(psa->fFeatures & FADF_DATADELETED))
275   {
276     ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
277
278     if (ulStartCell > ulCellCount) {
279       FIXME("unexpted ulcellcount %ld, start %ld\n",ulCellCount,ulStartCell);
280       return E_UNEXPECTED;
281     }
282
283     ulCellCount -= ulStartCell;
284
285     if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
286     {
287       LPUNKNOWN *lpUnknown = (LPUNKNOWN *)psa->pvData + ulStartCell;
288
289       while(ulCellCount--)
290       {
291         if (*lpUnknown)
292           IUnknown_Release(*lpUnknown);
293         lpUnknown++;
294       }
295     }
296     else if (psa->fFeatures & (FADF_RECORD))
297     {
298       IRecordInfo *lpRecInfo;
299
300       if (SUCCEEDED(SafeArrayGetRecordInfo(psa, &lpRecInfo)))
301       {
302         PBYTE pRecordData = (PBYTE)psa->pvData;
303         while(ulCellCount--)
304         {
305           IRecordInfo_RecordClear(lpRecInfo, pRecordData);
306           pRecordData += psa->cbElements;
307         }
308         IRecordInfo_Release(lpRecInfo);
309       }
310     }
311     else if (psa->fFeatures & FADF_BSTR)
312     {
313       BSTR* lpBstr = (BSTR*)psa->pvData + ulStartCell;
314
315       while(ulCellCount--)
316       {
317         if (*lpBstr)
318           SysFreeString(*lpBstr);
319         lpBstr++;
320       }
321     }
322     else if (psa->fFeatures & FADF_VARIANT)
323     {
324       VARIANT* lpVariant = (VARIANT*)psa->pvData + ulStartCell;
325
326       while(ulCellCount--)
327       {
328         HRESULT hRet = VariantClear(lpVariant);
329
330         if (FAILED(hRet)) FIXME("VariantClear of element failed!\n");
331         lpVariant++;
332       }
333     }
334   }
335   return S_OK;
336 }
337
338 /* Copy data items from one array to another */
339 static HRESULT SAFEARRAY_CopyData(SAFEARRAY *psa, SAFEARRAY *dest)
340 {
341   if (!psa->pvData)
342     return S_OK;
343   else if (!dest->pvData || psa->fFeatures & FADF_DATADELETED)
344     return E_INVALIDARG;
345   else
346   {
347     ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
348
349     dest->fFeatures = (dest->fFeatures & FADF_CREATEVECTOR) |
350                       (psa->fFeatures & ~(FADF_CREATEVECTOR|FADF_DATADELETED));
351
352     if (psa->fFeatures & FADF_VARIANT)
353     {
354       VARIANT* lpVariant = (VARIANT*)psa->pvData;
355       VARIANT* lpDest = (VARIANT*)dest->pvData;
356
357       while(ulCellCount--)
358       {
359         HRESULT hRet;
360
361         hRet = VariantCopy(lpDest, lpVariant);
362         if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%lx\n", hRet);
363         lpVariant++;
364         lpDest++;
365       }
366     }
367     else if (psa->fFeatures & FADF_BSTR)
368     {
369       BSTR* lpBstr = (BSTR*)psa->pvData;
370       BSTR* lpDest = (BSTR*)dest->pvData;
371
372       while(ulCellCount--)
373       {
374         if (*lpBstr)
375         {
376           *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
377           if (!*lpDest)
378             return E_OUTOFMEMORY;
379         }
380         else
381           *lpDest = NULL;
382         lpBstr++;
383         lpDest++;
384       }
385     }
386     else
387     {
388       /* Copy the data over */
389       memcpy(dest->pvData, psa->pvData, ulCellCount * psa->cbElements);
390
391       if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
392       {
393         LPUNKNOWN *lpUnknown = (LPUNKNOWN *)dest->pvData;
394
395         while(ulCellCount--)
396         {
397           if (*lpUnknown)
398             IUnknown_AddRef(*lpUnknown);
399           lpUnknown++;
400         }
401       }
402     }
403
404     if (psa->fFeatures & FADF_RECORD)
405     {
406       IRecordInfo* pRecInfo = NULL;
407
408       SafeArrayGetRecordInfo(psa, &pRecInfo);
409       SafeArraySetRecordInfo(dest, pRecInfo);
410
411       if (pRecInfo)
412       {
413         /* Release because Get() adds a reference */
414         IRecordInfo_Release(pRecInfo);
415       }
416     }
417     else if (psa->fFeatures & FADF_HAVEIID)
418     {
419       GUID guid;
420       SafeArrayGetIID(psa, &guid);
421       SafeArraySetIID(dest, &guid);
422     }
423     else if (psa->fFeatures & FADF_HAVEVARTYPE)
424     {
425       SAFEARRAY_SetHiddenDWORD(dest, SAFEARRAY_GetHiddenDWORD(psa));
426     }
427   }
428   return S_OK;
429 }
430
431 /*************************************************************************
432  *              SafeArrayAllocDescriptor (OLEAUT32.36)
433  *
434  * Allocate and initialise a descriptor for a SafeArray.
435  *
436  * PARAMS
437  *  cDims   [I] Number of dimensions of the array
438  *  ppsaOut [O] Destination for new descriptor
439  *
440  * RETURNS
441  * Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
442  * Failure: An HRESULT error code indicating the error.
443  *
444  * NOTES
445  * See SafeArray.
446  */
447 HRESULT WINAPI SafeArrayAllocDescriptor(UINT cDims, SAFEARRAY **ppsaOut)
448 {
449   LONG allocSize;
450
451   TRACE("(%d,%p)\n", cDims, ppsaOut);
452   
453   if (!cDims || cDims >= 0x10000) /* Maximum 65535 dimensions */
454     return E_INVALIDARG;
455
456   if (!ppsaOut)
457     return E_POINTER;
458
459   /* We need enough space for the header and its bounds */
460   allocSize = sizeof(SAFEARRAY) + sizeof(SAFEARRAYBOUND) * (cDims - 1);
461
462   if (FAILED(SAFEARRAY_AllocDescriptor(allocSize, ppsaOut)))
463     return E_UNEXPECTED;
464
465   (*ppsaOut)->cDims = cDims;
466
467   TRACE("(%d): %lu bytes allocated for descriptor.\n", cDims, allocSize);
468   return S_OK;
469 }
470
471 /*************************************************************************
472  *              SafeArrayAllocDescriptorEx (OLEAUT32.41)
473  *
474  * Allocate and initialise a descriptor for a SafeArray of a given type.
475  *
476  * PARAMS
477  *  vt      [I] The type of items to store in the array
478  *  cDims   [I] Number of dimensions of the array
479  *  ppsaOut [O] Destination for new descriptor
480  *
481  * RETURNS
482  *  Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
483  *  Failure: An HRESULT error code indicating the error.
484  *
485  * NOTES
486  *  - This function does not chack that vt is an allowed VARTYPE.
487  *  - Unlike SafeArrayAllocDescriptor(), vt is associated with the array.
488  *  See SafeArray.
489  */
490 HRESULT WINAPI SafeArrayAllocDescriptorEx(VARTYPE vt, UINT cDims, SAFEARRAY **ppsaOut)
491 {
492   ULONG cbElements;
493   HRESULT hRet = E_UNEXPECTED;
494
495   TRACE("(%d->%s,%d,%p)\n", vt, debugstr_vt(vt), cDims, ppsaOut);
496     
497   cbElements = SAFEARRAY_GetVTSize(vt);
498   if (!cbElements)
499     WARN("Creating a descriptor with an invalid VARTYPE!\n");
500
501   hRet = SafeArrayAllocDescriptor(cDims, ppsaOut);
502
503   if (SUCCEEDED(hRet))
504   {
505     SAFEARRAY_SetFeatures(vt, *ppsaOut);
506     (*ppsaOut)->cbElements = cbElements;
507   }
508   return hRet;
509 }
510
511 /*************************************************************************
512  *              SafeArrayAllocData (OLEAUT32.37)
513  *
514  * Allocate the data area of a SafeArray.
515  *
516  * PARAMS
517  *  psa [I] SafeArray to allocate the data area of.
518  *
519  * RETURNS
520  *  Success: S_OK. The data area is allocated and initialised.
521  *  Failure: An HRESULT error code indicating the error.
522  *
523  * NOTES
524  *  See SafeArray.
525  */
526 HRESULT WINAPI SafeArrayAllocData(SAFEARRAY *psa)
527 {
528   HRESULT hRet = E_INVALIDARG;
529   
530   TRACE("(%p)\n", psa);
531   
532   if (psa)
533   {
534     ULONG ulSize = SAFEARRAY_GetCellCount(psa);
535
536     hRet = E_OUTOFMEMORY;
537
538     if (psa->cbElements)
539     {
540       psa->pvData = SAFEARRAY_Malloc(ulSize * psa->cbElements);
541
542       if (psa->pvData)
543       {
544         hRet = S_OK;
545         TRACE("%lu bytes allocated for data at %p (%lu objects).\n",
546               ulSize * psa->cbElements, psa->pvData, ulSize);
547       }
548     }
549   }
550   return hRet;
551 }
552
553 /*************************************************************************
554  *              SafeArrayCreate (OLEAUT32.15)
555  *
556  * Create a new SafeArray.
557  *
558  * PARAMS
559  *  vt        [I] Type to store in the safe array
560  *  cDims     [I] Number of array dimensions
561  *  rgsabound [I] Bounds of the array dimensions
562  *
563  * RETURNS
564  *  Success: A pointer to a new array object.
565  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
566  *
567  * NOTES
568  *  Win32 allows arrays with 0 sized dimensions. This bug is not reproduced
569  *  in the Wine implementation.
570  *  See SafeArray.
571  */
572 SAFEARRAY* WINAPI SafeArrayCreate(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound)
573 {
574   TRACE("(%d->%s,%d,%p)\n", vt, debugstr_vt(vt), cDims, rgsabound);
575
576   if (vt == VT_RECORD)
577     return NULL;
578
579   return SAFEARRAY_Create(vt, cDims, rgsabound, 0);
580 }
581
582 /*************************************************************************
583  *              SafeArrayCreateEx (OLEAUT32.15)
584  *
585  * Create a new SafeArray.
586  *
587  * PARAMS
588  *  vt        [I] Type to store in the safe array
589  *  cDims     [I] Number of array dimensions
590  *  rgsabound [I] Bounds of the array dimensions
591  *  pvExtra   [I] Extra data
592  *
593  * RETURNS
594  *  Success: A pointer to a new array object.
595  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
596  *
597  * NOTES
598  * See SafeArray.
599  */
600 SAFEARRAY* WINAPI SafeArrayCreateEx(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, LPVOID pvExtra)
601 {
602   ULONG ulSize = 0;
603   IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
604   SAFEARRAY* psa;
605  
606   TRACE("(%d->%s,%d,%p,%p)\n", vt, debugstr_vt(vt), cDims, rgsabound, pvExtra);
607  
608   if (vt == VT_RECORD)
609   {
610     if  (!iRecInfo)
611       return NULL;
612     IRecordInfo_GetSize(iRecInfo, &ulSize);
613   }
614   psa = SAFEARRAY_Create(vt, cDims, rgsabound, ulSize);
615
616   if (pvExtra)
617   {
618     switch(vt)
619     {
620       case VT_RECORD:
621         SafeArraySetRecordInfo(psa, pvExtra);
622         break;
623       case VT_UNKNOWN:
624       case VT_DISPATCH:
625         SafeArraySetIID(psa, pvExtra);
626         break;
627     }
628   }
629   return psa;
630 }
631
632 /************************************************************************
633  *              SafeArrayCreateVector (OLEAUT32.411)
634  *
635  * Create a one dimensional, contiguous SafeArray.
636  *
637  * PARAMS
638  *  vt        [I] Type to store in the safe array
639  *  lLbound   [I] Lower bound of the array
640  *  cElements [I] Number of elements in the array
641  *
642  * RETURNS
643  *  Success: A pointer to a new array object.
644  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
645  *
646  * NOTES
647  * See SafeArray.
648  */
649 SAFEARRAY* WINAPI SafeArrayCreateVector(VARTYPE vt, LONG lLbound, ULONG cElements)
650 {
651   TRACE("(%d->%s,%ld,%ld\n", vt, debugstr_vt(vt), lLbound, cElements);
652     
653   if (vt == VT_RECORD)
654     return NULL;
655
656   return SAFEARRAY_CreateVector(vt, lLbound, cElements, SAFEARRAY_GetVTSize(vt));
657 }
658
659 /************************************************************************
660  *              SafeArrayCreateVectorEx (OLEAUT32.411)
661  *
662  * Create a one dimensional, contiguous SafeArray.
663  *
664  * PARAMS
665  *  vt        [I] Type to store in the safe array
666  *  lLbound   [I] Lower bound of the array
667  *  cElements [I] Number of elements in the array
668  *  pvExtra   [I] Extra data
669  *
670  * RETURNS
671  *  Success: A pointer to a new array object.
672  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
673  *
674  * NOTES
675  * See SafeArray.
676  */
677 SAFEARRAY* WINAPI SafeArrayCreateVectorEx(VARTYPE vt, LONG lLbound, ULONG cElements, LPVOID pvExtra)
678 {
679   ULONG ulSize;
680   IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
681   SAFEARRAY* psa;
682
683  TRACE("(%d->%s,%ld,%ld,%p\n", vt, debugstr_vt(vt), lLbound, cElements, pvExtra);
684  
685   if (vt == VT_RECORD)
686   {
687     if  (!iRecInfo)
688       return NULL;
689     IRecordInfo_GetSize(iRecInfo, &ulSize);
690   }
691   else
692     ulSize = SAFEARRAY_GetVTSize(vt);
693
694   psa = SAFEARRAY_CreateVector(vt, lLbound, cElements, ulSize);
695
696   if (pvExtra)
697   {
698     switch(vt)
699     {
700       case VT_RECORD:
701         SafeArraySetRecordInfo(psa, iRecInfo);
702         break;
703       case VT_UNKNOWN:
704       case VT_DISPATCH:
705         SafeArraySetIID(psa, pvExtra);
706         break;
707     }
708   }
709   return psa;
710 }
711
712 /*************************************************************************
713  *              SafeArrayDestroyDescriptor (OLEAUT32.38)
714  *
715  * Destroy a SafeArray.
716  *
717  * PARAMS
718  *  psa [I] SafeArray to destroy.
719  *
720  * RETURNS
721  *  Success: S_OK. The resources used by the array are freed.
722  *  Failure: An HRESULT error code indicating the error.
723  *
724  * NOTES
725  * See SafeArray.
726  */
727 HRESULT WINAPI SafeArrayDestroyDescriptor(SAFEARRAY *psa)
728 {
729   TRACE("(%p)\n", psa);
730     
731   if (psa)
732   {
733     LPVOID lpv = (char*)psa - SAFEARRAY_HIDDEN_SIZE;
734
735     if (psa->cLocks)
736       return DISP_E_ARRAYISLOCKED; /* Can't destroy a locked array */
737
738     if (psa->fFeatures & FADF_RECORD)
739       SafeArraySetRecordInfo(psa, NULL);
740
741     if (psa->fFeatures & FADF_CREATEVECTOR &&
742         !(psa->fFeatures & FADF_DATADELETED))
743         SAFEARRAY_DestroyData(psa, 0); /* Data not previously deleted */
744
745     if (!SAFEARRAY_Free(lpv))
746       return E_UNEXPECTED;
747   }
748   return S_OK;
749 }
750
751 /*************************************************************************
752  *              SafeArrayLock (OLEAUT32.21)
753  *
754  * Increment the lock counter of a SafeArray.
755  *
756  * PARAMS
757  *  psa [O] SafeArray to lock
758  *
759  * RETURNS
760  *  Success: S_OK. The array lock is incremented.
761  *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if too many locks
762  *           are held on the array at once.
763  *
764  * NOTES
765  *  In Win32 these locks are not thread safe.
766  *  See SafeArray.
767  */
768 HRESULT WINAPI SafeArrayLock(SAFEARRAY *psa)
769 {
770   ULONG ulLocks;
771
772   TRACE("(%p)\n", psa);
773     
774   if (!psa)
775     return E_INVALIDARG;
776
777   ulLocks = InterlockedIncrement( (LONG*) &psa->cLocks);
778
779   if (ulLocks > 0xffff) /* Maximum of 16384 locks at a time */
780   {
781     WARN("Out of locks!\n");
782     InterlockedDecrement( (LONG*) &psa->cLocks);
783     return E_UNEXPECTED;
784   }
785   return S_OK;
786 }
787
788 /*************************************************************************
789  *              SafeArrayUnlock (OLEAUT32.22)
790  *
791  * Decrement the lock counter of a SafeArray.
792  *
793  * PARAMS
794  *  psa [O] SafeArray to unlock
795  *
796  * RETURNS
797  *  Success: S_OK. The array lock is decremented.
798  *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if no locks are
799  *           held on the array.
800  *
801  * NOTES
802  * See SafeArray.
803  */
804 HRESULT WINAPI SafeArrayUnlock(SAFEARRAY *psa)
805 {
806   TRACE("(%p)\n", psa);
807   
808   if (!psa)
809     return E_INVALIDARG;
810
811   if ((LONG)InterlockedDecrement( (LONG*) &psa->cLocks) < 0)
812   {
813     WARN("Unlocked but no lock held!\n");
814     InterlockedIncrement( (LONG*) &psa->cLocks);
815     return E_UNEXPECTED;
816   }
817   return S_OK;
818 }
819
820 /*************************************************************************
821  *              SafeArrayPutElement (OLEAUT32.26)
822  *
823  * Put an item into a SafeArray.
824  *
825  * PARAMS
826  *  psa       [I] SafeArray to insert into
827  *  rgIndices [I] Indices to insert at
828  *  pvData    [I] Data to insert
829  *
830  * RETURNS
831  *  Success: S_OK. The item is inserted
832  *  Failure: An HRESULT error code indicating the error.
833  *
834  * NOTES
835  * See SafeArray.
836  */
837 HRESULT WINAPI SafeArrayPutElement(SAFEARRAY *psa, LONG *rgIndices, void *pvData)
838 {
839   HRESULT hRet;
840
841   TRACE("(%p,%p,%p)\n", psa, rgIndices, pvData);
842
843   if (!psa || !rgIndices)
844     return E_INVALIDARG;
845
846   if (!pvData)
847   {
848     ERR("Invalid pvData would crash under Win32!\n");
849     return E_INVALIDARG;
850   }
851
852   hRet = SafeArrayLock(psa);
853
854   if (SUCCEEDED(hRet))
855   {
856     PVOID lpvDest;
857
858     hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvDest);
859
860     if (SUCCEEDED(hRet))
861     {
862       if (psa->fFeatures & FADF_VARIANT)
863       {
864         VARIANT* lpVariant = (VARIANT*)pvData;
865         VARIANT* lpDest = (VARIANT*)lpvDest;
866
867         hRet = VariantClear(lpDest);
868         if (FAILED(hRet)) FIXME("VariantClear failed with 0x%lx\n", hRet);
869         hRet = VariantCopy(lpDest, lpVariant);
870         if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%lx\n", hRet);
871       }
872       else if (psa->fFeatures & FADF_BSTR)
873       {
874         BSTR  lpBstr = (BSTR)pvData;
875         BSTR* lpDest = (BSTR*)lpvDest;
876
877         if (*lpDest)
878          SysFreeString(*lpDest);
879
880         *lpDest = SysAllocStringByteLen((char*)lpBstr, SysStringByteLen(lpBstr));
881         if (!*lpDest)
882           hRet = E_OUTOFMEMORY;
883       }
884       else
885       {
886         if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
887         {
888           LPUNKNOWN  lpUnknown = (LPUNKNOWN)pvData;
889           LPUNKNOWN *lpDest = (LPUNKNOWN *)lpvDest;
890
891           if (lpUnknown)
892             IUnknown_AddRef(lpUnknown);
893           if (*lpDest)
894             IUnknown_Release(*lpDest);
895           *lpDest = lpUnknown;
896         } else {
897           /* Copy the data over */
898           memcpy(lpvDest, pvData, psa->cbElements);
899         }
900       }
901     }
902     SafeArrayUnlock(psa);
903   }
904   return hRet;
905 }
906
907
908 /*************************************************************************
909  *              SafeArrayGetElement (OLEAUT32.25)
910  *
911  * Get an item from a SafeArray.
912  *
913  * PARAMS
914  *  psa       [I] SafeArray to get from
915  *  rgIndices [I] Indices to get from
916  *  pvData    [O] Destination for data
917  *
918  * RETURNS
919  *  Success: S_OK. The item data is returned in pvData.
920  *  Failure: An HRESULT error code indicating the error.
921  *
922  * NOTES
923  * See SafeArray.
924  */
925 HRESULT WINAPI SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pvData)
926 {
927   HRESULT hRet;
928
929   TRACE("(%p,%p,%p)\n", psa, rgIndices, pvData);
930     
931   if (!psa || !rgIndices || !pvData)
932     return E_INVALIDARG;
933
934   hRet = SafeArrayLock(psa);
935
936   if (SUCCEEDED(hRet))
937   {
938     PVOID lpvSrc;
939
940     hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvSrc);
941
942     if (SUCCEEDED(hRet))
943     {
944       if (psa->fFeatures & FADF_VARIANT)
945       {
946         VARIANT* lpVariant = (VARIANT*)lpvSrc;
947         VARIANT* lpDest = (VARIANT*)pvData;
948
949         /* The original content of pvData is ignored. */
950         V_VT(lpDest) = VT_EMPTY;
951         hRet = VariantCopy(lpDest, lpVariant);
952         if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%lx\n", hRet);
953       }
954       else if (psa->fFeatures & FADF_BSTR)
955       {
956         BSTR* lpBstr = (BSTR*)lpvSrc;
957         BSTR* lpDest = (BSTR*)pvData;
958
959         if (*lpBstr)
960         {
961           *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
962           if (!*lpBstr)
963             hRet = E_OUTOFMEMORY;
964         }
965         else
966           *lpDest = NULL;
967       }
968       else
969       {
970         if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
971         {
972           LPUNKNOWN *lpUnknown = (LPUNKNOWN *)lpvSrc;
973
974           if (*lpUnknown)
975             IUnknown_AddRef(*lpUnknown);
976         }
977         /* Copy the data over */
978         memcpy(pvData, lpvSrc, psa->cbElements);
979       }
980     }
981     SafeArrayUnlock(psa);
982   }
983   return hRet;
984 }
985
986 /*************************************************************************
987  *              SafeArrayGetUBound (OLEAUT32.19)
988  *
989  * Get the upper bound for a given SafeArray dimension
990  *
991  * PARAMS
992  *  psa      [I] Array to get dimension upper bound from
993  *  nDim     [I] The dimension number to get the upper bound of
994  *  plUbound [O] Destination for the upper bound
995  *
996  * RETURNS
997  *  Success: S_OK. plUbound contains the dimensions upper bound.
998  *  Failure: An HRESULT error code indicating the error.
999  *
1000  * NOTES
1001  * See SafeArray.
1002  */
1003 HRESULT WINAPI SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound)
1004 {
1005   TRACE("(%p,%d,%p)\n", psa, nDim, plUbound);
1006     
1007   if (!psa || !plUbound)
1008     return E_INVALIDARG;
1009
1010   if(!nDim || nDim > psa->cDims)
1011     return DISP_E_BADINDEX;
1012
1013   *plUbound = psa->rgsabound[psa->cDims - nDim].lLbound +
1014               psa->rgsabound[psa->cDims - nDim].cElements - 1;
1015
1016   return S_OK;
1017 }
1018
1019 /*************************************************************************
1020  *              SafeArrayGetLBound (OLEAUT32.20)
1021  *
1022  * Get the lower bound for a given SafeArray dimension
1023  *
1024  * PARAMS
1025  *  psa      [I] Array to get dimension lower bound from
1026  *  nDim     [I] The dimension number to get the lowe bound of
1027  *  plLbound [O] Destination for the lower bound
1028  *
1029  * RETURNS
1030  *  Success: S_OK. plUbound contains the dimensions lower bound.
1031  *  Failure: An HRESULT error code indicating the error.
1032  *
1033  * NOTES
1034  * See SafeArray.
1035  */
1036 HRESULT WINAPI SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound)
1037 {
1038   TRACE("(%p,%d,%p)\n", psa, nDim, plLbound);
1039
1040   if (!psa || !plLbound)
1041     return E_INVALIDARG;
1042
1043   if(!nDim || nDim > psa->cDims)
1044     return DISP_E_BADINDEX;
1045
1046   *plLbound = psa->rgsabound[psa->cDims - nDim].lLbound;
1047   return S_OK;
1048 }
1049
1050 /*************************************************************************
1051  *              SafeArrayGetDim (OLEAUT32.17)
1052  *
1053  * Get the number of dimensions in a SafeArray.
1054  *
1055  * PARAMS
1056  *  psa [I] Array to get the dimensions of
1057  *
1058  * RETURNS
1059  *  The number of array dimensions in psa, or 0 if psa is NULL.
1060  *
1061  * NOTES
1062  * See SafeArray.
1063  */
1064 UINT WINAPI SafeArrayGetDim(SAFEARRAY *psa)
1065 {
1066   TRACE("(%p) returning %ld\n", psa, psa ? psa->cDims : 0ul);  
1067   return psa ? psa->cDims : 0;
1068 }
1069
1070 /*************************************************************************
1071  *              SafeArrayGetElemsize (OLEAUT32.18)
1072  *
1073  * Get the size of an element in a SafeArray.
1074  *
1075  * PARAMS
1076  *  psa [I] Array to get the element size from
1077  *
1078  * RETURNS
1079  *  The size of a single element in psa, or 0 if psa is NULL.
1080  *
1081  * NOTES
1082  * See SafeArray.
1083  */
1084 UINT WINAPI SafeArrayGetElemsize(SAFEARRAY *psa)
1085 {
1086   TRACE("(%p) returning %ld\n", psa, psa ? psa->cbElements : 0ul);
1087   return psa ? psa->cbElements : 0;
1088 }
1089
1090 /*************************************************************************
1091  *              SafeArrayAccessData (OLEAUT32.23)
1092  *
1093  * Lock a SafeArray and return a pointer to its data.
1094  *
1095  * PARAMS
1096  *  psa     [I] Array to get the data pointer from
1097  *  ppvData [O] Destination for the arrays data pointer
1098  *
1099  * RETURNS
1100  *  Success: S_OK. ppvData contains the arrays data pointer, and the array
1101  *           is locked.
1102  *  Failure: An HRESULT error code indicating the error.
1103  *
1104  * NOTES
1105  * See SafeArray.
1106  */
1107 HRESULT WINAPI SafeArrayAccessData(SAFEARRAY *psa, void **ppvData)
1108 {
1109   TRACE("(%p,%p)\n", psa, ppvData);
1110
1111   if(!psa || !ppvData)
1112     return E_INVALIDARG;
1113
1114   if (SUCCEEDED(SafeArrayLock(psa)))
1115   {
1116     *ppvData = psa->pvData;
1117     return S_OK;
1118   }
1119   *ppvData = NULL;
1120   return E_UNEXPECTED;
1121 }
1122
1123
1124 /*************************************************************************
1125  *              SafeArrayUnaccessData (OLEAUT32.24)
1126  *
1127  * Unlock a SafeArray after accessing its data.
1128  *
1129  * PARAMS
1130  *  psa     [I] Array to unlock
1131  *
1132  * RETURNS
1133  *  Success: S_OK. The array is unlocked.
1134  *  Failure: An HRESULT error code indicating the error.
1135  *
1136  * NOTES
1137  * See SafeArray.
1138  */
1139 HRESULT WINAPI SafeArrayUnaccessData(SAFEARRAY *psa)
1140 {
1141   TRACE("(%p)\n", psa);
1142   return SafeArrayUnlock(psa);
1143 }
1144
1145 /************************************************************************
1146  *              SafeArrayPtrOfIndex (OLEAUT32.148)
1147  *
1148  * Get the address of an item in a SafeArray.
1149  *
1150  * PARAMS
1151  *  psa       [I] Array to get the items address from
1152  *  rgIndices [I] Index of the item in the array
1153  *  ppvData   [O] Destination for item address
1154  *
1155  * RETURNS
1156  *  Success: S_OK. ppvData contains a pointer to the item.
1157  *  Failure: An HRESULT error code indicating the error.
1158  *
1159  * NOTES
1160  *  This function does not lock the array.
1161  *
1162  * NOTES
1163  * See SafeArray.
1164  */
1165 HRESULT WINAPI SafeArrayPtrOfIndex(SAFEARRAY *psa, LONG *rgIndices, void **ppvData)
1166 {
1167   USHORT dim;
1168   ULONG cell = 0, dimensionSize = 1;
1169   SAFEARRAYBOUND* psab;
1170   LONG c1;
1171
1172   TRACE("(%p,%p,%p)\n", psa, rgIndices, ppvData);
1173   
1174   /* The general formula for locating the cell number of an entry in an n
1175    * dimensional array (where cn = coordinate in dimension dn) is:
1176    *
1177    * c1 + c2 * sizeof(d1) + c3 * sizeof(d2) ... + cn * sizeof(c(n-1))
1178    *
1179    * We calculate the size of the last dimension at each step through the
1180    * dimensions to avoid recursing to calculate the last dimensions size.
1181    */
1182   if (!psa || !rgIndices || !ppvData)
1183     return E_INVALIDARG;
1184
1185   psab = psa->rgsabound + psa->cDims - 1;
1186   c1 = *rgIndices++;
1187
1188   if (c1 < psab->lLbound || c1 >= psab->lLbound + (LONG)psab->cElements)
1189     return DISP_E_BADINDEX; /* Initial index out of bounds */
1190
1191   for (dim = 1; dim < psa->cDims; dim++)
1192   {
1193     dimensionSize *= psab->cElements;
1194
1195     psab--;
1196
1197     if (!psab->cElements ||
1198         *rgIndices < psab->lLbound ||
1199         *rgIndices >= psab->lLbound + (LONG)psab->cElements)
1200     return DISP_E_BADINDEX; /* Index out of bounds */
1201
1202     cell += (*rgIndices - psab->lLbound) * dimensionSize;
1203     rgIndices++;
1204   }
1205
1206   cell += (c1 - psa->rgsabound[psa->cDims - 1].lLbound);
1207
1208   *ppvData = (char*)psa->pvData + cell * psa->cbElements;
1209   return S_OK;
1210 }
1211
1212 /************************************************************************
1213  *              SafeArrayDestroyData (OLEAUT32.39)
1214  *
1215  * Destroy the data associated with a SafeArray.
1216  *
1217  * PARAMS
1218  *  psa [I] Array to delete the data from
1219  *
1220  * RETURNS
1221  *  Success: S_OK. All items and the item data are freed.
1222  *  Failure: An HRESULT error code indicating the error.
1223  *
1224  * NOTES
1225  * See SafeArray.
1226  */
1227 HRESULT WINAPI SafeArrayDestroyData(SAFEARRAY *psa)
1228 {
1229   TRACE("(%p)\n", psa);
1230   
1231   if (!psa)
1232     return E_INVALIDARG;
1233
1234   if (psa->cLocks)
1235     return DISP_E_ARRAYISLOCKED; /* Can't delete a locked array */
1236
1237   /* Delete the actual item data */
1238   if (FAILED(SAFEARRAY_DestroyData(psa, 0)))
1239     return E_UNEXPECTED;
1240
1241   if (psa->pvData)
1242   {
1243     if (psa->fFeatures & FADF_STATIC)
1244     {
1245       ZeroMemory(psa->pvData, SAFEARRAY_GetCellCount(psa) * psa->cbElements);
1246       return S_OK;
1247     }
1248     /* If this is not a vector, free the data memory block */
1249     if (!(psa->fFeatures & FADF_CREATEVECTOR))
1250     {
1251       if (!SAFEARRAY_Free(psa->pvData))
1252         return E_UNEXPECTED;
1253       psa->pvData = NULL;
1254     }
1255     else
1256       psa->fFeatures |= FADF_DATADELETED; /* Mark the data deleted */
1257
1258   }
1259   return S_OK;
1260 }
1261
1262 /************************************************************************
1263  *              SafeArrayCopyData (OLEAUT32.412)
1264  *
1265  * Copy all data from one SafeArray to another.
1266  *
1267  * PARAMS
1268  *  psaSource [I] Source for copy
1269  *  psaTarget [O] Destination for copy
1270  *
1271  * RETURNS
1272  *  Success: S_OK. psaTarget contains a copy of psaSource.
1273  *  Failure: An HRESULT error code indicating the error.
1274  *
1275  * NOTES
1276  *  The two arrays must have the same number of dimensions and elements.
1277  *
1278  * NOTES
1279  * See SafeArray.
1280  */
1281 HRESULT WINAPI SafeArrayCopyData(SAFEARRAY *psaSource, SAFEARRAY *psaTarget)
1282 {
1283   int dim;
1284
1285   TRACE("(%p,%p)\n", psaSource, psaTarget);
1286   
1287   if (!psaSource || !psaTarget ||
1288       psaSource->cDims != psaTarget->cDims ||
1289       psaSource->cbElements != psaTarget->cbElements)
1290     return E_INVALIDARG;
1291
1292   /* Each dimension must be the same size */
1293   for (dim = psaSource->cDims - 1; dim >= 0 ; dim--)
1294     if (psaSource->rgsabound[dim].cElements !=
1295        psaTarget->rgsabound[dim].cElements)
1296       return E_INVALIDARG;
1297
1298   if (SUCCEEDED(SAFEARRAY_DestroyData(psaTarget, 0)) &&
1299       SUCCEEDED(SAFEARRAY_CopyData(psaSource, psaTarget)))
1300     return S_OK;
1301   return E_UNEXPECTED;
1302 }
1303
1304 /************************************************************************
1305  *              SafeArrayDestroy (OLEAUT32.16)
1306  *
1307  * Destroy a SafeArray.
1308  *
1309  * PARAMS
1310  *  psa [I] Array to destroy
1311  *
1312  * RETURNS
1313  *  Success: S_OK. All resources used by the array are freed.
1314  *  Failure: An HRESULT error code indicating the error.
1315  *
1316  * NOTES
1317  * See SafeArray.
1318  */
1319 HRESULT WINAPI SafeArrayDestroy(SAFEARRAY *psa)
1320 {
1321   TRACE("(%p)\n", psa);
1322
1323   if(!psa)
1324     return S_OK;
1325
1326   if(psa->cLocks > 0)
1327     return DISP_E_ARRAYISLOCKED;
1328
1329   /* Native doesn't check to see if the free succeeds */
1330   SafeArrayDestroyData(psa);
1331   SafeArrayDestroyDescriptor(psa);
1332   return S_OK;
1333 }
1334
1335 /************************************************************************
1336  *              SafeArrayCopy (OLEAUT32.27)
1337  *
1338  * Make a duplicate of a SafeArray.
1339  *
1340  * PARAMS
1341  *  psa     [I] Source for copy
1342  *  ppsaOut [O] Destination for new copy
1343  *
1344  * RETURNS
1345  *  Success: S_OK. ppsaOut contains a copy of the array.
1346  *  Failure: An HRESULT error code indicating the error.
1347  *
1348  * NOTES
1349  * See SafeArray.
1350  */
1351 HRESULT WINAPI SafeArrayCopy(SAFEARRAY *psa, SAFEARRAY **ppsaOut)
1352 {
1353   HRESULT hRet;
1354
1355   TRACE("(%p,%p)\n", psa, ppsaOut);
1356
1357   if (!ppsaOut)
1358     return E_INVALIDARG;
1359
1360   *ppsaOut = NULL;
1361
1362   if (!psa)
1363     return S_OK; /* Handles copying of NULL arrays */
1364
1365   if (!psa->cbElements)
1366   {
1367     ERR("not copying an array of 0 elements\n");
1368     return E_INVALIDARG;
1369   }
1370
1371   if (psa->fFeatures & (FADF_RECORD|FADF_HAVEIID|FADF_HAVEVARTYPE))
1372   {
1373     VARTYPE vt;
1374     if (FAILED(SafeArrayGetVartype(psa, &vt)))
1375       hRet = E_UNEXPECTED;
1376     else
1377       hRet = SafeArrayAllocDescriptorEx(vt, psa->cDims, ppsaOut);
1378   }
1379   else
1380   {
1381     hRet = SafeArrayAllocDescriptor(psa->cDims, ppsaOut);
1382     if (SUCCEEDED(hRet))
1383     {
1384       (*ppsaOut)->fFeatures = psa->fFeatures & ~FADF_CREATEVECTOR;
1385       (*ppsaOut)->cbElements = psa->cbElements;
1386     }
1387   }
1388
1389   if (SUCCEEDED(hRet))
1390   {
1391     /* Copy dimension bounds */
1392     memcpy((*ppsaOut)->rgsabound, psa->rgsabound, psa->cDims * sizeof(SAFEARRAYBOUND));
1393
1394     (*ppsaOut)->pvData = SAFEARRAY_Malloc(SAFEARRAY_GetCellCount(psa) * psa->cbElements);
1395
1396     if ((*ppsaOut)->pvData)
1397     {
1398       hRet = SAFEARRAY_CopyData(psa, *ppsaOut);
1399  
1400       if (SUCCEEDED(hRet))
1401         return hRet;
1402
1403       SAFEARRAY_Free((*ppsaOut)->pvData);
1404     }
1405     SafeArrayDestroyDescriptor(*ppsaOut);
1406   }
1407   *ppsaOut = NULL;
1408   return hRet;
1409 }
1410
1411 /************************************************************************
1412  *              SafeArrayRedim (OLEAUT32.40)
1413  *
1414  * Changes the characteristics of the last dimension of a SafeArray
1415  *
1416  * PARAMS
1417  *  psa      [I] Array to change
1418  *  psabound [I] New bound details for the last dimension
1419  *
1420  * RETURNS
1421  *  Success: S_OK. psa is updated to reflect the new bounds.
1422  *  Failure: An HRESULT error code indicating the error.
1423  *
1424  * NOTES
1425  * See SafeArray.
1426  */
1427 HRESULT WINAPI SafeArrayRedim(SAFEARRAY *psa, SAFEARRAYBOUND *psabound)
1428 {
1429   SAFEARRAYBOUND *oldBounds;
1430
1431   TRACE("(%p,%p)\n", psa, psabound);
1432   
1433   if (!psa || psa->fFeatures & FADF_FIXEDSIZE || !psabound)
1434     return E_INVALIDARG;
1435
1436   if (psa->cLocks > 0)
1437     return DISP_E_ARRAYISLOCKED;
1438
1439   if (FAILED(SafeArrayLock(psa)))
1440     return E_UNEXPECTED;
1441
1442   oldBounds = psa->rgsabound;
1443   oldBounds->lLbound = psabound->lLbound;
1444
1445   if (psabound->cElements != oldBounds->cElements)
1446   {
1447     if (psabound->cElements < oldBounds->cElements)
1448     {
1449       /* Shorten the final dimension. */
1450       ULONG ulStartCell = psabound->cElements *
1451                           (SAFEARRAY_GetCellCount(psa) / oldBounds->cElements);
1452       SAFEARRAY_DestroyData(psa, ulStartCell);
1453     }
1454     else
1455     {
1456       /* Lengthen the final dimension */
1457       ULONG ulOldSize, ulNewSize;
1458       PVOID pvNewData;
1459
1460       ulOldSize = SAFEARRAY_GetCellCount(psa) * psa->cbElements;
1461       if (ulOldSize)
1462         ulNewSize = (ulOldSize / oldBounds->cElements) * psabound->cElements;
1463       else {
1464         int oldelems = oldBounds->cElements;
1465         oldBounds->cElements = psabound->cElements;
1466         ulNewSize = SAFEARRAY_GetCellCount(psa) * psa->cbElements;
1467         oldBounds->cElements = oldelems;
1468       }
1469
1470       if (!(pvNewData = SAFEARRAY_Malloc(ulNewSize)))
1471       {
1472         SafeArrayUnlock(psa);
1473         return E_UNEXPECTED;
1474       }
1475
1476       memcpy(pvNewData, psa->pvData, ulOldSize);
1477       SAFEARRAY_Free(psa->pvData);
1478       psa->pvData = pvNewData;
1479     }
1480     oldBounds->cElements = psabound->cElements;
1481   }
1482
1483   SafeArrayUnlock(psa);
1484   return S_OK;
1485 }
1486
1487 /************************************************************************
1488  *              SafeArrayGetVartype (OLEAUT32.77)
1489  *
1490  * Get the type of the items in a SafeArray.
1491  *
1492  * PARAMS
1493  *  psa [I] Array to get the type from
1494  *  pvt [O] Destination for the type
1495  *
1496  * RETURNS
1497  *  Success: S_OK. pvt contains the type of the items.
1498  *  Failure: An HRESULT error code indicating the error.
1499  *
1500  * NOTES
1501  * See SafeArray.
1502  */
1503 HRESULT WINAPI SafeArrayGetVartype(SAFEARRAY* psa, VARTYPE* pvt)
1504 {
1505   TRACE("(%p,%p)\n", psa, pvt);
1506
1507   if (!psa || !pvt)
1508     return E_INVALIDARG;
1509
1510   if (psa->fFeatures & FADF_RECORD)
1511     *pvt = VT_RECORD;
1512   else if (psa->fFeatures & FADF_HAVEIID)
1513     *pvt = VT_UNKNOWN;
1514   else if (psa->fFeatures & FADF_HAVEVARTYPE)
1515   {
1516     VARTYPE vt = SAFEARRAY_GetHiddenDWORD(psa);
1517     *pvt = vt;
1518   }
1519   else
1520     return E_INVALIDARG;
1521
1522   return S_OK;
1523 }
1524
1525 /************************************************************************
1526  *              SafeArraySetRecordInfo (OLEAUT32.@)
1527  *
1528  * Set the record info for a SafeArray.
1529  *
1530  * PARAMS
1531  *  psa    [I] Array to set the record info for
1532  *  pRinfo [I] Record info
1533  *
1534  * RETURNS
1535  *  Success: S_OK. The record info is stored with the array.
1536  *  Failure: An HRESULT error code indicating the error.
1537  *
1538  * NOTES
1539  * See SafeArray.
1540  */
1541 HRESULT WINAPI SafeArraySetRecordInfo(SAFEARRAY *psa, IRecordInfo *pRinfo)
1542 {
1543   IRecordInfo** dest = (IRecordInfo**)psa;
1544
1545   TRACE("(%p,%p)\n", psa, pRinfo);
1546   
1547   if (!psa || !(psa->fFeatures & FADF_RECORD))
1548     return E_INVALIDARG;
1549
1550   if (pRinfo)
1551     IRecordInfo_AddRef(pRinfo);
1552
1553   if (dest[-1])
1554     IRecordInfo_Release(dest[-1]);
1555
1556   dest[-1] = pRinfo;
1557   return S_OK;
1558 }
1559
1560 /************************************************************************
1561  *              SafeArrayGetRecordInfo (OLEAUT32.@)
1562  *
1563  * Get the record info from a SafeArray.
1564  *
1565  * PARAMS
1566  *  psa    [I] Array to get the record info from
1567  *  pRinfo [O] Destination for the record info
1568  *
1569  * RETURNS
1570  *  Success: S_OK. pRinfo contains the record info, or NULL if there was none.
1571  *  Failure: An HRESULT error code indicating the error.
1572  *
1573  * NOTES
1574  * See SafeArray.
1575  */
1576 HRESULT WINAPI SafeArrayGetRecordInfo(SAFEARRAY *psa, IRecordInfo **pRinfo)
1577 {
1578   IRecordInfo** src = (IRecordInfo**)psa;
1579
1580   TRACE("(%p,%p)\n", psa, pRinfo);
1581
1582   if (!psa || !pRinfo || !(psa->fFeatures & FADF_RECORD))
1583     return E_INVALIDARG;
1584
1585   *pRinfo = src[-1];
1586
1587   if (*pRinfo)
1588     IRecordInfo_AddRef(*pRinfo);
1589   return S_OK;
1590 }
1591
1592 /************************************************************************
1593  *              SafeArraySetIID (OLEAUT32.@)
1594  *
1595  * Set the IID for a SafeArray.
1596  *
1597  * PARAMS
1598  *  psa  [I] Array to set the IID from
1599  *  guid [I] IID
1600  *
1601  * RETURNS
1602  *  Success: S_OK. The IID is stored with the array
1603  *  Failure: An HRESULT error code indicating the error.
1604  *
1605  * NOTES
1606  * See SafeArray.
1607  */
1608 HRESULT WINAPI SafeArraySetIID(SAFEARRAY *psa, REFGUID guid)
1609 {
1610   GUID* dest = (GUID*)psa;
1611
1612   TRACE("(%p,%s)\n", psa, debugstr_guid(guid));
1613
1614   if (!psa || !guid || !(psa->fFeatures & FADF_HAVEIID))
1615     return E_INVALIDARG;
1616
1617   dest[-1] = *guid;
1618   return S_OK;
1619 }
1620
1621 /************************************************************************
1622  *              SafeArrayGetIID (OLEAUT32.@)
1623  *
1624  * Get the IID from a SafeArray.
1625  *
1626  * PARAMS
1627  *  psa   [I] Array to get the ID from
1628  *  pGuid [O] Destination for the IID
1629  *
1630  * RETURNS
1631  *  Success: S_OK. pRinfo contains the IID, or NULL if there was none.
1632  *  Failure: An HRESULT error code indicating the error.
1633  *
1634  * NOTES
1635  * See SafeArray.
1636  */
1637 HRESULT WINAPI SafeArrayGetIID(SAFEARRAY *psa, GUID *pGuid)
1638 {
1639   GUID* src = (GUID*)psa;
1640
1641   TRACE("(%p,%p)\n", psa, pGuid);
1642
1643   if (!psa || !pGuid || !(psa->fFeatures & FADF_HAVEIID))
1644     return E_INVALIDARG;
1645
1646   *pGuid = src[-1];
1647   return S_OK;
1648 }
1649
1650 /************************************************************************
1651  *              VectorFromBstr (OLEAUT32.@)
1652  *
1653  * Create a SafeArray Vector from the bytes of a BSTR.
1654  *
1655  * PARAMS
1656  *  bstr [I] String to get bytes from
1657  *  ppsa [O] Destination for the array
1658  *
1659  * RETURNS
1660  *  Success: S_OK. ppsa contains the strings bytes as a VT_UI1 array.
1661  *  Failure: An HRESULT error code indicating the error.
1662  *
1663  * NOTES
1664  * See SafeArray.
1665  */
1666 HRESULT WINAPI VectorFromBstr(BSTR bstr, SAFEARRAY **ppsa)
1667 {
1668   SAFEARRAYBOUND sab;
1669
1670   TRACE("(%p,%p)\n", bstr, ppsa);
1671   
1672   if (!ppsa)
1673     return E_INVALIDARG;
1674
1675   sab.lLbound = 0;
1676   sab.cElements = SysStringByteLen(bstr);
1677
1678   *ppsa = SAFEARRAY_Create(VT_UI1, 1, &sab, 0);
1679
1680   if (*ppsa)
1681   {
1682     memcpy((*ppsa)->pvData, bstr, sab.cElements);
1683     return S_OK;
1684   }
1685   return E_OUTOFMEMORY;
1686 }
1687
1688 /************************************************************************
1689  *              BstrFromVector (OLEAUT32.@)
1690  *
1691  * Create a BSTR from a SafeArray.
1692  *
1693  * PARAMS
1694  *  psa   [I] Source array
1695  *  pbstr [O] Destination for output BSTR
1696  *
1697  * RETURNS
1698  *  Success: S_OK. pbstr contains the arrays data.
1699  *  Failure: An HRESULT error code indicating the error.
1700  *
1701  * NOTES
1702  *  psa must be a 1 dimensional array of a 1 byte type.
1703  *
1704  * NOTES
1705  * See SafeArray.
1706  */
1707 HRESULT WINAPI BstrFromVector(SAFEARRAY *psa, BSTR *pbstr)
1708 {
1709   TRACE("(%p,%p)\n", psa, pbstr);
1710
1711   if (!pbstr)
1712     return E_INVALIDARG;
1713
1714   *pbstr = NULL;
1715
1716   if (!psa || psa->cbElements != 1 || psa->cDims != 1)
1717     return E_INVALIDARG;
1718
1719   *pbstr = SysAllocStringByteLen(psa->pvData, psa->rgsabound[0].cElements);
1720   if (!*pbstr)
1721     return E_OUTOFMEMORY;
1722   return S_OK;
1723 }