ole32: Fix a memory leak.
[wine] / dlls / ole32 / stg_stream.c
1 /*
2  * Compound Storage (32 bit version)
3  * Stream implementation
4  *
5  * This file contains the implementation of the stream interface
6  * for streams contained in a compound storage.
7  *
8  * Copyright 1999 Francis Beaudet
9  * Copyright 1999 Thuy Nguyen
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include <assert.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31
32 #define COBJMACROS
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winerror.h"
39 #include "winternl.h"
40 #include "wine/debug.h"
41
42 #include "storage32.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(storage);
45
46
47 /***
48  * This is the destructor of the StgStreamImpl class.
49  *
50  * This method will clean-up all the resources used-up by the given StgStreamImpl
51  * class. The pointer passed-in to this function will be freed and will not
52  * be valid anymore.
53  */
54 static void StgStreamImpl_Destroy(StgStreamImpl* This)
55 {
56   TRACE("(%p)\n", This);
57
58   /*
59    * Release the reference we are holding on the parent storage.
60    * IStorage_Release((IStorage*)This->parentStorage);
61    *
62    * No, don't do this. Some apps call IStorage_Release without
63    * calling IStream_Release first. If we grab a reference the
64    * file is not closed, and the app fails when it tries to
65    * reopen the file (Easy-PC, for example). Just inform the
66    * storage that we have closed the stream
67    */
68
69   if(This->parentStorage) {
70
71     StorageBaseImpl_RemoveStream(This->parentStorage, This);
72
73   }
74
75   This->parentStorage = 0;
76
77   /*
78    * Finally, free the memory used-up by the class.
79    */
80   HeapFree(GetProcessHeap(), 0, This);
81 }
82
83 /***
84  * This implements the IUnknown method QueryInterface for this
85  * class
86  */
87 static HRESULT WINAPI StgStreamImpl_QueryInterface(
88                   IStream*     iface,
89                   REFIID         riid,        /* [in] */
90                   void**         ppvObject)   /* [iid_is][out] */
91 {
92   StgStreamImpl* const This=(StgStreamImpl*)iface;
93
94   /*
95    * Perform a sanity check on the parameters.
96    */
97   if (ppvObject==0)
98     return E_INVALIDARG;
99
100   /*
101    * Initialize the return parameter.
102    */
103   *ppvObject = 0;
104
105   /*
106    * Compare the riid with the interface IDs implemented by this object.
107    */
108   if (IsEqualIID(&IID_IUnknown, riid) ||
109       IsEqualIID(&IID_IPersist, riid) ||
110       IsEqualIID(&IID_IPersistStream, riid) ||
111       IsEqualIID(&IID_ISequentialStream, riid) ||
112       IsEqualIID(&IID_IStream, riid))
113   {
114     *ppvObject = This;
115   }
116
117   /*
118    * Check that we obtained an interface.
119    */
120   if ((*ppvObject)==0)
121     return E_NOINTERFACE;
122
123   /*
124    * Query Interface always increases the reference count by one when it is
125    * successful
126    */
127   IStream_AddRef(iface);
128
129   return S_OK;
130 }
131
132 /***
133  * This implements the IUnknown method AddRef for this
134  * class
135  */
136 static ULONG WINAPI StgStreamImpl_AddRef(
137                 IStream* iface)
138 {
139   StgStreamImpl* const This=(StgStreamImpl*)iface;
140   return InterlockedIncrement(&This->ref);
141 }
142
143 /***
144  * This implements the IUnknown method Release for this
145  * class
146  */
147 static ULONG WINAPI StgStreamImpl_Release(
148                 IStream* iface)
149 {
150   StgStreamImpl* const This=(StgStreamImpl*)iface;
151
152   ULONG ref;
153
154   ref = InterlockedDecrement(&This->ref);
155
156   /*
157    * If the reference count goes down to 0, perform suicide.
158    */
159   if (ref==0)
160   {
161     StgStreamImpl_Destroy(This);
162   }
163
164   return ref;
165 }
166
167 /***
168  * This method is part of the ISequentialStream interface.
169  *
170  * It reads a block of information from the stream at the current
171  * position. It then moves the current position at the end of the
172  * read block
173  *
174  * See the documentation of ISequentialStream for more info.
175  */
176 static HRESULT WINAPI StgStreamImpl_Read(
177                   IStream*     iface,
178                   void*          pv,        /* [length_is][size_is][out] */
179                   ULONG          cb,        /* [in] */
180                   ULONG*         pcbRead)   /* [out] */
181 {
182   StgStreamImpl* const This=(StgStreamImpl*)iface;
183
184   ULONG bytesReadBuffer;
185   HRESULT res;
186
187   TRACE("(%p, %p, %d, %p)\n",
188         iface, pv, cb, pcbRead);
189
190   if (!This->parentStorage)
191   {
192     WARN("storage reverted\n");
193     return STG_E_REVERTED;
194   }
195
196   /*
197    * If the caller is not interested in the number of bytes read,
198    * we use another buffer to avoid "if" statements in the code.
199    */
200   if (pcbRead==0)
201     pcbRead = &bytesReadBuffer;
202
203   res = StorageBaseImpl_StreamReadAt(This->parentStorage,
204                                      This->dirEntry,
205                                      This->currentPosition,
206                                      cb,
207                                      pv,
208                                      pcbRead);
209
210   if (SUCCEEDED(res))
211   {
212     /*
213      * Advance the pointer for the number of positions read.
214      */
215     This->currentPosition.u.LowPart += *pcbRead;
216   }
217
218   TRACE("<-- %08x\n", res);
219   return res;
220 }
221
222 /***
223  * This method is part of the ISequentialStream interface.
224  *
225  * It writes a block of information to the stream at the current
226  * position. It then moves the current position at the end of the
227  * written block. If the stream is too small to fit the block,
228  * the stream is grown to fit.
229  *
230  * See the documentation of ISequentialStream for more info.
231  */
232 static HRESULT WINAPI StgStreamImpl_Write(
233                   IStream*     iface,
234                   const void*    pv,          /* [size_is][in] */
235                   ULONG          cb,          /* [in] */
236                   ULONG*         pcbWritten)  /* [out] */
237 {
238   StgStreamImpl* const This=(StgStreamImpl*)iface;
239
240   ULONG bytesWritten = 0;
241   HRESULT res;
242
243   TRACE("(%p, %p, %d, %p)\n",
244         iface, pv, cb, pcbWritten);
245
246   /*
247    * Do we have permission to write to this stream?
248    */
249   switch(STGM_ACCESS_MODE(This->grfMode))
250   {
251   case STGM_WRITE:
252   case STGM_READWRITE:
253       break;
254   default:
255       WARN("access denied by flags: 0x%x\n", STGM_ACCESS_MODE(This->grfMode));
256       return STG_E_ACCESSDENIED;
257   }
258
259   if (!pv)
260     return STG_E_INVALIDPOINTER;
261
262   if (!This->parentStorage)
263   {
264     WARN("storage reverted\n");
265     return STG_E_REVERTED;
266   }
267  
268   /*
269    * If the caller is not interested in the number of bytes written,
270    * we use another buffer to avoid "if" statements in the code.
271    */
272   if (pcbWritten == 0)
273     pcbWritten = &bytesWritten;
274
275   /*
276    * Initialize the out parameter
277    */
278   *pcbWritten = 0;
279
280   if (cb == 0)
281   {
282     TRACE("<-- S_OK, written 0\n");
283     return S_OK;
284   }
285
286   res = StorageBaseImpl_StreamWriteAt(This->parentStorage,
287                                       This->dirEntry,
288                                       This->currentPosition,
289                                       cb,
290                                       pv,
291                                       pcbWritten);
292
293   /*
294    * Advance the position pointer for the number of positions written.
295    */
296   This->currentPosition.u.LowPart += *pcbWritten;
297
298   TRACE("<-- S_OK, written %u\n", *pcbWritten);
299   return res;
300 }
301
302 /***
303  * This method is part of the IStream interface.
304  *
305  * It will move the current stream pointer according to the parameters
306  * given.
307  *
308  * See the documentation of IStream for more info.
309  */
310 static HRESULT WINAPI StgStreamImpl_Seek(
311                   IStream*      iface,
312                   LARGE_INTEGER   dlibMove,         /* [in] */
313                   DWORD           dwOrigin,         /* [in] */
314                   ULARGE_INTEGER* plibNewPosition) /* [out] */
315 {
316   StgStreamImpl* const This=(StgStreamImpl*)iface;
317
318   ULARGE_INTEGER newPosition;
319   DirEntry currentEntry;
320   HRESULT hr;
321
322   TRACE("(%p, %d, %d, %p)\n",
323         iface, dlibMove.u.LowPart, dwOrigin, plibNewPosition);
324
325   /*
326    * fail if the stream has no parent (as does windows)
327    */
328
329   if (!This->parentStorage)
330   {
331     WARN("storage reverted\n");
332     return STG_E_REVERTED;
333   }
334
335   /*
336    * The caller is allowed to pass in NULL as the new position return value.
337    * If it happens, we assign it to a dynamic variable to avoid special cases
338    * in the code below.
339    */
340   if (plibNewPosition == 0)
341   {
342     plibNewPosition = &newPosition;
343   }
344
345   /*
346    * The file pointer is moved depending on the given "function"
347    * parameter.
348    */
349   switch (dwOrigin)
350   {
351     case STREAM_SEEK_SET:
352       plibNewPosition->u.HighPart = 0;
353       plibNewPosition->u.LowPart  = 0;
354       break;
355     case STREAM_SEEK_CUR:
356       *plibNewPosition = This->currentPosition;
357       break;
358     case STREAM_SEEK_END:
359       hr = StorageBaseImpl_ReadDirEntry(This->parentStorage, This->dirEntry, &currentEntry);
360       if (FAILED(hr)) return hr;
361       *plibNewPosition = currentEntry.size;
362       break;
363     default:
364       WARN("invalid dwOrigin %d\n", dwOrigin);
365       return STG_E_INVALIDFUNCTION;
366   }
367
368   plibNewPosition->QuadPart += dlibMove.QuadPart;
369
370   /*
371    * tell the caller what we calculated
372    */
373   This->currentPosition = *plibNewPosition;
374
375   return S_OK;
376 }
377
378 /***
379  * This method is part of the IStream interface.
380  *
381  * It will change the size of a stream.
382  *
383  * See the documentation of IStream for more info.
384  */
385 static HRESULT WINAPI StgStreamImpl_SetSize(
386                                      IStream*      iface,
387                                      ULARGE_INTEGER  libNewSize)   /* [in] */
388 {
389   StgStreamImpl* const This=(StgStreamImpl*)iface;
390
391   HRESULT      hr;
392
393   TRACE("(%p, %d)\n", iface, libNewSize.u.LowPart);
394
395   if(!This->parentStorage)
396   {
397     WARN("storage reverted\n");
398     return STG_E_REVERTED;
399   }
400
401   /*
402    * As documented.
403    */
404   if (libNewSize.u.HighPart != 0)
405   {
406     WARN("invalid value for libNewSize.u.HighPart %d\n", libNewSize.u.HighPart);
407     return STG_E_INVALIDFUNCTION;
408   }
409
410   /*
411    * Do we have permission?
412    */
413   if (!(This->grfMode & (STGM_WRITE | STGM_READWRITE)))
414   {
415     WARN("access denied\n");
416     return STG_E_ACCESSDENIED;
417   }
418
419   hr = StorageBaseImpl_StreamSetSize(This->parentStorage, This->dirEntry, libNewSize);
420   return hr;
421 }
422
423 /***
424  * This method is part of the IStream interface.
425  *
426  * It will copy the 'cb' Bytes to 'pstm' IStream.
427  *
428  * See the documentation of IStream for more info.
429  */
430 static HRESULT WINAPI StgStreamImpl_CopyTo(
431                                     IStream*      iface,
432                                     IStream*      pstm,         /* [unique][in] */
433                                     ULARGE_INTEGER  cb,           /* [in] */
434                                     ULARGE_INTEGER* pcbRead,      /* [out] */
435                                     ULARGE_INTEGER* pcbWritten)   /* [out] */
436 {
437   StgStreamImpl* const This=(StgStreamImpl*)iface;
438   HRESULT        hr = S_OK;
439   BYTE           tmpBuffer[128];
440   ULONG          bytesRead, bytesWritten, copySize;
441   ULARGE_INTEGER totalBytesRead;
442   ULARGE_INTEGER totalBytesWritten;
443
444   TRACE("(%p, %p, %d, %p, %p)\n",
445         iface, pstm, cb.u.LowPart, pcbRead, pcbWritten);
446
447   /*
448    * Sanity check
449    */
450
451   if (!This->parentStorage)
452   {
453     WARN("storage reverted\n");
454     return STG_E_REVERTED;
455   }
456
457   if ( pstm == 0 )
458     return STG_E_INVALIDPOINTER;
459
460   totalBytesRead.QuadPart = 0;
461   totalBytesWritten.QuadPart = 0;
462
463   while ( cb.QuadPart > 0 )
464   {
465     if ( cb.QuadPart >= sizeof(tmpBuffer) )
466       copySize = sizeof(tmpBuffer);
467     else
468       copySize = cb.u.LowPart;
469
470     IStream_Read(iface, tmpBuffer, copySize, &bytesRead);
471
472     totalBytesRead.QuadPart += bytesRead;
473
474     IStream_Write(pstm, tmpBuffer, bytesRead, &bytesWritten);
475
476     totalBytesWritten.QuadPart += bytesWritten;
477
478     /*
479      * Check that read & write operations were successful
480      */
481     if (bytesRead != bytesWritten)
482     {
483       hr = STG_E_MEDIUMFULL;
484       WARN("medium full\n");
485       break;
486     }
487
488     if (bytesRead!=copySize)
489       cb.QuadPart = 0;
490     else
491       cb.QuadPart -= bytesRead;
492   }
493
494   if (pcbRead) pcbRead->QuadPart = totalBytesRead.QuadPart;
495   if (pcbWritten) pcbWritten->QuadPart = totalBytesWritten.QuadPart;
496
497   return hr;
498 }
499
500 /***
501  * This method is part of the IStream interface.
502  *
503  * For streams contained in structured storages, this method
504  * does nothing. This is what the documentation tells us.
505  *
506  * See the documentation of IStream for more info.
507  */
508 static HRESULT WINAPI StgStreamImpl_Commit(
509                   IStream*      iface,
510                   DWORD           grfCommitFlags)  /* [in] */
511 {
512   StgStreamImpl* const This=(StgStreamImpl*)iface;
513
514   if (!This->parentStorage)
515   {
516     WARN("storage reverted\n");
517     return STG_E_REVERTED;
518   }
519
520   return S_OK;
521 }
522
523 /***
524  * This method is part of the IStream interface.
525  *
526  * For streams contained in structured storages, this method
527  * does nothing. This is what the documentation tells us.
528  *
529  * See the documentation of IStream for more info.
530  */
531 static HRESULT WINAPI StgStreamImpl_Revert(
532                   IStream* iface)
533 {
534   return S_OK;
535 }
536
537 static HRESULT WINAPI StgStreamImpl_LockRegion(
538                                         IStream*     iface,
539                                         ULARGE_INTEGER libOffset,   /* [in] */
540                                         ULARGE_INTEGER cb,          /* [in] */
541                                         DWORD          dwLockType)  /* [in] */
542 {
543   StgStreamImpl* const This=(StgStreamImpl*)iface;
544
545   if (!This->parentStorage)
546   {
547     WARN("storage reverted\n");
548     return STG_E_REVERTED;
549   }
550
551   FIXME("not implemented!\n");
552   return E_NOTIMPL;
553 }
554
555 static HRESULT WINAPI StgStreamImpl_UnlockRegion(
556                                           IStream*     iface,
557                                           ULARGE_INTEGER libOffset,   /* [in] */
558                                           ULARGE_INTEGER cb,          /* [in] */
559                                           DWORD          dwLockType)  /* [in] */
560 {
561   StgStreamImpl* const This=(StgStreamImpl*)iface;
562
563   if (!This->parentStorage)
564   {
565     WARN("storage reverted\n");
566     return STG_E_REVERTED;
567   }
568
569   FIXME("not implemented!\n");
570   return E_NOTIMPL;
571 }
572
573 /***
574  * This method is part of the IStream interface.
575  *
576  * This method returns information about the current
577  * stream.
578  *
579  * See the documentation of IStream for more info.
580  */
581 static HRESULT WINAPI StgStreamImpl_Stat(
582                   IStream*     iface,
583                   STATSTG*       pstatstg,     /* [out] */
584                   DWORD          grfStatFlag)  /* [in] */
585 {
586   StgStreamImpl* const This=(StgStreamImpl*)iface;
587
588   DirEntry     currentEntry;
589   HRESULT      hr;
590
591   TRACE("%p %p %d\n", This, pstatstg, grfStatFlag);
592
593   /*
594    * if stream has no parent, return STG_E_REVERTED
595    */
596
597   if (!This->parentStorage)
598   {
599     WARN("storage reverted\n");
600     return STG_E_REVERTED;
601   }
602
603   /*
604    * Read the information from the directory entry.
605    */
606   hr = StorageBaseImpl_ReadDirEntry(This->parentStorage,
607                                              This->dirEntry,
608                                              &currentEntry);
609
610   if (SUCCEEDED(hr))
611   {
612     StorageUtl_CopyDirEntryToSTATSTG(This->parentStorage,
613                      pstatstg,
614                                      &currentEntry,
615                                      grfStatFlag);
616
617     pstatstg->grfMode = This->grfMode;
618
619     /* In simple create mode cbSize is the current pos */
620     if((This->parentStorage->openFlags & STGM_SIMPLE) && This->parentStorage->create)
621       pstatstg->cbSize = This->currentPosition;
622
623     return S_OK;
624   }
625
626   WARN("failed to read entry\n");
627   return hr;
628 }
629
630 /***
631  * This method is part of the IStream interface.
632  *
633  * This method returns a clone of the interface that allows for
634  * another seek pointer
635  *
636  * See the documentation of IStream for more info.
637  *
638  * I am not totally sure what I am doing here but I presume that this
639  * should be basically as simple as creating a new stream with the same
640  * parent etc and positioning its seek cursor.
641  */
642 static HRESULT WINAPI StgStreamImpl_Clone(
643                                    IStream*     iface,
644                                    IStream**    ppstm) /* [out] */
645 {
646   StgStreamImpl* const This=(StgStreamImpl*)iface;
647   HRESULT hres;
648   StgStreamImpl* new_stream;
649   LARGE_INTEGER seek_pos;
650
651   TRACE("%p %p\n", This, ppstm);
652
653   /*
654    * Sanity check
655    */
656
657   if (!This->parentStorage)
658     return STG_E_REVERTED;
659
660   if ( ppstm == 0 )
661     return STG_E_INVALIDPOINTER;
662
663   new_stream = StgStreamImpl_Construct (This->parentStorage, This->grfMode, This->dirEntry);
664
665   if (!new_stream)
666     return STG_E_INSUFFICIENTMEMORY; /* Currently the only reason for new_stream=0 */
667
668   *ppstm = (IStream*) new_stream;
669   IStream_AddRef(*ppstm);
670
671   seek_pos.QuadPart = This->currentPosition.QuadPart;
672
673   hres=StgStreamImpl_Seek (*ppstm, seek_pos, STREAM_SEEK_SET, NULL);
674
675   assert (SUCCEEDED(hres));
676
677   return S_OK;
678 }
679
680 /*
681  * Virtual function table for the StgStreamImpl class.
682  */
683 static const IStreamVtbl StgStreamImpl_Vtbl =
684 {
685     StgStreamImpl_QueryInterface,
686     StgStreamImpl_AddRef,
687     StgStreamImpl_Release,
688     StgStreamImpl_Read,
689     StgStreamImpl_Write,
690     StgStreamImpl_Seek,
691     StgStreamImpl_SetSize,
692     StgStreamImpl_CopyTo,
693     StgStreamImpl_Commit,
694     StgStreamImpl_Revert,
695     StgStreamImpl_LockRegion,
696     StgStreamImpl_UnlockRegion,
697     StgStreamImpl_Stat,
698     StgStreamImpl_Clone
699 };
700
701 /******************************************************************************
702 ** StgStreamImpl implementation
703 */
704
705 /***
706  * This is the constructor for the StgStreamImpl class.
707  *
708  * Params:
709  *    parentStorage - Pointer to the storage that contains the stream to open
710  *    dirEntry      - Index of the directory entry that points to this stream.
711  */
712 StgStreamImpl* StgStreamImpl_Construct(
713                 StorageBaseImpl* parentStorage,
714     DWORD            grfMode,
715     DirRef           dirEntry)
716 {
717   StgStreamImpl* newStream;
718
719   newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(StgStreamImpl));
720
721   if (newStream!=0)
722   {
723     /*
724      * Set-up the virtual function table and reference count.
725      */
726     newStream->lpVtbl    = &StgStreamImpl_Vtbl;
727     newStream->ref       = 0;
728
729     newStream->parentStorage = parentStorage;
730
731     /*
732      * We want to nail-down the reference to the storage in case the
733      * stream out-lives the storage in the client application.
734      *
735      * -- IStorage_AddRef((IStorage*)newStream->parentStorage);
736      *
737      * No, don't do this. Some apps call IStorage_Release without
738      * calling IStream_Release first. If we grab a reference the
739      * file is not closed, and the app fails when it tries to
740      * reopen the file (Easy-PC, for example)
741      */
742
743     newStream->grfMode = grfMode;
744     newStream->dirEntry = dirEntry;
745
746     /*
747      * Start the stream at the beginning.
748      */
749     newStream->currentPosition.u.HighPart = 0;
750     newStream->currentPosition.u.LowPart = 0;
751
752     /* add us to the storage's list of active streams */
753     StorageBaseImpl_AddStream(parentStorage, newStream);
754   }
755
756   return newStream;
757 }