File: glob.cpp

package info (click to toggle)
megaglest 3.13.0-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,844 kB
  • ctags: 18,191
  • sloc: cpp: 144,280; ansic: 11,861; sh: 3,233; perl: 1,904; python: 1,751; objc: 142; asm: 42; makefile: 24
file content (473 lines) | stat: -rw-r--r-- 14,079 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/* /////////////////////////////////////////////////////////////////////////
 * File:    glob.c
 *
 * Purpose: Definition of the glob() API functions for the Win32 platform.
 *
 * Created: 13th November 2002
 * Updated: 6th February 2010
 *
 * Home:    http://synesis.com.au/software/
 *
 * Copyright (c) 2002-2010, Matthew Wilson and Synesis Software
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer. 
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the names of Matthew Wilson and Synesis Software nor the names of
 *   any contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * ////////////////////////////////////////////////////////////////////// */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#include <glob.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#define NOMINMAX
#include <windows.h>
#include "platform_util.h"

#define NUM_ELEMENTS(ar)      (sizeof(ar) / sizeof(ar[0]))

using namespace Shared::Util;
/* /////////////////////////////////////////////////////////////////////////
 * Helper functions
 */

static char const *strrpbrk(char const *string, char const *strCharSet)
{
    char const  *part   =   NULL;
    char const  *pch;

    for(pch = strCharSet; *pch; ++pch)
    {
        const char    *p  =   strrchr(string, *pch);

        if(NULL != p)
        {
            if(NULL == part)
            {
                part = p;
            }
            else
            {
                if(part < p)
                {
                    part = p;
                }
            }
        }
    }

    return part;
}

/* /////////////////////////////////////////////////////////////////////////
 * API functions
 */

/* It gives you back the matched contents of your pattern, so for Win32, the
 * directories must be included
 */

int glob(   char const  *pattern
        ,   int         flags
#if defined(__COMO__)
        , int         (*errfunc)(char const *, int)
#else /* ? compiler */
        , const int   (*errfunc)(char const *, int)
#endif /* compiler */
        ,   glob_t      *pglob)
{
    int                 result;
    char                szRelative[1 + _MAX_PATH];
    char const          *file_part;
    WIN32_FIND_DATAW    find_data;
    HANDLE              hFind;
    char                *buffer;
    char                szPattern2[1 + _MAX_PATH];
    char                szPattern3[1 + _MAX_PATH];
    char const          *effectivePattern   =   pattern;
    char const          *leafMost;
    const int           bMagic              =   (NULL != strpbrk(pattern, "?*"));
    int                 bNoMagic            =   0;
    int                 bMagic0;
    size_t              maxMatches          =   ~(size_t)(0);

    assert(NULL != pglob);

    if(flags & GLOB_NOMAGIC)
    {
        bNoMagic = !bMagic;
    }

    if(flags & GLOB_LIMIT)
    {
        maxMatches = (size_t)pglob->gl_matchc;
    }

    if(flags & GLOB_TILDE)
    {
        /* Check that begins with "~/" */
        if( '~' == pattern[0] &&
            (   '\0' == pattern[1] ||
                '/' == pattern[1] ||
                '\\' == pattern[1]))
        {
            DWORD   dw;

            (void)lstrcpyA(&szPattern2[0], "%HOMEDRIVE%%HOMEPATH%");

            dw = ExpandEnvironmentStringsA(&szPattern2[0], &szPattern3[0], NUM_ELEMENTS(szPattern3) - 1);

            if(0 != dw)
            {
                (void)lstrcpynA(&szPattern3[0] + dw - 1, &pattern[1], (int)(NUM_ELEMENTS(szPattern3) - dw));
                szPattern3[NUM_ELEMENTS(szPattern3) - 1] = '\0';

                effectivePattern = szPattern3;
            }
        }
    }

    file_part = strrpbrk(effectivePattern, "\\/");

    if(NULL != file_part)
    {
        leafMost = ++file_part;

        (void)lstrcpyA(szRelative, effectivePattern);
        szRelative[file_part - effectivePattern] = '\0';
    }
    else
    {
        szRelative[0] = '\0';
        leafMost = effectivePattern;
    }

    bMagic0 =   (leafMost == strpbrk(leafMost, "?*"));

	std::wstring wstr = utf8_decode(effectivePattern);
    hFind   =   FindFirstFileW(wstr.c_str(), &find_data);
    buffer  =   NULL;

    pglob->gl_pathc = 0;
    pglob->gl_pathv = NULL;

    if(0 == (flags & GLOB_DOOFFS))
    {
        pglob->gl_offs = 0;
    }

    if(hFind == INVALID_HANDLE_VALUE)
    {
        /* If this was a pattern search, and the
         * directory exists, then we return 0
         * matches, rather than GLOB_NOMATCH
         */
        if( bMagic &&
            NULL != file_part)
        {
            result = 0;
        }
        else
        {
            if(NULL != errfunc)
            {
                (void)errfunc(effectivePattern, (int)GetLastError());
            }

            result = GLOB_NOMATCH;
        }
    }
    else
    {
        int     cbCurr      =   0;
        size_t  cbAlloc     =   0;
        size_t  cMatches    =   0;

        result = 0;

        do
        {
            int     cch;
            size_t  new_cbAlloc;

            if( bMagic0 &&
                0 == (flags & GLOB_PERIOD))
            {
                if('.' == find_data.cFileName[0])
                {
                    continue;
                }
            }

            if(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
#ifdef GLOB_ONLYFILE
                if(flags & GLOB_ONLYFILE)
                {
                    continue;
                }
#endif /* GLOB_ONLYFILE */

                if( bMagic0 &&
                    GLOB_NODOTSDIRS == (flags & GLOB_NODOTSDIRS))
                {
                    /* Pattern must begin with '.' to match either dots directory */
                    if( 0 == lstrcmpW(L".", find_data.cFileName) ||
                        0 == lstrcmpW(L"..", find_data.cFileName))
                    {
                        continue;
                    }
                }

                if(flags & GLOB_MARK)
                {
#if 0
                    if(find_data.cFileName[0] >= 'A' && find_data.cFileName[0] <= 'M')
#endif /* 0 */
                    (void)lstrcatW(find_data.cFileName, L"/");
                }
            }
            else
            {
                if(flags & GLOB_ONLYDIR)
                {
                    /* Skip all further actions, and get the next entry */
#if 0
                    if(find_data.cFileName[0] >= 'A' && find_data.cFileName[0] <= 'M')
#endif /* 0 */
                    continue;
                }
            }

            //cch = lstrlenW(find_data.cFileName);
			string sFileName = utf8_encode(find_data.cFileName);
			cch = (int)sFileName.length();
            if(NULL != file_part)
            {
                cch += (int)(file_part - effectivePattern);
            }

            new_cbAlloc = (size_t)cbCurr + cch + 1;
            if(new_cbAlloc > cbAlloc)
            {
                char    *new_buffer;

                new_cbAlloc *= 2;

                new_cbAlloc = (new_cbAlloc + 31) & ~(31);

                new_buffer  = (char*)realloc(buffer, new_cbAlloc);

                if(new_buffer == NULL)
                {
                    result = GLOB_NOSPACE;
                    if(buffer) {
                    	free(buffer);
                    	buffer = NULL;
                    }
                    break;
                }

                buffer = new_buffer;
                cbAlloc = new_cbAlloc;
            }

			if(buffer == NULL) {
				throw exception("buffer == NULL");
			}
            (void)lstrcpynA(buffer + cbCurr, szRelative, 1 + (int)(file_part - effectivePattern));
            (void)lstrcatA(buffer + cbCurr, sFileName.c_str());
            cbCurr += cch + 1;

            ++cMatches;
        }
        //while(FindNextFileA(hFind, &find_data) && cMatches != maxMatches);
		while(FindNextFileW(hFind, &find_data) && cMatches != maxMatches);

        (void)FindClose(hFind);

        if(result == 0)
        {
            /* Now expand the buffer, to fit in all the pointers. */
            size_t  cbPointers  =   (1 + cMatches + pglob->gl_offs) * sizeof(char*);
            char    *new_buffer =   (char*)realloc(buffer, cbAlloc + cbPointers);

            if(new_buffer == NULL)
            {
                result = GLOB_NOSPACE;
                if(buffer) {
                	free(buffer);
                	buffer = NULL;
                }
            }
            else
            {
                char    **pp;
                char    **begin;
                char    **end;
                char    *next_str;

                buffer = new_buffer;

                (void)memmove(new_buffer + cbPointers, new_buffer, cbAlloc);

                /* Handle the offsets. */
                begin =   (char**)new_buffer;
                end   =   begin + pglob->gl_offs;

                for(; begin != end; ++begin)
                {
                    *begin = NULL;
                }

                /* Sort, or no sort. */
                pp    =   (char**)new_buffer + pglob->gl_offs;
                begin =   pp;
                end   =   begin + cMatches;

                if(flags & GLOB_NOSORT)
                {
                    /* The way we need in order to test the removal of dots in the findfile_sequence. */
                    *end = NULL;
                    for(begin = pp, next_str = buffer + cbPointers; begin != end; --end)
                    {
                        *(end - 1) = next_str;

                        /* Find the next string. */
                        next_str += 1 + lstrlenA(next_str);
                    }
                }
                else
                {
                    /* The normal way. */
                    for(begin = pp, next_str = buffer + cbPointers; begin != end; ++begin)
                    {
                        *begin = next_str;

                        /* Find the next string. */
                        next_str += 1 + lstrlenA(next_str);
                    }
                    *begin = NULL;
                }

                /* Return results to caller. */
                pglob->gl_pathc =   (int)cMatches;
                pglob->gl_matchc=   (int)cMatches;
                pglob->gl_flags =   0;
                if(bMagic)
                {
                    pglob->gl_flags |= GLOB_MAGCHAR;
                }
                pglob->gl_pathv =   (char**)new_buffer;
            }
        }

        if(0 == cMatches)
        {
            result = GLOB_NOMATCH;
        }
    }

    if(GLOB_NOMATCH == result)
    {
        if( (flags & GLOB_TILDE_CHECK) &&
            effectivePattern == szPattern3)
        {
            result = GLOB_NOMATCH;
        }
        else if(bNoMagic ||
                (flags & GLOB_NOCHECK))
        {
            const size_t    effPattLen  =   strlen(effectivePattern);
            const size_t    cbNeeded    =   ((2 + pglob->gl_offs) * sizeof(char*)) + (1 + effPattLen);
            char            **pp        =   (char**)realloc(buffer, cbNeeded);

            if(NULL == pp)
            {
                result = GLOB_NOSPACE;
                if(buffer) {
                	free(buffer);
                	buffer = NULL;
                }
            }
            else
            {
                /* Handle the offsets. */
                char**  begin   =   pp;
                char**  end     =   pp + pglob->gl_offs;
                char*   dest    =   (char*)(pp + 2 + pglob->gl_offs);

                for(; begin != end; ++begin)
                {
                    *begin = NULL;
                }

                /* Synthesise the pattern result. */
#ifdef UNIXEM_USING_SAFE_STR_FUNCTIONS
                pp[0 + pglob->gl_offs]  =   (strcpy_s(dest, effPattLen + 1, effectivePattern), dest);
#else /* ? UNIXEM_USING_SAFE_STR_FUNCTIONS */
                pp[0 + pglob->gl_offs]  =   strcpy(dest, effectivePattern);
#endif /* UNIXEM_USING_SAFE_STR_FUNCTIONS */
                pp[1 + pglob->gl_offs]  =   NULL;

                /* Return results to caller. */
                pglob->gl_pathc =   1;
                pglob->gl_matchc=   1;
                pglob->gl_flags =   0;
                if(bMagic)
                {
                    pglob->gl_flags |= GLOB_MAGCHAR;
                }
                pglob->gl_pathv =   pp;

                result = 0;
            }
        }
    }
    else if(0 == result)
    {
        if((size_t)pglob->gl_matchc == maxMatches)
        {
            result = GLOB_NOSPACE;
        }
    }

    return result;
}

void globfree(glob_t *pglob)
{
    if(pglob != NULL)
    {
        free(pglob->gl_pathv);
        pglob->gl_pathc = 0;
        pglob->gl_pathv = NULL;
    }
}

/* ///////////////////////////// end of file //////////////////////////// */