A small number of cleanups.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 #ifdef HAVE_STRING_H
37 # include <string.h>
38 #endif
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include "windef.h"
42 #include "winerror.h"
43 #include "winbase.h"
44 #include "oleauto.h"
45 #include "wine/debug.h"
46 #include "variant.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
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 seperately from
66  * the array header. This is the most flexable 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   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 /* Get the 0 based index of an index into a dimension */
173 static inline ULONG SAFEARRAY_GetDimensionIndex(SAFEARRAYBOUND *psab, ULONG ulIndex)
174 {
175   return ulIndex - psab->lLbound;
176 }
177
178 /* Get the size of a dimension in cells */
179 static inline ULONG SAFEARRAY_GetDimensionCells(SAFEARRAY *psa, ULONG ulDim)
180 {
181   ULONG size = psa->rgsabound[0].cElements;
182
183   while (ulDim)
184   {
185     size *= psa->rgsabound[ulDim].cElements;
186     ulDim--;
187   }
188   return size;
189 }
190
191 /* Allocate a descriptor for an array */
192 static HRESULT SAFEARRAY_AllocDescriptor(ULONG ulSize, SAFEARRAY **ppsaOut)
193 {
194   *ppsaOut = (SAFEARRAY*)((char*)SAFEARRAY_Malloc(ulSize + SAFEARRAY_HIDDEN_SIZE) + SAFEARRAY_HIDDEN_SIZE);
195
196   if (!*ppsaOut)
197     return E_UNEXPECTED;
198
199   return S_OK;
200 }
201
202 /* Set the features of an array */
203 static void SAFEARRAY_SetFeatures(VARTYPE vt, SAFEARRAY *psa)
204 {
205   /* Set the IID if we have one, otherwise set the type */
206   if (vt == VT_DISPATCH)
207   {
208     psa->fFeatures = FADF_HAVEIID;
209     SafeArraySetIID(psa, &IID_IDispatch);
210   }
211   else if (vt == VT_UNKNOWN)
212   {
213     psa->fFeatures = FADF_HAVEIID;
214     SafeArraySetIID(psa, &IID_IUnknown);
215   }
216   else if (vt == VT_RECORD)
217     psa->fFeatures = FADF_RECORD;
218   else
219   {
220     psa->fFeatures = FADF_HAVEVARTYPE;
221     SAFEARRAY_SetHiddenDWORD(psa, vt);
222   }
223 }
224
225 /* Create an array */
226 static SAFEARRAY* SAFEARRAY_Create(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, ULONG ulSize)
227 {
228   SAFEARRAY *psa = NULL;
229
230   if (!rgsabound)
231     return NULL;
232
233   if (SUCCEEDED(SafeArrayAllocDescriptorEx(vt, cDims, &psa)))
234   {
235     switch (vt)
236     {
237       case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
238       case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
239       case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
240       case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
241     }
242
243     memcpy(psa->rgsabound, rgsabound, cDims * sizeof(SAFEARRAYBOUND));
244
245     if (ulSize)
246       psa->cbElements = ulSize;
247
248     if (FAILED(SafeArrayAllocData(psa)))
249     {
250       SafeArrayDestroyDescriptor(psa);
251       psa = NULL;
252     }
253   }
254   return psa;
255 }
256
257 /* Create an array as a vector */
258 static SAFEARRAY* SAFEARRAY_CreateVector(VARTYPE vt, LONG lLbound, ULONG cElements, ULONG ulSize)
259 {
260   SAFEARRAY *psa = NULL;
261
262   if (ulSize || (vt == VT_RECORD))
263   {
264     /* Allocate the header and data together */
265     if (SUCCEEDED(SAFEARRAY_AllocDescriptor(sizeof(SAFEARRAY) + ulSize * cElements, &psa)))
266     {
267       SAFEARRAY_SetFeatures(vt, psa);
268
269       psa->cDims = 1;
270       psa->fFeatures |= FADF_CREATEVECTOR;
271       psa->pvData = &psa[1]; /* Data follows the header */
272       psa->cbElements = ulSize;
273       psa->rgsabound[0].cElements = cElements;
274       psa->rgsabound[0].lLbound = lLbound;
275
276       switch (vt)
277       {
278         case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
279         case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
280         case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
281         case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
282       }
283     }
284   }
285   return psa;
286 }
287
288 /* Free data items in an array */
289 static HRESULT SAFEARRAY_DestroyData(SAFEARRAY *psa, ULONG ulStartCell)
290 {
291   if (psa->pvData && !(psa->fFeatures & FADF_DATADELETED))
292   {
293     ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
294
295     if (ulStartCell > ulCellCount) {
296       FIXME("unexpted ulcellcount %ld, start %ld\n",ulCellCount,ulStartCell);
297       return E_UNEXPECTED;
298     }
299
300     ulCellCount -= ulStartCell;
301
302     if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
303     {
304       LPUNKNOWN *lpUnknown = (LPUNKNOWN *)psa->pvData + ulStartCell * psa->cbElements;
305
306       while(ulCellCount--)
307       {
308         if (*lpUnknown)
309           IUnknown_Release(*lpUnknown);
310         lpUnknown++;
311       }
312     }
313     else if (psa->fFeatures & (FADF_RECORD))
314     {
315       IRecordInfo *lpRecInfo;
316
317       if (SUCCEEDED(SafeArrayGetRecordInfo(psa, &lpRecInfo)))
318       {
319         PBYTE pRecordData = (PBYTE)psa->pvData;
320         while(ulCellCount--)
321         {
322           IRecordInfo_RecordClear(lpRecInfo, pRecordData);
323           pRecordData += psa->cbElements;
324         }
325         IRecordInfo_Release(lpRecInfo);
326       }
327     }
328     else if (psa->fFeatures & FADF_BSTR)
329     {
330       BSTR* lpBstr = (BSTR*)psa->pvData + ulStartCell * psa->cbElements;
331
332       while(ulCellCount--)
333       {
334         if (*lpBstr)
335           SysFreeString(*lpBstr);
336         lpBstr++;
337       }
338     }
339     else if (psa->fFeatures & FADF_VARIANT)
340     {
341       VARIANT* lpVariant = (VARIANT*)psa->pvData + ulStartCell * psa->cbElements;
342
343       while(ulCellCount--)
344       {
345         VariantClear(lpVariant);
346         lpVariant++;
347       }
348     }
349   }
350   return S_OK;
351 }
352
353 /* Copy data items from one array to another */
354 static HRESULT SAFEARRAY_CopyData(SAFEARRAY *psa, SAFEARRAY *dest)
355 {
356   if (!psa->pvData || !dest->pvData || psa->fFeatures & FADF_DATADELETED)
357     return E_INVALIDARG;
358   else
359   {
360     ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
361
362     dest->fFeatures = (dest->fFeatures & FADF_CREATEVECTOR) |
363                       (psa->fFeatures & ~(FADF_CREATEVECTOR|FADF_DATADELETED));
364
365     if (psa->fFeatures & FADF_VARIANT)
366     {
367       VARIANT* lpVariant = (VARIANT*)psa->pvData;
368       VARIANT* lpDest = (VARIANT*)dest->pvData;
369
370       while(ulCellCount--)
371       {
372         VariantCopy(lpDest, lpVariant);
373         lpVariant++;
374         lpDest++;
375       }
376     }
377     else if (psa->fFeatures & FADF_BSTR)
378     {
379       BSTR* lpBstr = (BSTR*)psa->pvData;
380       BSTR* lpDest = (BSTR*)dest->pvData;
381
382       while(ulCellCount--)
383       {
384         if (*lpBstr)
385         {
386           *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
387           if (!*lpDest)
388             return E_OUTOFMEMORY;
389         }
390         else
391           *lpDest = NULL;
392         lpBstr++;
393         lpDest++;
394       }
395     }
396     else
397     {
398       /* Copy the data over */
399       memcpy(dest->pvData, psa->pvData, ulCellCount * psa->cbElements);
400
401       if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
402       {
403         LPUNKNOWN *lpUnknown = (LPUNKNOWN *)dest->pvData;
404
405         while(ulCellCount--)
406         {
407           if (*lpUnknown)
408             IUnknown_AddRef(*lpUnknown);
409           lpUnknown++;
410         }
411       }
412     }
413
414     if (psa->fFeatures & FADF_RECORD)
415     {
416       IRecordInfo* pRecInfo = NULL;
417
418       SafeArrayGetRecordInfo(psa, &pRecInfo);
419       SafeArraySetRecordInfo(dest, pRecInfo);
420
421       if (pRecInfo)
422       {
423         /* Release because Get() adds a reference */
424         IRecordInfo_Release(pRecInfo);
425       }
426     }
427     else if (psa->fFeatures & FADF_HAVEIID)
428     {
429       GUID guid;
430       SafeArrayGetIID(psa, &guid);
431       SafeArraySetIID(dest, &guid);
432     }
433     else if (psa->fFeatures & FADF_HAVEVARTYPE)
434     {
435       SAFEARRAY_SetHiddenDWORD(dest, SAFEARRAY_GetHiddenDWORD(psa));
436     }
437   }
438   return S_OK;
439 }
440
441 /*************************************************************************
442  *              SafeArrayAllocDescriptor (OLEAUT32.36)
443  *
444  * Allocate and initialise a descriptor for a SafeArray.
445  *
446  * PARAMS
447  *  cDims   [I] Number of dimensions of the array
448  *  ppsaOut [O] Destination for new descriptor
449  *
450  * RETURNS
451  * Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
452  * Failure: An HRESULT error code indicating the error.
453  *
454  * NOTES
455  * See SafeArray.
456  */
457 HRESULT WINAPI SafeArrayAllocDescriptor(UINT cDims, SAFEARRAY **ppsaOut)
458 {
459   LONG allocSize;
460
461   TRACE("(%d,%p)\n", cDims, ppsaOut);
462   
463   if (!cDims || cDims >= 0x10000) /* Maximum 65535 dimensions */
464     return E_INVALIDARG;
465
466   if (!ppsaOut)
467     return E_POINTER;
468
469   /* We need enough space for the header and its bounds */
470   allocSize = sizeof(SAFEARRAY) + sizeof(SAFEARRAYBOUND) * (cDims - 1);
471
472   if (FAILED(SAFEARRAY_AllocDescriptor(allocSize, ppsaOut)))
473     return E_UNEXPECTED;
474
475   (*ppsaOut)->cDims = cDims;
476
477   TRACE("(%d): %lu bytes allocated for descriptor.\n", cDims, allocSize);
478   return S_OK;
479 }
480
481 /*************************************************************************
482  *              SafeArrayAllocDescriptorEx (OLEAUT32.41)
483  *
484  * Allocate and initialise a descriptor for a SafeArray of a given type.
485  *
486  * PARAMS
487  *  vt      [I] The type of items to store in the array
488  *  cDims   [I] Number of dimensions of the array
489  *  ppsaOut [O] Destination for new descriptor
490  *
491  * RETURNS
492  *  Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
493  *  Failure: An HRESULT error code indicating the error.
494  *
495  * NOTES
496  *  - This function does not chack that vt is an allowed VARTYPE.
497  *  - Unlike SafeArrayAllocDescriptor(), vt is associated with the array.
498  *  See SafeArray.
499  */
500 HRESULT WINAPI SafeArrayAllocDescriptorEx(VARTYPE vt, UINT cDims, SAFEARRAY **ppsaOut)
501 {
502   ULONG cbElements;
503   HRESULT hRet = E_UNEXPECTED;
504
505   TRACE("(%d->%s,%d,%p)\n", vt, debugstr_vt(vt), cDims, ppsaOut);
506     
507   cbElements = SAFEARRAY_GetVTSize(vt);
508   if (!cbElements)
509     WARN("Creating a descriptor with an invalid VARTYPE!\n");
510
511   hRet = SafeArrayAllocDescriptor(cDims, ppsaOut);
512
513   if (SUCCEEDED(hRet))
514   {
515     SAFEARRAY_SetFeatures(vt, *ppsaOut);
516     (*ppsaOut)->cbElements = cbElements;
517   }
518   return hRet;
519 }
520
521 /*************************************************************************
522  *              SafeArrayAllocData (OLEAUT32.37)
523  *
524  * Allocate the data area of a SafeArray.
525  *
526  * PARAMS
527  *  psa [I] SafeArray to allocate the data area of.
528  *
529  * RETURNS
530  *  Success: S_OK. The data area is allocated and initialised.
531  *  Failure: An HRESULT error code indicating the error.
532  *
533  * NOTES
534  *  See SafeArray.
535  */
536 HRESULT WINAPI SafeArrayAllocData(SAFEARRAY *psa)
537 {
538   HRESULT hRet = E_INVALIDARG;
539   
540   TRACE("(%p)\n", psa);
541   
542   if (psa)
543   {
544     ULONG ulSize = SAFEARRAY_GetCellCount(psa);
545
546     hRet = E_OUTOFMEMORY;
547
548     if (psa->cbElements)
549     {
550       psa->pvData = SAFEARRAY_Malloc(ulSize * psa->cbElements);
551
552       if (psa->pvData)
553       {
554         hRet = S_OK;
555         TRACE("%lu bytes allocated for data at %p (%lu objects).\n",
556               ulSize * psa->cbElements, psa->pvData, ulSize);
557       }
558     }
559   }
560   return hRet;
561 }
562
563 /*************************************************************************
564  *              SafeArrayCreate (OLEAUT32.15)
565  *
566  * Create a new SafeArray.
567  *
568  * PARAMS
569  *  vt        [I] Type to store in the safe array
570  *  cDims     [I] Number of array dimensions
571  *  rgsabound [I] Bounds of the array dimensions
572  *
573  * RETURNS
574  *  Success: A pointer to a new array object.
575  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
576  *
577  * NOTES
578  *  Win32 allows arrays with 0 sized dimensions. This bug is not reproduced
579  *  in the Wine implementation.
580  *  See SafeArray.
581  */
582 SAFEARRAY* WINAPI SafeArrayCreate(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound)
583 {
584   TRACE("(%d->%s,%d,%p)\n", vt, debugstr_vt(vt), cDims, rgsabound);
585
586   if (vt == VT_RECORD)
587     return NULL;
588
589   return SAFEARRAY_Create(vt, cDims, rgsabound, 0);
590 }
591
592 /*************************************************************************
593  *              SafeArrayCreateEx (OLEAUT32.15)
594  *
595  * Create a new SafeArray.
596  *
597  * PARAMS
598  *  vt        [I] Type to store in the safe array
599  *  cDims     [I] Number of array dimensions
600  *  rgsabound [I] Bounds of the array dimensions
601  *  pvExtra   [I] Extra data
602  *
603  * RETURNS
604  *  Success: A pointer to a new array object.
605  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
606  *
607  * NOTES
608  * See SafeArray.
609  */
610 SAFEARRAY* WINAPI SafeArrayCreateEx(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, LPVOID pvExtra)
611 {
612   ULONG ulSize = 0;
613   IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
614   SAFEARRAY* psa;
615  
616   TRACE("(%d->%s,%d,%p,%p)\n", vt, debugstr_vt(vt), cDims, rgsabound, pvExtra);
617  
618   if (vt == VT_RECORD)
619   {
620     if  (!iRecInfo)
621       return NULL;
622     IRecordInfo_GetSize(iRecInfo, &ulSize);
623   }
624   psa = SAFEARRAY_Create(vt, cDims, rgsabound, ulSize);
625
626   if (pvExtra)
627   {
628     switch(vt)
629     {
630       case VT_RECORD:
631         SafeArraySetRecordInfo(psa, pvExtra);
632         break;
633       case VT_UNKNOWN:
634       case VT_DISPATCH:
635         SafeArraySetIID(psa, pvExtra);
636         break;
637     }
638   }
639   return psa;
640 }
641
642 /************************************************************************
643  *              SafeArrayCreateVector (OLEAUT32.411)
644  *
645  * Create a one dimensional, contigous SafeArray.
646  *
647  * PARAMS
648  *  vt        [I] Type to store in the safe array
649  *  lLbound   [I] Lower bound of the array
650  *  cElements [I] Number of elements in the array
651  *
652  * RETURNS
653  *  Success: A pointer to a new array object.
654  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
655  *
656  * NOTES
657  * See SafeArray.
658  */
659 SAFEARRAY* WINAPI SafeArrayCreateVector(VARTYPE vt, LONG lLbound, ULONG cElements)
660 {
661   TRACE("(%d->%s,%ld,%ld\n", vt, debugstr_vt(vt), lLbound, cElements);
662     
663   if (vt == VT_RECORD)
664     return NULL;
665
666   return SAFEARRAY_CreateVector(vt, lLbound, cElements, SAFEARRAY_GetVTSize(vt));
667 }
668
669 /************************************************************************
670  *              SafeArrayCreateVectorEx (OLEAUT32.411)
671  *
672  * Create a one dimensional, contigous SafeArray.
673  *
674  * PARAMS
675  *  vt        [I] Type to store in the safe array
676  *  lLbound   [I] Lower bound of the array
677  *  cElements [I] Number of elements in the array
678  *  pvExtra   [I] Extra data
679  *
680  * RETURNS
681  *  Success: A pointer to a new array object.
682  *  Failure: NULL, if any parameter is invalid or memory allocation fails.
683  *
684  * NOTES
685  * See SafeArray.
686  */
687 SAFEARRAY* WINAPI SafeArrayCreateVectorEx(VARTYPE vt, LONG lLbound, ULONG cElements, LPVOID pvExtra)
688 {
689   ULONG ulSize;
690   IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
691   SAFEARRAY* psa;
692
693  TRACE("(%d->%s,%ld,%ld,%p\n", vt, debugstr_vt(vt), lLbound, cElements, pvExtra);
694  
695   if (vt == VT_RECORD)
696   {
697     if  (!iRecInfo)
698       return NULL;
699     IRecordInfo_GetSize(iRecInfo, &ulSize);
700   }
701   else
702     ulSize = SAFEARRAY_GetVTSize(vt);
703
704   psa = SAFEARRAY_CreateVector(vt, lLbound, cElements, ulSize);
705
706   if (pvExtra)
707   {
708     switch(vt)
709     {
710       case VT_RECORD:
711         SafeArraySetRecordInfo(psa, iRecInfo);
712         break;
713       case VT_UNKNOWN:
714       case VT_DISPATCH:
715         SafeArraySetIID(psa, pvExtra);
716         break;
717     }
718   }
719   return psa;
720 }
721
722 /*************************************************************************
723  *              SafeArrayDestroyDescriptor (OLEAUT32.38)
724  *
725  * Destroy a SafeArray.
726  *
727  * PARAMS
728  *  psa [I] SafeArray to destroy.
729  *
730  * RETURNS
731  *  Success: S_OK. The resources used by the array are freed.
732  *  Failure: An HRESULT error code indicating the error.
733  *
734  * NOTES
735  * See SafeArray.
736  */
737 HRESULT WINAPI SafeArrayDestroyDescriptor(SAFEARRAY *psa)
738 {
739   TRACE("(%p)\n", psa);
740     
741   if (psa)
742   {
743     LPVOID lpv = (char*)psa - SAFEARRAY_HIDDEN_SIZE;
744
745     if (psa->cLocks)
746       return DISP_E_ARRAYISLOCKED; /* Can't destroy a locked array */
747
748     if (psa->fFeatures & FADF_RECORD)
749       SafeArraySetRecordInfo(psa, NULL);
750
751     if (psa->fFeatures & FADF_CREATEVECTOR &&
752         !(psa->fFeatures & FADF_DATADELETED))
753         SAFEARRAY_DestroyData(psa, 0); /* Data not previously deleted */
754
755     if (!SAFEARRAY_Free(lpv))
756       return E_UNEXPECTED;
757   }
758   return S_OK;
759 }
760
761 /*************************************************************************
762  *              SafeArrayLock (OLEAUT32.21)
763  *
764  * Increment the lock counter of a SafeArray.
765  *
766  * PARAMS
767  *  psa [O] SafeArray to lock
768  *
769  * RETURNS
770  *  Success: S_OK. The array lock is incremented.
771  *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if too many locks
772  *           are held on the array at once.
773  *
774  * NOTES
775  *  In Win32 these locks are not thread safe.
776  *  See SafeArray.
777  */
778 HRESULT WINAPI SafeArrayLock(SAFEARRAY *psa)
779 {
780   ULONG ulLocks;
781
782   TRACE("(%p)\n", psa);
783     
784   if (!psa)
785     return E_INVALIDARG;
786
787   ulLocks = InterlockedIncrement(&psa->cLocks);
788
789   if (ulLocks > 0xffff) /* Maximum of 16384 locks at a time */
790   {
791     WARN("Out of locks!\n");
792     InterlockedDecrement(&psa->cLocks);
793     return E_UNEXPECTED;
794   }
795   return S_OK;
796 }
797
798 /*************************************************************************
799  *              SafeArrayUnlock (OLEAUT32.22)
800  *
801  * Decrement the lock counter of a SafeArray.
802  *
803  * PARAMS
804  *  psa [O] SafeArray to unlock
805  *
806  * RETURNS
807  *  Success: S_OK. The array lock is decremented.
808  *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if no locks are
809  *           held on the array.
810  *
811  * NOTES
812  * See SafeArray.
813  */
814 HRESULT WINAPI SafeArrayUnlock(SAFEARRAY *psa)
815 {
816   TRACE("(%p)\n", psa);
817   
818   if (!psa)
819     return E_INVALIDARG;
820
821   if ((LONG)InterlockedDecrement(&psa->cLocks) < 0)
822   {
823     WARN("Unlocked but no lock held!\n");
824     InterlockedIncrement(&psa->cLocks);
825     return E_UNEXPECTED;
826   }
827   return S_OK;
828 }
829
830 /*************************************************************************
831  *              SafeArrayPutElement (OLEAUT32.26)
832  *
833  * Put an item into a SafeArray.
834  *
835  * PARAMS
836  *  psa       [I] SafeArray to insert into
837  *  rgIndices [I] Indices to insert at
838  *  pvData    [I] Data to insert
839  *
840  * RETURNS
841  *  Success: S_OK. The item is inserted
842  *  Failure: An HRESULT error code indicating the error.
843  *
844  * NOTES
845  * See SafeArray.
846  */
847 HRESULT WINAPI SafeArrayPutElement(SAFEARRAY *psa, LONG *rgIndices, void *pvData)
848 {
849   HRESULT hRet;
850
851   TRACE("(%p,%p,%p)\n", psa, rgIndices, pvData);
852
853   if (!psa || !rgIndices)
854     return E_INVALIDARG;
855
856   if (!pvData)
857   {
858     ERR("Invalid pvData would crash under Win32!\n");
859     return E_INVALIDARG;
860   }
861
862   hRet = SafeArrayLock(psa);
863
864   if (SUCCEEDED(hRet))
865   {
866     PVOID lpvDest;
867
868     hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvDest);
869
870     if (SUCCEEDED(hRet))
871     {
872       if (psa->fFeatures & FADF_VARIANT)
873       {
874         VARIANT* lpVariant = (VARIANT*)pvData;
875         VARIANT* lpDest = (VARIANT*)lpvDest;
876
877         VariantClear(lpDest);
878         VariantCopy(lpDest, lpVariant);
879       }
880       else if (psa->fFeatures & FADF_BSTR)
881       {
882         BSTR  lpBstr = (BSTR)pvData;
883         BSTR* lpDest = (BSTR*)lpvDest;
884
885         if (*lpDest)
886          SysFreeString(*lpDest);
887
888         if (lpBstr)
889         {
890           *lpDest = SysAllocStringByteLen((char*)lpBstr, SysStringByteLen(lpBstr));
891           if (!*lpDest)
892             hRet = E_OUTOFMEMORY;
893         }
894         else
895           *lpDest = NULL;
896       }
897       else
898       {
899         if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
900         {
901           LPUNKNOWN  lpUnknown = (LPUNKNOWN)pvData;
902           LPUNKNOWN *lpDest = (LPUNKNOWN *)lpvDest;
903
904           if (lpUnknown)
905             IUnknown_AddRef(lpUnknown);
906           if (*lpDest)
907             IUnknown_Release(*lpDest);
908           *lpDest = lpUnknown;
909         } else {
910           /* Copy the data over */
911           memcpy(lpvDest, pvData, psa->cbElements);
912         }
913       }
914     }
915     SafeArrayUnlock(psa);
916   }
917   return hRet;
918 }
919
920
921 /*************************************************************************
922  *              SafeArrayGetElement (OLEAUT32.25)
923  *
924  * Get an item from a SafeArray.
925  *
926  * PARAMS
927  *  psa       [I] SafeArray to get from
928  *  rgIndices [I] Indices to get from
929  *  pvData    [O] Destination for data
930  *
931  * RETURNS
932  *  Success: S_OK. The item data is returned in pvData.
933  *  Failure: An HRESULT error code indicating the error.
934  *
935  * NOTES
936  * See SafeArray.
937  */
938 HRESULT WINAPI SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pvData)
939 {
940   HRESULT hRet;
941
942   TRACE("(%p,%p,%p)\n", psa, rgIndices, pvData);
943     
944   if (!psa || !rgIndices || !pvData)
945     return E_INVALIDARG;
946
947   hRet = SafeArrayLock(psa);
948
949   if (SUCCEEDED(hRet))
950   {
951     PVOID lpvSrc;
952
953     hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvSrc);
954
955     if (SUCCEEDED(hRet))
956     {
957       if (psa->fFeatures & FADF_VARIANT)
958       {
959         VARIANT* lpVariant = (VARIANT*)lpvSrc;
960         VARIANT* lpDest = (VARIANT*)pvData;
961
962         VariantCopy(lpDest, lpVariant);
963       }
964       else if (psa->fFeatures & FADF_BSTR)
965       {
966         BSTR* lpBstr = (BSTR*)lpvSrc;
967         BSTR* lpDest = (BSTR*)pvData;
968
969         if (*lpBstr)
970         {
971           *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
972           if (!*lpBstr)
973             hRet = E_OUTOFMEMORY;
974         }
975         else
976           *lpDest = NULL;
977       }
978       else
979       {
980         if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
981         {
982           LPUNKNOWN *lpUnknown = (LPUNKNOWN *)lpvSrc;
983
984           if (*lpUnknown)
985             IUnknown_AddRef(*lpUnknown);
986         }
987         /* Copy the data over */
988         memcpy(pvData, lpvSrc, psa->cbElements);
989       }
990     }
991     SafeArrayUnlock(psa);
992   }
993   return hRet;
994 }
995
996 /*************************************************************************
997  *              SafeArrayGetUBound (OLEAUT32.19)
998  *
999  * Get the upper bound for a given SafeArray dimension
1000  *
1001  * PARAMS
1002  *  psa      [I] Array to get dimension upper bound from
1003  *  nDim     [I] The dimension number to get the upper bound of
1004  *  plUbound [O] Destination for the upper bound
1005  *
1006  * RETURNS
1007  *  Success: S_OK. plUbound contains the dimensions upper bound.
1008  *  Failure: An HRESULT error code indicating the error.
1009  *
1010  * NOTES
1011  * See SafeArray.
1012  */
1013 HRESULT WINAPI SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound)
1014 {
1015   TRACE("(%p,%d,%p)\n", psa, nDim, plUbound);
1016     
1017   if (!psa || !plUbound)
1018     return E_INVALIDARG;
1019
1020   if(!nDim || nDim > psa->cDims)
1021     return DISP_E_BADINDEX;
1022
1023   *plUbound = psa->rgsabound[nDim - 1].lLbound +
1024               psa->rgsabound[nDim - 1].cElements - 1;
1025
1026   return S_OK;
1027 }
1028
1029 /*************************************************************************
1030  *              SafeArrayGetLBound (OLEAUT32.20)
1031  *
1032  * Get the lower bound for a given SafeArray dimension
1033  *
1034  * PARAMS
1035  *  psa      [I] Array to get dimension lower bound from
1036  *  nDim     [I] The dimension number to get the lowe bound of
1037  *  plLbound [O] Destination for the lower bound
1038  *
1039  * RETURNS
1040  *  Success: S_OK. plUbound contains the dimensions lower bound.
1041  *  Failure: An HRESULT error code indicating the error.
1042  *
1043  * NOTES
1044  * See SafeArray.
1045  */
1046 HRESULT WINAPI SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound)
1047 {
1048   TRACE("(%p,%d,%p)\n", psa, nDim, plLbound);
1049
1050   if (!psa || !plLbound)
1051     return E_INVALIDARG;
1052
1053   if(!nDim || nDim > psa->cDims)
1054     return DISP_E_BADINDEX;
1055
1056   *plLbound = psa->rgsabound[nDim - 1].lLbound;
1057   return S_OK;
1058 }
1059
1060 /*************************************************************************
1061  *              SafeArrayGetDim (OLEAUT32.17)
1062  *
1063  * Get the number of dimensions in a SafeArray.
1064  *
1065  * PARAMS
1066  *  psa [I] Array to get the dimensions of
1067  *
1068  * RETURNS
1069  *  The number of array dimensions in psa, or 0 if psa is NULL.
1070  *
1071  * NOTES
1072  * See SafeArray.
1073  */
1074 UINT WINAPI SafeArrayGetDim(SAFEARRAY *psa)
1075 {
1076   TRACE("(%p) returning %ld\n", psa, psa ? psa->cDims : 0ul);  
1077   return psa ? psa->cDims : 0;
1078 }
1079
1080 /*************************************************************************
1081  *              SafeArrayGetElemsize (OLEAUT32.18)
1082  *
1083  * Get the size of an element in a SafeArray.
1084  *
1085  * PARAMS
1086  *  psa [I] Array to get the element size from
1087  *
1088  * RETURNS
1089  *  The size of a single element in psa, or 0 if psa is NULL.
1090  *
1091  * NOTES
1092  * See SafeArray.
1093  */
1094 UINT WINAPI SafeArrayGetElemsize(SAFEARRAY *psa)
1095 {
1096   TRACE("(%p) returning %ld\n", psa, psa ? psa->cbElements : 0ul);
1097   return psa ? psa->cbElements : 0;
1098 }
1099
1100 /*************************************************************************
1101  *              SafeArrayAccessData (OLEAUT32.23)
1102  *
1103  * Lock a SafeArray and return a pointer to its data.
1104  *
1105  * PARAMS
1106  *  psa     [I] Array to get the data pointer from
1107  *  ppvData [O] Destination for the arrays data pointer
1108  *
1109  * RETURNS
1110  *  Success: S_OK. ppvData contains the arrays data pointer, and the array
1111  *           is locked.
1112  *  Failure: An HRESULT error code indicating the error.
1113  *
1114  * NOTES
1115  * See SafeArray.
1116  */
1117 HRESULT WINAPI SafeArrayAccessData(SAFEARRAY *psa, void **ppvData)
1118 {
1119   TRACE("(%p,%p)\n", psa, ppvData);
1120
1121   if(!psa || !ppvData)
1122     return E_INVALIDARG;
1123
1124   if (SUCCEEDED(SafeArrayLock(psa)))
1125   {
1126     *ppvData = psa->pvData;
1127     return S_OK;
1128   }
1129   *ppvData = NULL;
1130   return E_UNEXPECTED;
1131 }
1132
1133
1134 /*************************************************************************
1135  *              SafeArrayUnaccessData (OLEAUT32.24)
1136  *
1137  * Unlock a SafeArray after accessing its data.
1138  *
1139  * PARAMS
1140  *  psa     [I] Array to unlock
1141  *
1142  * RETURNS
1143  *  Success: S_OK. The array is unlocked.
1144  *  Failure: An HRESULT error code indicating the error.
1145  *
1146  * NOTES
1147  * See SafeArray.
1148  */
1149 HRESULT WINAPI SafeArrayUnaccessData(SAFEARRAY *psa)
1150 {
1151   TRACE("(%p)\n", psa);
1152   return SafeArrayUnlock(psa);
1153 }
1154
1155 /************************************************************************
1156  *              SafeArrayPtrOfIndex (OLEAUT32.148)
1157  *
1158  * Get the address of an item in a SafeArray.
1159  *
1160  * PARAMS
1161  *  psa       [I] Array to get the items address from
1162  *  rgIndices [I] Index of the item in the array
1163  *  ppvData   [O] Destination for item address
1164  *
1165  * RETURNS
1166  *  Success: S_OK. ppvData contains a pointer to the item.
1167  *  Failure: An HRESULT error code indicating the error.
1168  *
1169  * NOTES
1170  *  This function does not lock the array.
1171  *
1172  * NOTES
1173  * See SafeArray.
1174  */
1175 HRESULT WINAPI SafeArrayPtrOfIndex(SAFEARRAY *psa, LONG *rgIndices, void **ppvData)
1176 {
1177   USHORT dim;
1178   ULONG cell = 0, dimensionSize = 1;
1179   SAFEARRAYBOUND* psab;
1180   LONG c1;
1181
1182   TRACE("(%p,%p,%p)\n", psa, rgIndices, ppvData);
1183   
1184   /* The general formula for locating the cell number of an entry in an n
1185    * dimensional array (where cn = coordinate in dimension dn) is:
1186    *
1187    * c1 + c2 * sizeof(d1) + c3 * sizeof(d2) ... + cn * sizeof(c(n-1))
1188    *
1189    * We calculate the size of the last dimension at each step through the
1190    * dimensions to avoid recursing to calculate the last dimensions size.
1191    */
1192   if (!psa || !rgIndices || !ppvData)
1193     return E_INVALIDARG;
1194
1195   psab = psa->rgsabound;
1196   c1 = *rgIndices++;
1197
1198   if (c1 < psab->lLbound || c1 >= psab->lLbound + (LONG)psab->cElements)
1199     return DISP_E_BADINDEX; /* Initial index out of bounds */
1200
1201   for (dim = 1; dim < psa->cDims; dim++)
1202   {
1203     dimensionSize *= psab->cElements;
1204
1205     psab++;
1206
1207     if (!psab->cElements ||
1208         *rgIndices < psab->lLbound ||
1209         *rgIndices >= psab->lLbound + (LONG)psab->cElements)
1210     return DISP_E_BADINDEX; /* Index out of bounds */
1211
1212     cell += (*rgIndices - psab->lLbound) * dimensionSize;
1213     rgIndices++;
1214   }
1215
1216   cell += (c1 - psa->rgsabound[0].lLbound);
1217
1218   *ppvData = (char*)psa->pvData + cell * psa->cbElements;
1219   return S_OK;
1220 }
1221
1222 /************************************************************************
1223  *              SafeArrayDestroyData (OLEAUT32.39)
1224  *
1225  * Destroy the data associated with a SafeArray.
1226  *
1227  * PARAMS
1228  *  psa [I] Array to delete the data from
1229  *
1230  * RETURNS
1231  *  Success: S_OK. All items and the item data are freed.
1232  *  Failure: An HRESULT error code indicating the error.
1233  *
1234  * NOTES
1235  * See SafeArray.
1236  */
1237 HRESULT WINAPI SafeArrayDestroyData(SAFEARRAY *psa)
1238 {
1239   TRACE("(%p)\n", psa);
1240   
1241   if (!psa)
1242     return E_INVALIDARG;
1243
1244   if (psa->cLocks)
1245     return DISP_E_ARRAYISLOCKED; /* Cant delete a locked array */
1246
1247   if (psa->pvData)
1248   {
1249     /* Delete the actual item data */
1250     if (FAILED(SAFEARRAY_DestroyData(psa, 0)))
1251       return E_UNEXPECTED;
1252
1253     /* If this is not a vector, free the data memory block */
1254     if (!(psa->fFeatures & FADF_CREATEVECTOR))
1255     {
1256       if (!SAFEARRAY_Free(psa->pvData))
1257         return E_UNEXPECTED;
1258       psa->pvData = NULL;
1259     }
1260     else
1261       psa->fFeatures |= FADF_DATADELETED; /* Mark the data deleted */
1262
1263   }
1264   return S_OK;
1265 }
1266
1267 /************************************************************************
1268  *              SafeArrayCopyData (OLEAUT32.412)
1269  *
1270  * Copy all data from one SafeArray to another.
1271  *
1272  * PARAMS
1273  *  psaSource [I] Source for copy
1274  *  psaTarget [O] Destination for copy
1275  *
1276  * RETURNS
1277  *  Success: S_OK. psaTarget contains a copy of psaSource.
1278  *  Failure: An HRESULT error code indicating the error.
1279  *
1280  * NOTES
1281  *  The two arrays must have the same number of dimensions and elements.
1282  *
1283  * NOTES
1284  * See SafeArray.
1285  */
1286 HRESULT WINAPI SafeArrayCopyData(SAFEARRAY *psaSource, SAFEARRAY *psaTarget)
1287 {
1288   int dim;
1289
1290   TRACE("(%p,%p)\n", psaSource, psaTarget);
1291   
1292   if (!psaSource || !psaTarget ||
1293       psaSource->cDims != psaTarget->cDims ||
1294       psaSource->cbElements != psaTarget->cbElements)
1295     return E_INVALIDARG;
1296
1297   /* Each dimension must be the same size */
1298   for (dim = psaSource->cDims - 1; dim >= 0 ; dim--)
1299     if (psaSource->rgsabound[dim].cElements !=
1300        psaTarget->rgsabound[dim].cElements)
1301       return E_INVALIDARG;
1302
1303   if (SUCCEEDED(SAFEARRAY_DestroyData(psaTarget, 0)) &&
1304       SUCCEEDED(SAFEARRAY_CopyData(psaSource, psaTarget)))
1305     return S_OK;
1306   return E_UNEXPECTED;
1307 }
1308
1309 /************************************************************************
1310  *              SafeArrayDestroy (OLEAUT32.16)
1311  *
1312  * Destroy a SafeArray.
1313  *
1314  * PARAMS
1315  *  psa [I] Array to destroy
1316  *
1317  * RETURNS
1318  *  Success: S_OK. All resources used by the array are freed.
1319  *  Failure: An HRESULT error code indicating the error.
1320  *
1321  * NOTES
1322  * See SafeArray.
1323  */
1324 HRESULT WINAPI SafeArrayDestroy(SAFEARRAY *psa)
1325 {
1326   TRACE("(%p)\n", psa);
1327
1328   if(!psa)
1329     return E_INVALIDARG;
1330
1331   if(psa->cLocks > 0)
1332     return DISP_E_ARRAYISLOCKED;
1333
1334   /* Native doesn't check to see if the free succeeds */
1335   SafeArrayDestroyData(psa);
1336   SafeArrayDestroyDescriptor(psa);
1337   return S_OK;
1338 }
1339
1340 /************************************************************************
1341  *              SafeArrayCopy (OLEAUT32.27)
1342  *
1343  * Make a duplicate of a SafeArray.
1344  *
1345  * PARAMS
1346  *  psa     [I] Source for copy
1347  *  ppsaOut [O] Destination for new copy
1348  *
1349  * RETURNS
1350  *  Success: S_OK. ppsaOut contains a copy of the array.
1351  *  Failure: An HRESULT error code indicating the error.
1352  *
1353  * NOTES
1354  * See SafeArray.
1355  */
1356 HRESULT WINAPI SafeArrayCopy(SAFEARRAY *psa, SAFEARRAY **ppsaOut)
1357 {
1358   HRESULT hRet;
1359
1360   TRACE("(%p,%p)\n", psa, ppsaOut);
1361
1362   if (!ppsaOut)
1363     return E_INVALIDARG;
1364
1365   *ppsaOut = NULL;
1366
1367   if (!psa)
1368     return S_OK; /* Handles copying of NULL arrays */
1369
1370   if (psa->fFeatures & (FADF_RECORD|FADF_HAVEIID|FADF_HAVEVARTYPE))
1371   {
1372     VARTYPE vt;
1373     if (FAILED(SafeArrayGetVartype(psa, &vt)))
1374       hRet = E_UNEXPECTED;
1375     else
1376       hRet = SafeArrayAllocDescriptorEx(vt, psa->cDims, ppsaOut);
1377   }
1378   else
1379   {
1380     hRet = SafeArrayAllocDescriptor(psa->cDims, ppsaOut);
1381     if (SUCCEEDED(hRet))
1382     {
1383       (*ppsaOut)->fFeatures = psa->fFeatures & ~FADF_CREATEVECTOR;
1384       (*ppsaOut)->cbElements = psa->cbElements;
1385     }
1386   }
1387
1388   if (SUCCEEDED(hRet))
1389   {
1390     /* Copy dimension bounds */
1391     memcpy((*ppsaOut)->rgsabound, psa->rgsabound, psa->cDims * sizeof(SAFEARRAYBOUND));
1392
1393     (*ppsaOut)->pvData = SAFEARRAY_Malloc(SAFEARRAY_GetCellCount(psa) * psa->cbElements);
1394
1395     if ((*ppsaOut)->pvData)
1396     {
1397       hRet = SAFEARRAY_CopyData(psa, *ppsaOut);
1398  
1399       if (SUCCEEDED(hRet))
1400         return hRet;
1401
1402       SAFEARRAY_Free((*ppsaOut)->pvData);
1403     }
1404     SafeArrayDestroyDescriptor(*ppsaOut);
1405   }
1406   *ppsaOut = NULL;
1407   return hRet;
1408 }
1409
1410 /************************************************************************
1411  *              SafeArrayRedim (OLEAUT32.40)
1412  *
1413  * Changes the characteristics of the last dimension of a SafeArray
1414  *
1415  * PARAMS
1416  *  psa      [I] Array to change
1417  *  psabound [I] New bound details for the last dimension
1418  *
1419  * RETURNS
1420  *  Success: S_OK. psa is updated to reflect the new bounds.
1421  *  Failure: An HRESULT error code indicating the error.
1422  *
1423  * NOTES
1424  * See SafeArray.
1425  */
1426 HRESULT WINAPI SafeArrayRedim(SAFEARRAY *psa, SAFEARRAYBOUND *psabound)
1427 {
1428   SAFEARRAYBOUND *oldBounds;
1429
1430   TRACE("(%p,%p)\n", psa, psabound);
1431   
1432   if (!psa || psa->fFeatures & FADF_FIXEDSIZE || !psabound)
1433     return E_INVALIDARG;
1434
1435   if (psa->cLocks > 0)
1436     return DISP_E_ARRAYISLOCKED;
1437
1438   if (FAILED(SafeArrayLock(psa)))
1439     return E_UNEXPECTED;
1440
1441   oldBounds = &psa->rgsabound[psa->cDims - 1];
1442   oldBounds->lLbound = psabound->lLbound;
1443
1444   if (psabound->cElements != oldBounds->cElements)
1445   {
1446     if (psabound->cElements < oldBounds->cElements)
1447     {
1448       /* Shorten the final dimension. */
1449       ULONG ulStartCell = psa->cDims == 1 ? 0 : SAFEARRAY_GetDimensionCells(psa, psa->cDims - 1);
1450
1451       ulStartCell += psabound->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 }