safearray.c 42.5 KB
Newer Older
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 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 25 26
/* Memory Layout of a SafeArray:
 *
 * -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 31 32
 *  0x00: SAFEARRAY,
 *  0x10: SAFEARRAYBOUNDS[0...]
 */
33

34 35
#include "config.h"

36
#include <string.h>
37
#include <stdarg.h>
38
#include <stdio.h>
39 40 41

#define COBJMACROS

42
#include "windef.h"
43 44
#include "winerror.h"
#include "winbase.h"
45
#include "variant.h"
46
#include "wine/debug.h"
47

48
WINE_DEFAULT_DEBUG_CHANNEL(variant);
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/************************************************************************
 * SafeArray {OLEAUT32}
 *
 * NOTES
 * The SafeArray data type provides the underlying interface for Ole
 * Automations arrays, used for example to represent array types in
 * Visual Basic(tm) and to gather user defined parameters for invocation through
 * an IDispatch interface.
 *
 * Safe arrays provide bounds checking and automatically manage the data
 * types they contain, for example handing reference counting and copying
 * of interface pointers. User defined types can be stored in arrays
 * using the IRecordInfo interface.
 *
 * There are two types of SafeArray, normal and vectors. Normal arrays can have
65 66
 * multiple dimensions and the data for the array is allocated separately from
 * the array header. This is the most flexible type of array. Vectors, on the
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
 * other hand, are fixed in size and consist of a single allocated block, and a
 * single dimension.
 *
 * DATATYPES
 * The following types of data can be stored within a SafeArray.
 * Numeric:
 *|  VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_I8, VT_UI8, VT_INT, VT_UINT,
 *|  VT_R4, VT_R8, VT_CY, VT_DECIMAL
 * Interfaces:
 *|  VT_DISPATCH, VT_UNKNOWN, VT_RECORD
 * Other:
 *|  VT_VARIANT, VT_INT_PTR, VT_UINT_PTR, VT_BOOL, VT_ERROR, VT_DATE, VT_BSTR
 *
 * FUNCTIONS
 *  BstrFromVector()
 *  VectorFromBstr()
 */

/* Undocumented hidden space before the start of a SafeArray descriptor */
#define SAFEARRAY_HIDDEN_SIZE sizeof(GUID)

/* Allocate memory */
static inline LPVOID SAFEARRAY_Malloc(ULONG ulSize)
{
  /* FIXME: Memory should be allocated and freed using a per-thread IMalloc
   *        instance returned from CoGetMalloc().
   */
  return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulSize);
}

/* Free memory */
static inline BOOL SAFEARRAY_Free(LPVOID lpData)
{
  return HeapFree(GetProcessHeap(), 0, lpData);
}

/* Get the size of a supported VT type (0 means unsupported) */
static DWORD SAFEARRAY_GetVTSize(VARTYPE vt)
{
  switch (vt)
  {
    case VT_I1:
    case VT_UI1:      return sizeof(BYTE);
    case VT_BOOL:
    case VT_I2:
    case VT_UI2:      return sizeof(SHORT);
    case VT_I4:
    case VT_UI4:
    case VT_R4:
    case VT_ERROR:    return sizeof(LONG);
    case VT_R8:
    case VT_I8:
    case VT_UI8:      return sizeof(LONG64);
    case VT_INT:
    case VT_UINT:     return sizeof(INT);
    case VT_INT_PTR:
    case VT_UINT_PTR: return sizeof(UINT_PTR);
    case VT_CY:       return sizeof(CY);
    case VT_DATE:     return sizeof(DATE);
    case VT_BSTR:     return sizeof(BSTR);
    case VT_DISPATCH: return sizeof(LPDISPATCH);
    case VT_VARIANT:  return sizeof(VARIANT);
    case VT_UNKNOWN:  return sizeof(LPUNKNOWN);
    case VT_DECIMAL:  return sizeof(DECIMAL);
    /* Note: Return a non-zero size to indicate vt is valid. The actual size
     * of a UDT is taken from the result of IRecordInfo_GetSize().
     */
    case VT_RECORD:   return 32;
  }
  return 0;
}

/* Set the hidden data for an array */
static inline void SAFEARRAY_SetHiddenDWORD(SAFEARRAY* psa, DWORD dw)
{
  /* Implementation data is stored in the 4 bytes before the header */
  LPDWORD lpDw = (LPDWORD)psa;
  lpDw[-1] = dw;
}

/* Get the hidden data from an array */
static inline DWORD SAFEARRAY_GetHiddenDWORD(SAFEARRAY* psa)
{
  LPDWORD lpDw = (LPDWORD)psa;
  return lpDw[-1];
}

/* Get the number of cells in a SafeArray */
static ULONG SAFEARRAY_GetCellCount(const SAFEARRAY *psa)
{
157
  const SAFEARRAYBOUND* psab = psa->rgsabound;
158 159
  USHORT cCount = psa->cDims;
  ULONG ulNumCells = 1;
160

161 162
  while (cCount--)
  {
163
    /* This is a valid bordercase. See testcases. -Marcus */
164
    if (!psab->cElements)
165
      return 0;
166 167 168 169 170
    ulNumCells *= psab->cElements;
    psab++;
  }
  return ulNumCells;
}
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/* Allocate a descriptor for an array */
static HRESULT SAFEARRAY_AllocDescriptor(ULONG ulSize, SAFEARRAY **ppsaOut)
{
  *ppsaOut = (SAFEARRAY*)((char*)SAFEARRAY_Malloc(ulSize + SAFEARRAY_HIDDEN_SIZE) + SAFEARRAY_HIDDEN_SIZE);

  if (!*ppsaOut)
    return E_UNEXPECTED;

  return S_OK;
}

/* Set the features of an array */
static void SAFEARRAY_SetFeatures(VARTYPE vt, SAFEARRAY *psa)
{
  /* Set the IID if we have one, otherwise set the type */
  if (vt == VT_DISPATCH)
  {
    psa->fFeatures = FADF_HAVEIID;
    SafeArraySetIID(psa, &IID_IDispatch);
  }
  else if (vt == VT_UNKNOWN)
  {
    psa->fFeatures = FADF_HAVEIID;
    SafeArraySetIID(psa, &IID_IUnknown);
  }
  else if (vt == VT_RECORD)
    psa->fFeatures = FADF_RECORD;
  else
  {
    psa->fFeatures = FADF_HAVEVARTYPE;
    SAFEARRAY_SetHiddenDWORD(psa, vt);
  }
}

/* Create an array */
static SAFEARRAY* SAFEARRAY_Create(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, ULONG ulSize)
{
  SAFEARRAY *psa = NULL;
210
  int i;
211 212 213 214 215 216 217 218 219 220 221 222 223 224

  if (!rgsabound)
    return NULL;

  if (SUCCEEDED(SafeArrayAllocDescriptorEx(vt, cDims, &psa)))
  {
    switch (vt)
    {
      case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
      case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
      case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
      case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
    }

225 226
    for (i = 0; i < cDims; i++)
      memcpy(psa->rgsabound + i, rgsabound + cDims - 1 - i, sizeof(SAFEARRAYBOUND));
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

    if (ulSize)
      psa->cbElements = ulSize;

    if (FAILED(SafeArrayAllocData(psa)))
    {
      SafeArrayDestroyDescriptor(psa);
      psa = NULL;
    }
  }
  return psa;
}

/* Create an array as a vector */
static SAFEARRAY* SAFEARRAY_CreateVector(VARTYPE vt, LONG lLbound, ULONG cElements, ULONG ulSize)
{
  SAFEARRAY *psa = NULL;

245
  if (ulSize || (vt == VT_RECORD))
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  {
    /* Allocate the header and data together */
    if (SUCCEEDED(SAFEARRAY_AllocDescriptor(sizeof(SAFEARRAY) + ulSize * cElements, &psa)))
    {
      SAFEARRAY_SetFeatures(vt, psa);

      psa->cDims = 1;
      psa->fFeatures |= FADF_CREATEVECTOR;
      psa->pvData = &psa[1]; /* Data follows the header */
      psa->cbElements = ulSize;
      psa->rgsabound[0].cElements = cElements;
      psa->rgsabound[0].lLbound = lLbound;

      switch (vt)
      {
        case VT_BSTR:     psa->fFeatures |= FADF_BSTR; break;
        case VT_UNKNOWN:  psa->fFeatures |= FADF_UNKNOWN; break;
        case VT_DISPATCH: psa->fFeatures |= FADF_DISPATCH; break;
        case VT_VARIANT:  psa->fFeatures |= FADF_VARIANT; break;
      }
    }
  }
  return psa;
}
270

271 272 273 274 275 276
/* Free data items in an array */
static HRESULT SAFEARRAY_DestroyData(SAFEARRAY *psa, ULONG ulStartCell)
{
  if (psa->pvData && !(psa->fFeatures & FADF_DATADELETED))
  {
    ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
277

278
    if (ulStartCell > ulCellCount) {
279
      FIXME("unexpted ulcellcount %d, start %d\n",ulCellCount,ulStartCell);
280
      return E_UNEXPECTED;
281
    }
282

283
    ulCellCount -= ulStartCell;
284

285 286
    if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
    {
287
      LPUNKNOWN *lpUnknown = (LPUNKNOWN *)psa->pvData + ulStartCell;
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
      while(ulCellCount--)
      {
        if (*lpUnknown)
          IUnknown_Release(*lpUnknown);
        lpUnknown++;
      }
    }
    else if (psa->fFeatures & (FADF_RECORD))
    {
      IRecordInfo *lpRecInfo;

      if (SUCCEEDED(SafeArrayGetRecordInfo(psa, &lpRecInfo)))
      {
        PBYTE pRecordData = (PBYTE)psa->pvData;
        while(ulCellCount--)
        {
          IRecordInfo_RecordClear(lpRecInfo, pRecordData);
          pRecordData += psa->cbElements;
        }
        IRecordInfo_Release(lpRecInfo);
      }
    }
    else if (psa->fFeatures & FADF_BSTR)
    {
313
      BSTR* lpBstr = (BSTR*)psa->pvData + ulStartCell;
314 315 316 317 318 319 320 321 322 323

      while(ulCellCount--)
      {
        if (*lpBstr)
          SysFreeString(*lpBstr);
        lpBstr++;
      }
    }
    else if (psa->fFeatures & FADF_VARIANT)
    {
324
      VARIANT* lpVariant = (VARIANT*)psa->pvData + ulStartCell;
325 326 327

      while(ulCellCount--)
      {
328 329 330
        HRESULT hRet = VariantClear(lpVariant);

        if (FAILED(hRet)) FIXME("VariantClear of element failed!\n");
331 332 333 334 335 336
        lpVariant++;
      }
    }
  }
  return S_OK;
}
337

338 339
/* Copy data items from one array to another */
static HRESULT SAFEARRAY_CopyData(SAFEARRAY *psa, SAFEARRAY *dest)
340
{
341 342 343
  if (!psa->pvData)
    return S_OK;
  else if (!dest->pvData || psa->fFeatures & FADF_DATADELETED)
344 345 346 347
    return E_INVALIDARG;
  else
  {
    ULONG ulCellCount = SAFEARRAY_GetCellCount(psa);
348

349 350 351 352 353 354 355 356 357 358
    dest->fFeatures = (dest->fFeatures & FADF_CREATEVECTOR) |
                      (psa->fFeatures & ~(FADF_CREATEVECTOR|FADF_DATADELETED));

    if (psa->fFeatures & FADF_VARIANT)
    {
      VARIANT* lpVariant = (VARIANT*)psa->pvData;
      VARIANT* lpDest = (VARIANT*)dest->pvData;

      while(ulCellCount--)
      {
359 360 361
        HRESULT hRet;

        hRet = VariantCopy(lpDest, lpVariant);
362
        if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%x\n", hRet);
363 364 365 366 367 368 369 370 371 372 373 374 375
        lpVariant++;
        lpDest++;
      }
    }
    else if (psa->fFeatures & FADF_BSTR)
    {
      BSTR* lpBstr = (BSTR*)psa->pvData;
      BSTR* lpDest = (BSTR*)dest->pvData;

      while(ulCellCount--)
      {
        if (*lpBstr)
        {
Marcus Meissner's avatar
Marcus Meissner committed
376
          *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
          if (!*lpDest)
            return E_OUTOFMEMORY;
        }
        else
          *lpDest = NULL;
        lpBstr++;
        lpDest++;
      }
    }
    else
    {
      /* Copy the data over */
      memcpy(dest->pvData, psa->pvData, ulCellCount * psa->cbElements);

      if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
      {
        LPUNKNOWN *lpUnknown = (LPUNKNOWN *)dest->pvData;

        while(ulCellCount--)
        {
          if (*lpUnknown)
            IUnknown_AddRef(*lpUnknown);
          lpUnknown++;
        }
      }
    }

    if (psa->fFeatures & FADF_RECORD)
    {
      IRecordInfo* pRecInfo = NULL;

      SafeArrayGetRecordInfo(psa, &pRecInfo);
      SafeArraySetRecordInfo(dest, pRecInfo);

      if (pRecInfo)
      {
        /* Release because Get() adds a reference */
        IRecordInfo_Release(pRecInfo);
      }
    }
    else if (psa->fFeatures & FADF_HAVEIID)
    {
      GUID guid;
      SafeArrayGetIID(psa, &guid);
      SafeArraySetIID(dest, &guid);
    }
    else if (psa->fFeatures & FADF_HAVEVARTYPE)
    {
      SAFEARRAY_SetHiddenDWORD(dest, SAFEARRAY_GetHiddenDWORD(psa));
    }
  }
  return S_OK;
}
430

431
/*************************************************************************
432
 *		SafeArrayAllocDescriptor (OLEAUT32.36)
433 434 435 436 437 438 439 440 441 442 443 444 445
 *
 * Allocate and initialise a descriptor for a SafeArray.
 *
 * PARAMS
 *  cDims   [I] Number of dimensions of the array
 *  ppsaOut [O] Destination for new descriptor
 *
 * RETURNS
 * Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
 * Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
446
 */
447
HRESULT WINAPI SafeArrayAllocDescriptor(UINT cDims, SAFEARRAY **ppsaOut)
448
{
449
  LONG allocSize;
450

451 452 453
  TRACE("(%d,%p)\n", cDims, ppsaOut);
  
  if (!cDims || cDims >= 0x10000) /* Maximum 65535 dimensions */
454
    return E_INVALIDARG;
455

456 457 458
  if (!ppsaOut)
    return E_POINTER;

459 460
  /* We need enough space for the header and its bounds */
  allocSize = sizeof(SAFEARRAY) + sizeof(SAFEARRAYBOUND) * (cDims - 1);
461

462 463
  if (FAILED(SAFEARRAY_AllocDescriptor(allocSize, ppsaOut)))
    return E_UNEXPECTED;
464

465 466
  (*ppsaOut)->cDims = cDims;

467
  TRACE("(%d): %u bytes allocated for descriptor.\n", cDims, allocSize);
468
  return S_OK;
469 470
}

Bill Medland's avatar
Bill Medland committed
471
/*************************************************************************
472
 *		SafeArrayAllocDescriptorEx (OLEAUT32.41)
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
 *
 * Allocate and initialise a descriptor for a SafeArray of a given type.
 *
 * PARAMS
 *  vt      [I] The type of items to store in the array
 *  cDims   [I] Number of dimensions of the array
 *  ppsaOut [O] Destination for new descriptor
 *
 * RETURNS
 *  Success: S_OK. ppsaOut is filled with a newly allocated descriptor.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 *  - This function does not chack that vt is an allowed VARTYPE.
 *  - Unlike SafeArrayAllocDescriptor(), vt is associated with the array.
 *  See SafeArray.
Bill Medland's avatar
Bill Medland committed
489
 */
490
HRESULT WINAPI SafeArrayAllocDescriptorEx(VARTYPE vt, UINT cDims, SAFEARRAY **ppsaOut)
Bill Medland's avatar
Bill Medland committed
491
{
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  ULONG cbElements;
  HRESULT hRet = E_UNEXPECTED;

  TRACE("(%d->%s,%d,%p)\n", vt, debugstr_vt(vt), cDims, ppsaOut);
    
  cbElements = SAFEARRAY_GetVTSize(vt);
  if (!cbElements)
    WARN("Creating a descriptor with an invalid VARTYPE!\n");

  hRet = SafeArrayAllocDescriptor(cDims, ppsaOut);

  if (SUCCEEDED(hRet))
  {
    SAFEARRAY_SetFeatures(vt, *ppsaOut);
    (*ppsaOut)->cbElements = cbElements;
507
  }
508
  return hRet;
Bill Medland's avatar
Bill Medland committed
509 510
}

511
/*************************************************************************
512
 *		SafeArrayAllocData (OLEAUT32.37)
513 514 515 516 517 518 519 520 521 522 523 524
 *
 * Allocate the data area of a SafeArray.
 *
 * PARAMS
 *  psa [I] SafeArray to allocate the data area of.
 *
 * RETURNS
 *  Success: S_OK. The data area is allocated and initialised.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 *  See SafeArray.
525
 */
526
HRESULT WINAPI SafeArrayAllocData(SAFEARRAY *psa)
527
{
528 529 530 531 532 533 534
  HRESULT hRet = E_INVALIDARG;
  
  TRACE("(%p)\n", psa);
  
  if (psa)
  {
    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 543 544
      if (psa->pvData)
      {
        hRet = S_OK;
545
        TRACE("%u bytes allocated for data at %p (%u objects).\n",
546 547 548 549 550
              ulSize * psa->cbElements, psa->pvData, ulSize);
      }
    }
  }
  return hRet;
551 552 553
}

/*************************************************************************
554
 *		SafeArrayCreate (OLEAUT32.15)
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
 *
 * Create a new SafeArray.
 *
 * PARAMS
 *  vt        [I] Type to store in the safe array
 *  cDims     [I] Number of array dimensions
 *  rgsabound [I] Bounds of the array dimensions
 *
 * RETURNS
 *  Success: A pointer to a new array object.
 *  Failure: NULL, if any parameter is invalid or memory allocation fails.
 *
 * NOTES
 *  Win32 allows arrays with 0 sized dimensions. This bug is not reproduced
 *  in the Wine implementation.
 *  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 578
    return NULL;

579 580
  return SAFEARRAY_Create(vt, cDims, rgsabound, 0);
}
581

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
/*************************************************************************
 *		SafeArrayCreateEx (OLEAUT32.15)
 *
 * Create a new SafeArray.
 *
 * PARAMS
 *  vt        [I] Type to store in the safe array
 *  cDims     [I] Number of array dimensions
 *  rgsabound [I] Bounds of the array dimensions
 *  pvExtra   [I] Extra data
 *
 * RETURNS
 *  Success: A pointer to a new array object.
 *  Failure: NULL, if any parameter is invalid or memory allocation fails.
 *
 * NOTES
 * See SafeArray.
 */
SAFEARRAY* WINAPI SafeArrayCreateEx(VARTYPE vt, UINT cDims, SAFEARRAYBOUND *rgsabound, LPVOID pvExtra)
{
  ULONG ulSize = 0;
  IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
  SAFEARRAY* psa;
 
  TRACE("(%d->%s,%d,%p,%p)\n", vt, debugstr_vt(vt), cDims, rgsabound, pvExtra);
 
  if (vt == VT_RECORD)
  {
    if  (!iRecInfo)
      return NULL;
    IRecordInfo_GetSize(iRecInfo, &ulSize);
613
  }
614 615 616 617 618 619 620 621 622 623 624 625 626 627
  psa = SAFEARRAY_Create(vt, cDims, rgsabound, ulSize);

  if (pvExtra)
  {
    switch(vt)
    {
      case VT_RECORD:
        SafeArraySetRecordInfo(psa, pvExtra);
        break;
      case VT_UNKNOWN:
      case VT_DISPATCH:
        SafeArraySetIID(psa, pvExtra);
        break;
    }
628
  }
629 630
  return psa;
}
631

632 633 634
/************************************************************************
 *		SafeArrayCreateVector (OLEAUT32.411)
 *
635
 * Create a one dimensional, contiguous SafeArray.
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
 *
 * PARAMS
 *  vt        [I] Type to store in the safe array
 *  lLbound   [I] Lower bound of the array
 *  cElements [I] Number of elements in the array
 *
 * RETURNS
 *  Success: A pointer to a new array object.
 *  Failure: NULL, if any parameter is invalid or memory allocation fails.
 *
 * NOTES
 * See SafeArray.
 */
SAFEARRAY* WINAPI SafeArrayCreateVector(VARTYPE vt, LONG lLbound, ULONG cElements)
{
651
  TRACE("(%d->%s,%d,%d\n", vt, debugstr_vt(vt), lLbound, cElements);
652 653
    
  if (vt == VT_RECORD)
654
    return NULL;
655 656 657 658 659 660 661

  return SAFEARRAY_CreateVector(vt, lLbound, cElements, SAFEARRAY_GetVTSize(vt));
}

/************************************************************************
 *		SafeArrayCreateVectorEx (OLEAUT32.411)
 *
662
 * Create a one dimensional, contiguous SafeArray.
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
 *
 * PARAMS
 *  vt        [I] Type to store in the safe array
 *  lLbound   [I] Lower bound of the array
 *  cElements [I] Number of elements in the array
 *  pvExtra   [I] Extra data
 *
 * RETURNS
 *  Success: A pointer to a new array object.
 *  Failure: NULL, if any parameter is invalid or memory allocation fails.
 *
 * NOTES
 * See SafeArray.
 */
SAFEARRAY* WINAPI SafeArrayCreateVectorEx(VARTYPE vt, LONG lLbound, ULONG cElements, LPVOID pvExtra)
{
  ULONG ulSize;
  IRecordInfo* iRecInfo = (IRecordInfo*)pvExtra;
  SAFEARRAY* psa;

683
 TRACE("(%d->%s,%d,%d,%p\n", vt, debugstr_vt(vt), lLbound, cElements, pvExtra);
684 685 686 687 688 689
 
  if (vt == VT_RECORD)
  {
    if  (!iRecInfo)
      return NULL;
    IRecordInfo_GetSize(iRecInfo, &ulSize);
690
  }
691 692 693 694
  else
    ulSize = SAFEARRAY_GetVTSize(vt);

  psa = SAFEARRAY_CreateVector(vt, lLbound, cElements, ulSize);
695

696 697 698 699 700 701 702 703 704 705 706 707 708 709
  if (pvExtra)
  {
    switch(vt)
    {
      case VT_RECORD:
        SafeArraySetRecordInfo(psa, iRecInfo);
        break;
      case VT_UNKNOWN:
      case VT_DISPATCH:
        SafeArraySetIID(psa, pvExtra);
        break;
    }
  }
  return psa;
710 711 712
}

/*************************************************************************
713
 *		SafeArrayDestroyDescriptor (OLEAUT32.38)
714 715 716 717 718 719 720 721 722 723 724 725
 *
 * Destroy a SafeArray.
 *
 * PARAMS
 *  psa [I] SafeArray to destroy.
 *
 * RETURNS
 *  Success: S_OK. The resources used by the array are freed.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
726
 */
727
HRESULT WINAPI SafeArrayDestroyDescriptor(SAFEARRAY *psa)
728
{
729 730 731 732 733
  TRACE("(%p)\n", psa);
    
  if (psa)
  {
    LPVOID lpv = (char*)psa - SAFEARRAY_HIDDEN_SIZE;
734

735 736
    if (psa->cLocks)
      return DISP_E_ARRAYISLOCKED; /* Can't destroy a locked array */
737

738 739 740 741 742 743
    if (psa->fFeatures & FADF_RECORD)
      SafeArraySetRecordInfo(psa, NULL);

    if (psa->fFeatures & FADF_CREATEVECTOR &&
        !(psa->fFeatures & FADF_DATADELETED))
        SAFEARRAY_DestroyData(psa, 0); /* Data not previously deleted */
744

745 746 747 748 749
    if (!SAFEARRAY_Free(lpv))
      return E_UNEXPECTED;
  }
  return S_OK;
}
750 751

/*************************************************************************
752
 *		SafeArrayLock (OLEAUT32.21)
753
 *
754 755 756 757 758 759 760 761 762 763 764 765 766
 * Increment the lock counter of a SafeArray.
 *
 * PARAMS
 *  psa [O] SafeArray to lock
 *
 * RETURNS
 *  Success: S_OK. The array lock is incremented.
 *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if too many locks
 *           are held on the array at once.
 *
 * NOTES
 *  In Win32 these locks are not thread safe.
 *  See SafeArray.
767
 */
768
HRESULT WINAPI SafeArrayLock(SAFEARRAY *psa)
769
{
770 771 772 773 774
  ULONG ulLocks;

  TRACE("(%p)\n", psa);
    
  if (!psa)
775 776
    return E_INVALIDARG;

Mike McCormack's avatar
Mike McCormack committed
777
  ulLocks = InterlockedIncrement( (LONG*) &psa->cLocks);
778

779 780 781
  if (ulLocks > 0xffff) /* Maximum of 16384 locks at a time */
  {
    WARN("Out of locks!\n");
Mike McCormack's avatar
Mike McCormack committed
782
    InterlockedDecrement( (LONG*) &psa->cLocks);
783 784 785
    return E_UNEXPECTED;
  }
  return S_OK;
786 787 788
}

/*************************************************************************
789
 *		SafeArrayUnlock (OLEAUT32.22)
790 791 792 793 794 795 796 797 798 799 800 801 802
 *
 * Decrement the lock counter of a SafeArray.
 *
 * PARAMS
 *  psa [O] SafeArray to unlock
 *
 * RETURNS
 *  Success: S_OK. The array lock is decremented.
 *  Failure: E_INVALIDARG if psa is NULL, or E_UNEXPECTED if no locks are
 *           held on the array.
 *
 * NOTES
 * See SafeArray.
803
 */
804
HRESULT WINAPI SafeArrayUnlock(SAFEARRAY *psa)
805
{
806 807 808
  TRACE("(%p)\n", psa);
  
  if (!psa)
809 810
    return E_INVALIDARG;

Mike McCormack's avatar
Mike McCormack committed
811
  if ((LONG)InterlockedDecrement( (LONG*) &psa->cLocks) < 0)
812 813
  {
    WARN("Unlocked but no lock held!\n");
Mike McCormack's avatar
Mike McCormack committed
814
    InterlockedIncrement( (LONG*) &psa->cLocks);
815 816 817
    return E_UNEXPECTED;
  }
  return S_OK;
818 819 820
}

/*************************************************************************
821
 *		SafeArrayPutElement (OLEAUT32.26)
822 823 824 825 826 827 828 829 830 831 832 833 834 835
 *
 * Put an item into a SafeArray.
 *
 * PARAMS
 *  psa       [I] SafeArray to insert into
 *  rgIndices [I] Indices to insert at
 *  pvData    [I] Data to insert
 *
 * RETURNS
 *  Success: S_OK. The item is inserted
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * 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 844
  if (!psa || !rgIndices)
    return E_INVALIDARG;
845

846
  hRet = SafeArrayLock(psa);
847

848 849 850
  if (SUCCEEDED(hRet))
  {
    PVOID lpvDest;
851

852
    hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvDest);
853

854 855 856 857 858 859
    if (SUCCEEDED(hRet))
    {
      if (psa->fFeatures & FADF_VARIANT)
      {
        VARIANT* lpVariant = (VARIANT*)pvData;
        VARIANT* lpDest = (VARIANT*)lpvDest;
860

861
        hRet = VariantClear(lpDest);
862
        if (FAILED(hRet)) FIXME("VariantClear failed with 0x%x\n", hRet);
863
        hRet = VariantCopy(lpDest, lpVariant);
864
        if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%x\n", hRet);
865
      }
866 867
      else if (psa->fFeatures & FADF_BSTR)
      {
868
        BSTR  lpBstr = (BSTR)pvData;
869 870 871 872 873
        BSTR* lpDest = (BSTR*)lpvDest;

        if (*lpDest)
         SysFreeString(*lpDest);

874 875 876
        *lpDest = SysAllocStringByteLen((char*)lpBstr, SysStringByteLen(lpBstr));
        if (!*lpDest)
          hRet = E_OUTOFMEMORY;
877 878 879 880 881
      }
      else
      {
        if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
        {
882
          LPUNKNOWN  lpUnknown = (LPUNKNOWN)pvData;
883 884
          LPUNKNOWN *lpDest = (LPUNKNOWN *)lpvDest;

885 886
          if (lpUnknown)
            IUnknown_AddRef(lpUnknown);
887 888
          if (*lpDest)
            IUnknown_Release(*lpDest);
889 890 891 892 893
	  *lpDest = lpUnknown;
        } else {
          /* Copy the data over */
          memcpy(lpvDest, pvData, psa->cbElements);
	}
894
      }
895
    }
896
    SafeArrayUnlock(psa);
897
  }
898
  return hRet;
899 900 901 902
}


/*************************************************************************
903
 *		SafeArrayGetElement (OLEAUT32.25)
904 905 906 907 908 909 910 911 912 913 914 915 916 917
 *
 * Get an item from a SafeArray.
 *
 * PARAMS
 *  psa       [I] SafeArray to get from
 *  rgIndices [I] Indices to get from
 *  pvData    [O] Destination for data
 *
 * RETURNS
 *  Success: S_OK. The item data is returned in pvData.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
918
 */
919
HRESULT WINAPI SafeArrayGetElement(SAFEARRAY *psa, LONG *rgIndices, void *pvData)
920
{
921
  HRESULT hRet;
922

923 924 925
  TRACE("(%p,%p,%p)\n", psa, rgIndices, pvData);
    
  if (!psa || !rgIndices || !pvData)
926
    return E_INVALIDARG;
927

928
  hRet = SafeArrayLock(psa);
929

930 931 932
  if (SUCCEEDED(hRet))
  {
    PVOID lpvSrc;
933

934
    hRet = SafeArrayPtrOfIndex(psa, rgIndices, &lpvSrc);
935

936 937 938 939 940 941
    if (SUCCEEDED(hRet))
    {
      if (psa->fFeatures & FADF_VARIANT)
      {
        VARIANT* lpVariant = (VARIANT*)lpvSrc;
        VARIANT* lpDest = (VARIANT*)pvData;
942

943 944 945
        /* The original content of pvData is ignored. */
        V_VT(lpDest) = VT_EMPTY;
        hRet = VariantCopy(lpDest, lpVariant);
946
	if (FAILED(hRet)) FIXME("VariantCopy failed with 0x%x\n", hRet);
947 948 949 950 951 952 953 954
      }
      else if (psa->fFeatures & FADF_BSTR)
      {
        BSTR* lpBstr = (BSTR*)lpvSrc;
        BSTR* lpDest = (BSTR*)pvData;

        if (*lpBstr)
        {
Marcus Meissner's avatar
Marcus Meissner committed
955
          *lpDest = SysAllocStringByteLen((char*)*lpBstr, SysStringByteLen(*lpBstr));
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
          if (!*lpBstr)
            hRet = E_OUTOFMEMORY;
        }
        else
          *lpDest = NULL;
      }
      else
      {
        if (psa->fFeatures & (FADF_UNKNOWN|FADF_DISPATCH))
        {
          LPUNKNOWN *lpUnknown = (LPUNKNOWN *)lpvSrc;

          if (*lpUnknown)
            IUnknown_AddRef(*lpUnknown);
        }
        /* Copy the data over */
        memcpy(pvData, lpvSrc, psa->cbElements);
973 974
      }
    }
975
    SafeArrayUnlock(psa);
976
  }
977
  return hRet;
978 979 980
}

/*************************************************************************
981
 *		SafeArrayGetUBound (OLEAUT32.19)
982 983 984 985 986 987 988 989 990 991 992 993 994 995
 *
 * Get the upper bound for a given SafeArray dimension
 *
 * PARAMS
 *  psa      [I] Array to get dimension upper bound from
 *  nDim     [I] The dimension number to get the upper bound of
 *  plUbound [O] Destination for the upper bound
 *
 * RETURNS
 *  Success: S_OK. plUbound contains the dimensions upper bound.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
996
 */
997
HRESULT WINAPI SafeArrayGetUBound(SAFEARRAY *psa, UINT nDim, LONG *plUbound)
998
{
999 1000 1001
  TRACE("(%p,%d,%p)\n", psa, nDim, plUbound);
    
  if (!psa || !plUbound)
1002 1003
    return E_INVALIDARG;

1004
  if(!nDim || nDim > psa->cDims)
1005 1006
    return DISP_E_BADINDEX;

1007 1008
  *plUbound = psa->rgsabound[psa->cDims - nDim].lLbound +
              psa->rgsabound[psa->cDims - nDim].cElements - 1;
1009 1010 1011 1012 1013

  return S_OK;
}

/*************************************************************************
1014
 *		SafeArrayGetLBound (OLEAUT32.20)
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
 *
 * Get the lower bound for a given SafeArray dimension
 *
 * PARAMS
 *  psa      [I] Array to get dimension lower bound from
 *  nDim     [I] The dimension number to get the lowe bound of
 *  plLbound [O] Destination for the lower bound
 *
 * RETURNS
 *  Success: S_OK. plUbound contains the dimensions lower bound.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1029
 */
1030
HRESULT WINAPI SafeArrayGetLBound(SAFEARRAY *psa, UINT nDim, LONG *plLbound)
1031
{
1032
  TRACE("(%p,%d,%p)\n", psa, nDim, plLbound);
1033

1034 1035
  if (!psa || !plLbound)
    return E_INVALIDARG;
1036

1037
  if(!nDim || nDim > psa->cDims)
1038
    return DISP_E_BADINDEX;
1039

1040
  *plLbound = psa->rgsabound[psa->cDims - nDim].lLbound;
1041 1042 1043 1044
  return S_OK;
}

/*************************************************************************
1045
 *		SafeArrayGetDim (OLEAUT32.17)
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
 *
 * Get the number of dimensions in a SafeArray.
 *
 * PARAMS
 *  psa [I] Array to get the dimensions of
 *
 * RETURNS
 *  The number of array dimensions in psa, or 0 if psa is NULL.
 *
 * NOTES
 * See SafeArray.
1057
 */
1058
UINT WINAPI SafeArrayGetDim(SAFEARRAY *psa)
1059
{
1060
  TRACE("(%p) returning %d\n", psa, psa ? psa->cDims : 0u);  
1061
  return psa ? psa->cDims : 0;
1062 1063 1064
}

/*************************************************************************
1065
 *		SafeArrayGetElemsize (OLEAUT32.18)
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
 *
 * Get the size of an element in a SafeArray.
 *
 * PARAMS
 *  psa [I] Array to get the element size from
 *
 * RETURNS
 *  The size of a single element in psa, or 0 if psa is NULL.
 *
 * NOTES
 * See SafeArray.
1077
 */
1078
UINT WINAPI SafeArrayGetElemsize(SAFEARRAY *psa)
1079
{
1080
  TRACE("(%p) returning %d\n", psa, psa ? psa->cbElements : 0u);
1081
  return psa ? psa->cbElements : 0;
1082 1083 1084
}

/*************************************************************************
1085
 *		SafeArrayAccessData (OLEAUT32.23)
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
 *
 * Lock a SafeArray and return a pointer to its data.
 *
 * PARAMS
 *  psa     [I] Array to get the data pointer from
 *  ppvData [O] Destination for the arrays data pointer
 *
 * RETURNS
 *  Success: S_OK. ppvData contains the arrays data pointer, and the array
 *           is locked.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1100
 */
1101
HRESULT WINAPI SafeArrayAccessData(SAFEARRAY *psa, void **ppvData)
1102
{
1103
  TRACE("(%p,%p)\n", psa, ppvData);
1104

1105
  if(!psa || !ppvData)
1106 1107
    return E_INVALIDARG;

1108 1109 1110 1111
  if (SUCCEEDED(SafeArrayLock(psa)))
  {
    *ppvData = psa->pvData;
    return S_OK;
1112
  }
1113 1114
  *ppvData = NULL;
  return E_UNEXPECTED;
1115 1116 1117 1118
}


/*************************************************************************
1119
 *		SafeArrayUnaccessData (OLEAUT32.24)
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
 *
 * Unlock a SafeArray after accessing its data.
 *
 * PARAMS
 *  psa     [I] Array to unlock
 *
 * RETURNS
 *  Success: S_OK. The array is unlocked.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1132
 */
1133
HRESULT WINAPI SafeArrayUnaccessData(SAFEARRAY *psa)
1134
{
1135 1136
  TRACE("(%p)\n", psa);
  return SafeArrayUnlock(psa);
1137 1138
}

1139
/************************************************************************
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
 *		SafeArrayPtrOfIndex (OLEAUT32.148)
 *
 * Get the address of an item in a SafeArray.
 *
 * PARAMS
 *  psa       [I] Array to get the items address from
 *  rgIndices [I] Index of the item in the array
 *  ppvData   [O] Destination for item address
 *
 * RETURNS
 *  Success: S_OK. ppvData contains a pointer to the item.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 *  This function does not lock the array.
 *
 * NOTES
 * See SafeArray.
1158
 */
1159
HRESULT WINAPI SafeArrayPtrOfIndex(SAFEARRAY *psa, LONG *rgIndices, void **ppvData)
1160
{
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
  USHORT dim;
  ULONG cell = 0, dimensionSize = 1;
  SAFEARRAYBOUND* psab;
  LONG c1;

  TRACE("(%p,%p,%p)\n", psa, rgIndices, ppvData);
  
  /* The general formula for locating the cell number of an entry in an n
   * dimensional array (where cn = coordinate in dimension dn) is:
   *
   * c1 + c2 * sizeof(d1) + c3 * sizeof(d2) ... + cn * sizeof(c(n-1))
   *
   * We calculate the size of the last dimension at each step through the
   * dimensions to avoid recursing to calculate the last dimensions size.
   */
  if (!psa || !rgIndices || !ppvData)
1177 1178
    return E_INVALIDARG;

1179
  psab = psa->rgsabound + psa->cDims - 1;
1180
  c1 = *rgIndices++;
1181

1182 1183
  if (c1 < psab->lLbound || c1 >= psab->lLbound + (LONG)psab->cElements)
    return DISP_E_BADINDEX; /* Initial index out of bounds */
1184

1185 1186 1187
  for (dim = 1; dim < psa->cDims; dim++)
  {
    dimensionSize *= psab->cElements;
1188

1189
    psab--;
1190

1191 1192 1193 1194
    if (!psab->cElements ||
        *rgIndices < psab->lLbound ||
        *rgIndices >= psab->lLbound + (LONG)psab->cElements)
    return DISP_E_BADINDEX; /* Index out of bounds */
1195

1196 1197
    cell += (*rgIndices - psab->lLbound) * dimensionSize;
    rgIndices++;
1198
  }
1199

1200
  cell += (c1 - psa->rgsabound[psa->cDims - 1].lLbound);
1201

1202 1203 1204
  *ppvData = (char*)psa->pvData + cell * psa->cbElements;
  return S_OK;
}
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
/************************************************************************
 *		SafeArrayDestroyData (OLEAUT32.39)
 *
 * Destroy the data associated with a SafeArray.
 *
 * PARAMS
 *  psa [I] Array to delete the data from
 *
 * RETURNS
 *  Success: S_OK. All items and the item data are freed.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
 */
HRESULT WINAPI SafeArrayDestroyData(SAFEARRAY *psa)
{
  TRACE("(%p)\n", psa);
  
  if (!psa)
    return E_INVALIDARG;
1227

1228
  if (psa->cLocks)
1229
    return DISP_E_ARRAYISLOCKED; /* Can't delete a locked array */
1230

1231 1232 1233
  /* Delete the actual item data */
  if (FAILED(SAFEARRAY_DestroyData(psa, 0)))
    return E_UNEXPECTED;
1234

1235 1236 1237 1238 1239 1240 1241
  if (psa->pvData)
  {
    if (psa->fFeatures & FADF_STATIC)
    {
      ZeroMemory(psa->pvData, SAFEARRAY_GetCellCount(psa) * psa->cbElements);
      return S_OK;
    }
1242 1243 1244 1245 1246 1247 1248 1249 1250
    /* If this is not a vector, free the data memory block */
    if (!(psa->fFeatures & FADF_CREATEVECTOR))
    {
      if (!SAFEARRAY_Free(psa->pvData))
        return E_UNEXPECTED;
      psa->pvData = NULL;
    }
    else
      psa->fFeatures |= FADF_DATADELETED; /* Mark the data deleted */
1251 1252 1253 1254 1255

  }
  return S_OK;
}

1256
/************************************************************************
1257
 *		SafeArrayCopyData (OLEAUT32.412)
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
 *
 * Copy all data from one SafeArray to another.
 *
 * PARAMS
 *  psaSource [I] Source for copy
 *  psaTarget [O] Destination for copy
 *
 * RETURNS
 *  Success: S_OK. psaTarget contains a copy of psaSource.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 *  The two arrays must have the same number of dimensions and elements.
 *
 * NOTES
 * See SafeArray.
1274
 */
1275
HRESULT WINAPI SafeArrayCopyData(SAFEARRAY *psaSource, SAFEARRAY *psaTarget)
1276
{
1277
  int dim;
1278

1279 1280 1281 1282 1283
  TRACE("(%p,%p)\n", psaSource, psaTarget);
  
  if (!psaSource || !psaTarget ||
      psaSource->cDims != psaTarget->cDims ||
      psaSource->cbElements != psaTarget->cbElements)
1284 1285
    return E_INVALIDARG;

1286 1287 1288 1289
  /* Each dimension must be the same size */
  for (dim = psaSource->cDims - 1; dim >= 0 ; dim--)
    if (psaSource->rgsabound[dim].cElements !=
       psaTarget->rgsabound[dim].cElements)
1290 1291
      return E_INVALIDARG;

1292 1293 1294 1295
  if (SUCCEEDED(SAFEARRAY_DestroyData(psaTarget, 0)) &&
      SUCCEEDED(SAFEARRAY_CopyData(psaSource, psaTarget)))
    return S_OK;
  return E_UNEXPECTED;
1296 1297
}

1298
/************************************************************************
1299
 *		SafeArrayDestroy (OLEAUT32.16)
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
 *
 * Destroy a SafeArray.
 *
 * PARAMS
 *  psa [I] Array to destroy
 *
 * RETURNS
 *  Success: S_OK. All resources used by the array are freed.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1312
 */
1313
HRESULT WINAPI SafeArrayDestroy(SAFEARRAY *psa)
1314
{
1315
  TRACE("(%p)\n", psa);
1316

1317
  if(!psa)
1318
    return S_OK;
1319

1320
  if(psa->cLocks > 0)
1321 1322
    return DISP_E_ARRAYISLOCKED;

1323 1324 1325 1326
  /* Native doesn't check to see if the free succeeds */
  SafeArrayDestroyData(psa);
  SafeArrayDestroyDescriptor(psa);
  return S_OK;
1327 1328
}

1329
/************************************************************************
1330
 *		SafeArrayCopy (OLEAUT32.27)
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
 *
 * Make a duplicate of a SafeArray.
 *
 * PARAMS
 *  psa     [I] Source for copy
 *  ppsaOut [O] Destination for new copy
 *
 * RETURNS
 *  Success: S_OK. ppsaOut contains a copy of the array.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1344
 */
1345
HRESULT WINAPI SafeArrayCopy(SAFEARRAY *psa, SAFEARRAY **ppsaOut)
1346
{
1347
  HRESULT hRet;
1348

1349
  TRACE("(%p,%p)\n", psa, ppsaOut);
1350

1351 1352
  if (!ppsaOut)
    return E_INVALIDARG;
1353

1354
  *ppsaOut = NULL;
1355

1356 1357
  if (!psa)
    return S_OK; /* Handles copying of NULL arrays */
1358

1359 1360 1361 1362 1363 1364
  if (!psa->cbElements)
  {
    ERR("not copying an array of 0 elements\n");
    return E_INVALIDARG;
  }

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  if (psa->fFeatures & (FADF_RECORD|FADF_HAVEIID|FADF_HAVEVARTYPE))
  {
    VARTYPE vt;
    if (FAILED(SafeArrayGetVartype(psa, &vt)))
      hRet = E_UNEXPECTED;
    else
      hRet = SafeArrayAllocDescriptorEx(vt, psa->cDims, ppsaOut);
  }
  else
  {
    hRet = SafeArrayAllocDescriptor(psa->cDims, ppsaOut);
    if (SUCCEEDED(hRet))
    {
      (*ppsaOut)->fFeatures = psa->fFeatures & ~FADF_CREATEVECTOR;
      (*ppsaOut)->cbElements = psa->cbElements;
1380
    }
1381
  }
1382

1383 1384 1385 1386
  if (SUCCEEDED(hRet))
  {
    /* Copy dimension bounds */
    memcpy((*ppsaOut)->rgsabound, psa->rgsabound, psa->cDims * sizeof(SAFEARRAYBOUND));
1387

1388
    (*ppsaOut)->pvData = SAFEARRAY_Malloc(SAFEARRAY_GetCellCount(psa) * psa->cbElements);
1389

1390 1391 1392 1393 1394 1395
    if ((*ppsaOut)->pvData)
    {
      hRet = SAFEARRAY_CopyData(psa, *ppsaOut);
 
      if (SUCCEEDED(hRet))
        return hRet;
1396

1397
      SAFEARRAY_Free((*ppsaOut)->pvData);
1398
    }
1399
    SafeArrayDestroyDescriptor(*ppsaOut);
1400
  }
1401 1402
  *ppsaOut = NULL;
  return hRet;
1403
}
1404

1405
/************************************************************************
1406
 *		SafeArrayRedim (OLEAUT32.40)
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
 *
 * Changes the characteristics of the last dimension of a SafeArray
 *
 * PARAMS
 *  psa      [I] Array to change
 *  psabound [I] New bound details for the last dimension
 *
 * RETURNS
 *  Success: S_OK. psa is updated to reflect the new bounds.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1420
 */
1421
HRESULT WINAPI SafeArrayRedim(SAFEARRAY *psa, SAFEARRAYBOUND *psabound)
1422
{
1423
  SAFEARRAYBOUND *oldBounds;
1424

1425 1426
  TRACE("(%p,%p)\n", psa, psabound);
  
1427
  if (!psa || psa->fFeatures & FADF_FIXEDSIZE || !psabound)
1428 1429
    return E_INVALIDARG;

1430
  if (psa->cLocks > 0)
1431 1432
    return DISP_E_ARRAYISLOCKED;

1433 1434
  if (FAILED(SafeArrayLock(psa)))
    return E_UNEXPECTED;
1435

1436
  oldBounds = psa->rgsabound;
1437
  oldBounds->lLbound = psabound->lLbound;
Ove Kaaven's avatar
Ove Kaaven committed
1438

1439 1440 1441 1442 1443
  if (psabound->cElements != oldBounds->cElements)
  {
    if (psabound->cElements < oldBounds->cElements)
    {
      /* Shorten the final dimension. */
1444 1445
      ULONG ulStartCell = psabound->cElements *
                          (SAFEARRAY_GetCellCount(psa) / oldBounds->cElements);
1446 1447 1448 1449 1450 1451 1452 1453
      SAFEARRAY_DestroyData(psa, ulStartCell);
    }
    else
    {
      /* Lengthen the final dimension */
      ULONG ulOldSize, ulNewSize;
      PVOID pvNewData;

1454
      ulOldSize = SAFEARRAY_GetCellCount(psa) * psa->cbElements;
1455 1456 1457 1458 1459
      if (ulOldSize)
        ulNewSize = (ulOldSize / oldBounds->cElements) * psabound->cElements;
      else {
	int oldelems = oldBounds->cElements;
	oldBounds->cElements = psabound->cElements;
1460
        ulNewSize = SAFEARRAY_GetCellCount(psa) * psa->cbElements;
1461 1462
	oldBounds->cElements = oldelems;
      }
1463

1464
      if (!(pvNewData = SAFEARRAY_Malloc(ulNewSize)))
1465 1466 1467 1468
      {
        SafeArrayUnlock(psa);
        return E_UNEXPECTED;
      }
1469

1470 1471 1472 1473 1474 1475
      memcpy(pvNewData, psa->pvData, ulOldSize);
      SAFEARRAY_Free(psa->pvData);
      psa->pvData = pvNewData;
    }
    oldBounds->cElements = psabound->cElements;
  }
1476

1477 1478
  SafeArrayUnlock(psa);
  return S_OK;
1479 1480 1481
}

/************************************************************************
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
 *		SafeArrayGetVartype (OLEAUT32.77)
 *
 * Get the type of the items in a SafeArray.
 *
 * PARAMS
 *  psa [I] Array to get the type from
 *  pvt [O] Destination for the type
 *
 * RETURNS
 *  Success: S_OK. pvt contains the type of the items.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1496
 */
1497
HRESULT WINAPI SafeArrayGetVartype(SAFEARRAY* psa, VARTYPE* pvt)
1498
{
1499
  TRACE("(%p,%p)\n", psa, pvt);
1500

1501 1502
  if (!psa || !pvt)
    return E_INVALIDARG;
1503

1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
  if (psa->fFeatures & FADF_RECORD)
    *pvt = VT_RECORD;
  else if (psa->fFeatures & FADF_HAVEIID)
    *pvt = VT_UNKNOWN;
  else if (psa->fFeatures & FADF_HAVEVARTYPE)
  {
    VARTYPE vt = SAFEARRAY_GetHiddenDWORD(psa);
    *pvt = vt;
  }
  else
    return E_INVALIDARG;
1515

1516
  return S_OK;
1517 1518
}

1519
/************************************************************************
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
 *		SafeArraySetRecordInfo (OLEAUT32.@)
 *
 * Set the record info for a SafeArray.
 *
 * PARAMS
 *  psa    [I] Array to set the record info for
 *  pRinfo [I] Record info
 *
 * RETURNS
 *  Success: S_OK. The record info is stored with the array.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1534
 */
1535
HRESULT WINAPI SafeArraySetRecordInfo(SAFEARRAY *psa, IRecordInfo *pRinfo)
1536
{
1537
  IRecordInfo** dest = (IRecordInfo**)psa;
1538

1539 1540 1541 1542
  TRACE("(%p,%p)\n", psa, pRinfo);
  
  if (!psa || !(psa->fFeatures & FADF_RECORD))
    return E_INVALIDARG;
1543

1544 1545
  if (pRinfo)
    IRecordInfo_AddRef(pRinfo);
1546

1547 1548
  if (dest[-1])
    IRecordInfo_Release(dest[-1]);
1549

1550 1551
  dest[-1] = pRinfo;
  return S_OK;
1552 1553
}

1554
/************************************************************************
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
 *		SafeArrayGetRecordInfo (OLEAUT32.@)
 *
 * Get the record info from a SafeArray.
 *
 * PARAMS
 *  psa    [I] Array to get the record info from
 *  pRinfo [O] Destination for the record info
 *
 * RETURNS
 *  Success: S_OK. pRinfo contains the record info, or NULL if there was none.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1569
 */
1570
HRESULT WINAPI SafeArrayGetRecordInfo(SAFEARRAY *psa, IRecordInfo **pRinfo)
1571
{
1572
  IRecordInfo** src = (IRecordInfo**)psa;
1573

1574
  TRACE("(%p,%p)\n", psa, pRinfo);
1575

1576 1577
  if (!psa || !pRinfo || !(psa->fFeatures & FADF_RECORD))
    return E_INVALIDARG;
1578

1579
  *pRinfo = src[-1];
1580

1581 1582 1583
  if (*pRinfo)
    IRecordInfo_AddRef(*pRinfo);
  return S_OK;
1584 1585
}

1586
/************************************************************************
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
 *		SafeArraySetIID (OLEAUT32.@)
 *
 * Set the IID for a SafeArray.
 *
 * PARAMS
 *  psa  [I] Array to set the IID from
 *  guid [I] IID
 *
 * RETURNS
 *  Success: S_OK. The IID is stored with the array
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1601
 */
1602
HRESULT WINAPI SafeArraySetIID(SAFEARRAY *psa, REFGUID guid)
1603
{
1604
  GUID* dest = (GUID*)psa;
1605

1606
  TRACE("(%p,%s)\n", psa, debugstr_guid(guid));
1607

1608 1609
  if (!psa || !guid || !(psa->fFeatures & FADF_HAVEIID))
    return E_INVALIDARG;
1610

1611 1612
  dest[-1] = *guid;
  return S_OK;
1613 1614
}

1615
/************************************************************************
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
 *		SafeArrayGetIID (OLEAUT32.@)
 *
 * Get the IID from a SafeArray.
 *
 * PARAMS
 *  psa   [I] Array to get the ID from
 *  pGuid [O] Destination for the IID
 *
 * RETURNS
 *  Success: S_OK. pRinfo contains the IID, or NULL if there was none.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1630
 */
1631
HRESULT WINAPI SafeArrayGetIID(SAFEARRAY *psa, GUID *pGuid)
1632
{
1633
  GUID* src = (GUID*)psa;
1634

1635
  TRACE("(%p,%p)\n", psa, pGuid);
1636

1637 1638
  if (!psa || !pGuid || !(psa->fFeatures & FADF_HAVEIID))
    return E_INVALIDARG;
1639

1640
  *pGuid = src[-1];
1641 1642 1643
  return S_OK;
}

1644
/************************************************************************
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
 *		VectorFromBstr (OLEAUT32.@)
 *
 * Create a SafeArray Vector from the bytes of a BSTR.
 *
 * PARAMS
 *  bstr [I] String to get bytes from
 *  ppsa [O] Destination for the array
 *
 * RETURNS
 *  Success: S_OK. ppsa contains the strings bytes as a VT_UI1 array.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 * See SafeArray.
1659
 */
1660
HRESULT WINAPI VectorFromBstr(BSTR bstr, SAFEARRAY **ppsa)
1661
{
1662
  SAFEARRAYBOUND sab;
1663

1664 1665 1666 1667
  TRACE("(%p,%p)\n", bstr, ppsa);
  
  if (!ppsa)
    return E_INVALIDARG;
1668

1669 1670
  sab.lLbound = 0;
  sab.cElements = SysStringByteLen(bstr);
1671

1672
  *ppsa = SAFEARRAY_Create(VT_UI1, 1, &sab, 0);
1673

1674
  if (*ppsa)
1675
  {
1676
    memcpy((*ppsa)->pvData, bstr, sab.cElements);
1677
    return S_OK;
1678
  }
1679
  return E_OUTOFMEMORY;
1680 1681 1682
}

/************************************************************************
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
 *		BstrFromVector (OLEAUT32.@)
 *
 * Create a BSTR from a SafeArray.
 *
 * PARAMS
 *  psa   [I] Source array
 *  pbstr [O] Destination for output BSTR
 *
 * RETURNS
 *  Success: S_OK. pbstr contains the arrays data.
 *  Failure: An HRESULT error code indicating the error.
 *
 * NOTES
 *  psa must be a 1 dimensional array of a 1 byte type.
 *
 * NOTES
 * See SafeArray.
1700
 */
1701 1702 1703
HRESULT WINAPI BstrFromVector(SAFEARRAY *psa, BSTR *pbstr)
{
  TRACE("(%p,%p)\n", psa, pbstr);
1704

1705
  if (!pbstr)
1706 1707
    return E_INVALIDARG;

1708
  *pbstr = NULL;
1709

1710
  if (!psa || psa->cbElements != 1 || psa->cDims != 1)
1711 1712
    return E_INVALIDARG;

1713 1714 1715
  *pbstr = SysAllocStringByteLen(psa->pvData, psa->rgsabound[0].cElements);
  if (!*pbstr)
    return E_OUTOFMEMORY;
1716
  return S_OK;
1717
}