Coverage Report

Created: 2026-11-10 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/utils/collections/StreamPool.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Object Pool
4
 *
5
 * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
20
#include <winpr/config.h>
21
#include <winpr/interlocked.h>
22
23
#include <winpr/crt.h>
24
#include <winpr/wlog.h>
25
26
#include <winpr/collections.h>
27
28
#include "../stream.h"
29
#include "../log.h"
30
4.39k
#define XTAG WINPR_TAG("utils.streampool")
31
32
#if !defined(STREAMPOOL_SIZE_LIMIT)
33
#error "CMake must define STREAMPOOL_SIZE_LIMIT=<unsigned>"
34
#endif
35
static const size_t POOL_COMMON_LIMIT = STREAMPOOL_SIZE_LIMIT;
36
37
struct s_StreamPoolEntry
38
{
39
#if defined(WITH_DEBUG_STREAMPOOL)
40
  char** msg;
41
  size_t lines;
42
#endif
43
  wStream* s;
44
};
45
46
struct s_wStreamPool
47
{
48
  size_t aSize;
49
  size_t aCapacity;
50
  struct s_StreamPoolEntry* aArray;
51
52
  size_t uSize;
53
  size_t uCapacity;
54
  struct s_StreamPoolEntry* uArray;
55
56
  CRITICAL_SECTION lock;
57
  BOOL synchronized;
58
  size_t defaultSize;
59
  wLog* log;
60
};
61
62
static void discard_entry(struct s_StreamPoolEntry* entry, BOOL discardStream)
63
106k
{
64
106k
  if (!entry)
65
0
    return;
66
67
106k
#if defined(WITH_DEBUG_STREAMPOOL)
68
106k
  free((void*)entry->msg);
69
106k
#endif
70
71
106k
  if (discardStream && entry->s)
72
8.29k
    Stream_Free(entry->s, entry->s->isAllocatedStream);
73
74
106k
  const struct s_StreamPoolEntry empty = WINPR_C_ARRAY_INIT;
75
106k
  *entry = empty;
76
106k
}
77
78
static struct s_StreamPoolEntry add_entry(wStream* s)
79
106k
{
80
106k
  struct s_StreamPoolEntry entry = WINPR_C_ARRAY_INIT;
81
82
106k
#if defined(WITH_DEBUG_STREAMPOOL)
83
106k
  void* stack = winpr_backtrace(20);
84
106k
  if (stack)
85
106k
    entry.msg = winpr_backtrace_symbols(stack, &entry.lines);
86
106k
  winpr_backtrace_free(stack);
87
106k
#endif
88
89
106k
  entry.s = s;
90
106k
  return entry;
91
106k
}
92
93
/**
94
 * Lock the stream pool
95
 */
96
97
static inline void StreamPool_Lock(wStreamPool* pool)
98
113k
{
99
113k
  WINPR_ASSERT(pool);
100
113k
  if (pool->synchronized)
101
113k
    EnterCriticalSection(&pool->lock);
102
113k
}
103
104
/**
105
 * Unlock the stream pool
106
 */
107
108
static inline void StreamPool_Unlock(wStreamPool* pool)
109
113k
{
110
113k
  WINPR_ASSERT(pool);
111
113k
  if (pool->synchronized)
112
113k
    LeaveCriticalSection(&pool->lock);
113
113k
}
114
115
static BOOL StreamPool_ShrinkToCommonLimit(wStream* s)
116
53.2k
{
117
53.2k
  if (Stream_Capacity(s) <= POOL_COMMON_LIMIT)
118
53.2k
    return TRUE;
119
120
0
  return Stream_ResizeToCapacity(s, POOL_COMMON_LIMIT);
121
53.2k
}
122
123
static BOOL StreamPool_EnsureCapacity(wStreamPool* pool, size_t count, BOOL usedOrAvailable)
124
115k
{
125
115k
  WINPR_ASSERT(pool);
126
127
115k
  size_t* cap = (usedOrAvailable) ? &pool->uCapacity : &pool->aCapacity;
128
115k
  size_t* size = (usedOrAvailable) ? &pool->uSize : &pool->aSize;
129
115k
  struct s_StreamPoolEntry** array = (usedOrAvailable) ? &pool->uArray : &pool->aArray;
130
131
115k
  size_t new_cap = 0;
132
115k
  if (*cap == 0)
133
8.78k
    new_cap = *size + count;
134
106k
  else if (*size + count > *cap)
135
22
    new_cap = (*size + count + 2) / 2 * 3;
136
106k
  else if ((*size + count) < *cap / 3)
137
14.4k
    new_cap = *cap / 2;
138
139
115k
  if (new_cap > 0)
140
23.2k
  {
141
23.2k
    struct s_StreamPoolEntry* new_arr = nullptr;
142
143
23.2k
    if (*cap < *size + count)
144
8.81k
      *cap += count;
145
146
23.2k
    new_arr =
147
23.2k
        (struct s_StreamPoolEntry*)realloc(*array, sizeof(struct s_StreamPoolEntry) * new_cap);
148
23.2k
    if (!new_arr)
149
0
      return FALSE;
150
23.2k
    *cap = new_cap;
151
23.2k
    *array = new_arr;
152
23.2k
  }
153
115k
  return TRUE;
154
115k
}
155
156
/**
157
 * Methods
158
 */
159
160
static void StreamPool_ShiftUsed(wStreamPool* pool, size_t index)
161
53.2k
{
162
53.2k
  WINPR_ASSERT(pool);
163
164
53.2k
  const size_t pcount = 1;
165
53.2k
  const size_t off = index + pcount;
166
53.2k
  if (pool->uSize >= off)
167
53.2k
  {
168
106k
    for (size_t x = 0; x < pcount; x++)
169
53.2k
    {
170
53.2k
      struct s_StreamPoolEntry* cur = &pool->uArray[index + x];
171
53.2k
      discard_entry(cur, FALSE);
172
53.2k
    }
173
53.2k
    MoveMemory(&pool->uArray[index], &pool->uArray[index + pcount],
174
53.2k
               (pool->uSize - index - pcount) * sizeof(struct s_StreamPoolEntry));
175
53.2k
    pool->uSize -= pcount;
176
53.2k
  }
177
53.2k
}
178
179
/**
180
 * Adds a used stream to the pool.
181
 */
182
183
static void StreamPool_AddUsed(wStreamPool* pool, wStream* s)
184
53.2k
{
185
53.2k
  StreamPool_EnsureCapacity(pool, 1, TRUE);
186
53.2k
  pool->uArray[pool->uSize] = add_entry(s);
187
53.2k
  pool->uSize++;
188
53.2k
}
189
190
/**
191
 * Removes a used stream from the pool.
192
 */
193
194
static void StreamPool_RemoveUsed(wStreamPool* pool, wStream* s)
195
53.2k
{
196
53.2k
  WINPR_ASSERT(pool);
197
74.0k
  for (size_t index = 0; index < pool->uSize; index++)
198
74.0k
  {
199
74.0k
    struct s_StreamPoolEntry* cur = &pool->uArray[index];
200
74.0k
    if (cur->s == s)
201
53.2k
    {
202
53.2k
      StreamPool_ShiftUsed(pool, index);
203
53.2k
      break;
204
53.2k
    }
205
74.0k
  }
206
53.2k
}
207
208
static void StreamPool_ShiftAvailable(wStreamPool* pool, size_t index)
209
44.9k
{
210
44.9k
  WINPR_ASSERT(pool);
211
212
44.9k
  const size_t pcount = 1;
213
44.9k
  const size_t off = index + pcount;
214
44.9k
  if (pool->aSize >= off)
215
44.9k
  {
216
89.8k
    for (size_t x = 0; x < pcount; x++)
217
44.9k
    {
218
44.9k
      struct s_StreamPoolEntry* cur = &pool->aArray[index + x];
219
44.9k
      discard_entry(cur, FALSE);
220
44.9k
    }
221
222
44.9k
    MoveMemory(&pool->aArray[index], &pool->aArray[index + pcount],
223
44.9k
               (pool->aSize - index - pcount) * sizeof(struct s_StreamPoolEntry));
224
44.9k
    pool->aSize -= pcount;
225
44.9k
  }
226
44.9k
}
227
228
/**
229
 * Gets a stream from the pool.
230
 */
231
232
wStream* StreamPool_Take(wStreamPool* pool, size_t size)
233
53.2k
{
234
53.2k
  BOOL found = FALSE;
235
53.2k
  size_t foundIndex = 0;
236
53.2k
  wStream* s = nullptr;
237
238
53.2k
  StreamPool_Lock(pool);
239
240
53.2k
  if (size == 0)
241
8.19k
    size = pool->defaultSize;
242
243
125k
  for (size_t index = 0; index < pool->aSize; index++)
244
117k
  {
245
117k
    struct s_StreamPoolEntry* cur = &pool->aArray[index];
246
117k
    s = cur->s;
247
248
117k
    if (Stream_Capacity(s) >= size)
249
44.9k
    {
250
44.9k
      found = TRUE;
251
44.9k
      foundIndex = index;
252
44.9k
      break;
253
44.9k
    }
254
117k
  }
255
256
53.2k
  if (!found)
257
8.29k
  {
258
8.29k
    s = Stream_New(nullptr, size);
259
8.29k
    if (!s)
260
0
      goto out_fail;
261
8.29k
  }
262
44.9k
  else if (s)
263
44.9k
  {
264
44.9k
    Stream_ResetPosition(s);
265
44.9k
    if (!Stream_SetLength(s, Stream_Capacity(s)))
266
0
      goto out_fail;
267
44.9k
    StreamPool_ShiftAvailable(pool, foundIndex);
268
44.9k
  }
269
270
53.2k
  if (s)
271
53.2k
  {
272
53.2k
    s->pool = pool;
273
53.2k
    s->count = 1;
274
53.2k
    StreamPool_AddUsed(pool, s);
275
53.2k
  }
276
277
53.2k
out_fail:
278
53.2k
  StreamPool_Unlock(pool);
279
280
53.2k
  return s;
281
53.2k
}
282
283
/**
284
 * Returns an object to the pool.
285
 */
286
287
static void StreamPool_Remove(wStreamPool* pool, wStream* s)
288
53.2k
{
289
53.2k
  StreamPool_EnsureCapacity(pool, 1, FALSE);
290
53.2k
  Stream_EnsureValidity(s);
291
53.2k
  StreamPool_ShrinkToCommonLimit(s);
292
147k
  for (size_t x = 0; x < pool->aSize; x++)
293
94.3k
  {
294
94.3k
    wStream* cs = pool->aArray[x].s;
295
94.3k
    if (cs == s)
296
0
      return;
297
94.3k
  }
298
53.2k
  pool->aArray[(pool->aSize)++] = add_entry(s);
299
53.2k
  StreamPool_RemoveUsed(pool, s);
300
53.2k
}
301
302
static void StreamPool_ReleaseOrReturn(wStreamPool* pool, wStream* s)
303
53.2k
{
304
53.2k
  StreamPool_Lock(pool);
305
53.2k
  StreamPool_Remove(pool, s);
306
53.2k
  StreamPool_Unlock(pool);
307
53.2k
}
308
309
void StreamPool_Return(wStreamPool* pool, wStream* s)
310
0
{
311
0
  WINPR_ASSERT(pool);
312
0
  if (!s)
313
0
    return;
314
315
0
  StreamPool_Lock(pool);
316
0
  StreamPool_Remove(pool, s);
317
0
  StreamPool_Unlock(pool);
318
0
}
319
320
/**
321
 * Increment stream reference count
322
 */
323
324
void Stream_AddRef(wStream* s)
325
29.4k
{
326
29.4k
  WINPR_ASSERT(s);
327
29.4k
  InterlockedIncrement(&s->count);
328
29.4k
}
329
330
/**
331
 * Decrement stream reference count
332
 */
333
334
void Stream_Release(wStream* s)
335
53.2k
{
336
53.2k
  WINPR_ASSERT(s);
337
338
53.2k
  const LONG val = InterlockedDecrement(&s->count);
339
53.2k
  if (val <= 0)
340
53.2k
  {
341
53.2k
    if (s->pool)
342
53.2k
      StreamPool_ReleaseOrReturn(s->pool, s);
343
0
    else
344
0
      Stream_Free(s, TRUE);
345
53.2k
  }
346
53.2k
}
347
348
/**
349
 * Find stream in pool using pointer inside buffer
350
 */
351
352
wStream* StreamPool_Find(wStreamPool* pool, const BYTE* ptr)
353
0
{
354
0
  wStream* s = nullptr;
355
356
0
  StreamPool_Lock(pool);
357
358
0
  for (size_t index = 0; index < pool->uSize; index++)
359
0
  {
360
0
    struct s_StreamPoolEntry* cur = &pool->uArray[index];
361
362
0
    if ((ptr >= Stream_Buffer(cur->s)) &&
363
0
        (ptr < (Stream_Buffer(cur->s) + Stream_Capacity(cur->s))))
364
0
    {
365
0
      s = cur->s;
366
0
      break;
367
0
    }
368
0
  }
369
370
0
  StreamPool_Unlock(pool);
371
372
0
  return s;
373
0
}
374
375
/**
376
 * Releases the streams currently cached in the pool.
377
 */
378
379
void StreamPool_Clear(wStreamPool* pool)
380
4.39k
{
381
4.39k
  StreamPool_Lock(pool);
382
383
12.6k
  for (size_t x = 0; x < pool->aSize; x++)
384
8.29k
  {
385
8.29k
    struct s_StreamPoolEntry* cur = &pool->aArray[x];
386
8.29k
    discard_entry(cur, TRUE);
387
8.29k
  }
388
4.39k
  pool->aSize = 0;
389
390
4.39k
  if (pool->uSize > 0)
391
0
  {
392
0
    WLog_Print(pool->log, WLOG_WARN,
393
0
               "Clearing StreamPool, but there are %" PRIuz " streams currently in use",
394
0
               pool->uSize);
395
0
    for (size_t x = 0; x < pool->uSize; x++)
396
0
    {
397
0
      struct s_StreamPoolEntry* cur = &pool->uArray[x];
398
0
      discard_entry(cur, TRUE);
399
0
    }
400
0
    pool->uSize = 0;
401
0
  }
402
403
4.39k
  StreamPool_Unlock(pool);
404
4.39k
}
405
406
size_t StreamPool_UsedCount(wStreamPool* pool)
407
2.19k
{
408
2.19k
  StreamPool_Lock(pool);
409
2.19k
  size_t usize = pool->uSize;
410
2.19k
  StreamPool_Unlock(pool);
411
2.19k
  return usize;
412
2.19k
}
413
414
/**
415
 * Construction, Destruction
416
 */
417
418
wStreamPool* StreamPool_New(BOOL synchronized, size_t defaultSize)
419
4.39k
{
420
4.39k
  wStreamPool* pool = calloc(1, sizeof(wStreamPool));
421
422
4.39k
  if (!pool)
423
0
    return nullptr;
424
425
4.39k
  pool->log = WLog_Create(XTAG, WLog_GetRoot());
426
4.39k
  if (!pool->log)
427
0
    goto fail;
428
429
4.39k
  pool->synchronized = synchronized;
430
4.39k
  pool->defaultSize = defaultSize;
431
432
4.39k
  if (!StreamPool_EnsureCapacity(pool, 32, FALSE))
433
0
    goto fail;
434
4.39k
  if (!StreamPool_EnsureCapacity(pool, 32, TRUE))
435
0
    goto fail;
436
437
4.39k
  if (!InitializeCriticalSectionAndSpinCount(&pool->lock, 4000))
438
0
    goto fail;
439
440
4.39k
  return pool;
441
0
fail:
442
0
  WINPR_PRAGMA_DIAG_PUSH
443
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
444
0
  StreamPool_Free(pool);
445
0
  WINPR_PRAGMA_DIAG_POP
446
0
  return nullptr;
447
4.39k
}
448
449
void StreamPool_Free(wStreamPool* pool)
450
4.39k
{
451
4.39k
  if (!pool)
452
0
    return;
453
454
4.39k
  StreamPool_Clear(pool);
455
456
4.39k
  DeleteCriticalSection(&pool->lock);
457
458
4.39k
  free(pool->aArray);
459
4.39k
  free(pool->uArray);
460
461
4.39k
  WLog_Discard(pool->log);
462
4.39k
  free(pool);
463
4.39k
}
464
465
char* StreamPool_GetStatistics(wStreamPool* pool, char* buffer, size_t size)
466
0
{
467
0
  WINPR_ASSERT(pool);
468
469
0
  if (!buffer || (size < 1))
470
0
    return nullptr;
471
472
0
  size_t used = 0;
473
0
  int offset = _snprintf(buffer, size - 1,
474
0
                         "aSize    =%" PRIuz ", uSize    =%" PRIuz ", aCapacity=%" PRIuz
475
0
                         ", uCapacity=%" PRIuz,
476
0
                         pool->aSize, pool->uSize, pool->aCapacity, pool->uCapacity);
477
0
  if ((offset > 0) && ((size_t)offset < size))
478
0
    used += (size_t)offset;
479
480
0
#if defined(WITH_DEBUG_STREAMPOOL)
481
0
  StreamPool_Lock(pool);
482
483
0
  offset = _snprintf(&buffer[used], size - 1 - used, "\n-- dump used array take locations --\n");
484
0
  if ((offset > 0) && ((size_t)offset < size - used))
485
0
    used += (size_t)offset;
486
0
  for (size_t x = 0; x < pool->uSize; x++)
487
0
  {
488
0
    const struct s_StreamPoolEntry* cur = &pool->uArray[x];
489
0
    WINPR_ASSERT(cur->msg || (cur->lines == 0));
490
491
0
    for (size_t y = 0; y < cur->lines; y++)
492
0
    {
493
0
      offset = _snprintf(&buffer[used], size - 1 - used, "[%" PRIuz " | %" PRIuz "]: %s\n", x,
494
0
                         y, cur->msg[y]);
495
0
      if ((offset > 0) && ((size_t)offset < size - used))
496
0
        used += (size_t)offset;
497
0
    }
498
0
  }
499
500
0
  offset = _snprintf(&buffer[used], size - 1 - used, "\n-- statistics called from --\n");
501
0
  if ((offset > 0) && ((size_t)offset < size - used))
502
0
    used += (size_t)offset;
503
504
0
  struct s_StreamPoolEntry entry = WINPR_C_ARRAY_INIT;
505
0
  void* stack = winpr_backtrace(20);
506
0
  if (stack)
507
0
    entry.msg = winpr_backtrace_symbols(stack, &entry.lines);
508
0
  winpr_backtrace_free(stack);
509
510
0
  for (size_t x = 0; x < entry.lines; x++)
511
0
  {
512
0
    const char* msg = entry.msg[x];
513
0
    offset = _snprintf(&buffer[used], size - 1 - used, "[%" PRIuz "]: %s\n", x, msg);
514
0
    if ((offset > 0) && ((size_t)offset < size - used))
515
0
      used += (size_t)offset;
516
0
  }
517
0
  free((void*)entry.msg);
518
0
  StreamPool_Unlock(pool);
519
0
#endif
520
0
  buffer[used] = '\0';
521
0
  return buffer;
522
0
}
523
524
BOOL StreamPool_WaitForReturn(wStreamPool* pool, UINT32 timeoutMS)
525
2.19k
{
526
  /* HACK: We disconnected the transport above, now wait without a read or write lock until all
527
   * streams in use have been returned to the pool. */
528
2.19k
  while (timeoutMS > 0)
529
2.19k
  {
530
2.19k
    const size_t used = StreamPool_UsedCount(pool);
531
2.19k
    if (used == 0)
532
2.19k
      return TRUE;
533
0
    WLog_Print(pool->log, WLOG_DEBUG, "%" PRIuz " streams still in use, sleeping...", used);
534
535
0
    char buffer[4096] = WINPR_C_ARRAY_INIT;
536
0
    StreamPool_GetStatistics(pool, buffer, sizeof(buffer));
537
0
    WLog_Print(pool->log, WLOG_TRACE, "Pool statistics: %s", buffer);
538
539
0
    UINT32 diff = 10;
540
0
    if (timeoutMS != INFINITE)
541
0
    {
542
0
      diff = timeoutMS > 10 ? 10 : timeoutMS;
543
0
      timeoutMS -= diff;
544
0
    }
545
0
    Sleep(diff);
546
0
  }
547
548
0
  return FALSE;
549
2.19k
}