File: File.h

package info (click to toggle)
intel-graphics-compiler 1.0.12504.6-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 83,912 kB
  • sloc: cpp: 910,147; lisp: 202,655; ansic: 15,197; python: 4,025; yacc: 2,241; lex: 1,570; pascal: 244; sh: 104; makefile: 25
file content (719 lines) | stat: -rw-r--r-- 19,848 bytes parent folder | download
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*========================== begin_copyright_notice ============================

Copyright (C) 2019-2021 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#pragma once

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string>
#include <errno.h>
#include "MemCopy.h"

#include "Debug.h"

#if defined _WIN32
#   include <direct.h>
#   include <wtypes.h>
#   include <winbase.h>
#   include <process.h>
// disable warning about deprecated functions:
// 'vsprintf' and 'fopen'
#   pragma warning(push)
#   pragma warning(disable: 4996)
#elif defined(__GNUC__)
#   include <libgen.h>
#   include <sys/stat.h>
#endif


namespace iSTD
{

/*****************************************************************************\
Function Prototypes
\*****************************************************************************/
inline int DirectoryCreate( const char * dirPath );
inline DWORD GetModuleFileName( char* pFileName, DWORD bufSize );

inline void* FileOpen( const char * fileName,
                      const char * mode );

inline void FileWrite( const void* pFile, const char * str, ... );
inline void FileClose( void* pFile );
inline DWORD FileRead( const void* pFile, void* pBuffer, DWORD bufSize );
inline DWORD FileSize( const void* pFile );
inline void LogToFile( const char* filename, const char * str, ... );
inline signed long ReadParamFromFile( char* filename, DWORD line );


/*****************************************************************************\
Inline Function:
    DirectoryCreate

Description:
    Creates a directory
\*****************************************************************************/
inline int DirectoryCreate( const char * dirPath )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
#   if defined _WIN32
    return _mkdir( dirPath );
#   endif
#   if defined (__GNUC__)
    return mkdir( dirPath, ( S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_IFDIR ) );
#   endif
#endif
}


/*****************************************************************************\
Inline Function:
    GetModuleFileName

Description:
    Gets file name of a runnimg application module
\*****************************************************************************/
inline DWORD GetModuleFileName( char* pFileName, DWORD bufSize )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently not implemented for kernel-mode
    return 0;
#elif defined(ISTDLIB_UMD)
    #if defined(_WIN32)
        return ::GetModuleFileNameA( NULL, pFileName, bufSize );
    #elif defined(__linux__)
        //TODO: add Linux implementation.
        return 0;
    #else
        // TO DO: replace with non-Windows version
        #error "TODO implement non-Windows equivalent of GetModuleFileName"
    #endif
#else
    // this compilation path is not intended
    // neither UMD nor KMD flag is set

   // this assert is commented out due to the number of solutions that do not define
   // ISTDLIB as KMD or UMD, it may be enabled in separate commit
   // C_ASSERT( 0 );

    return 0;
#endif
}


/*****************************************************************************\
Inline Function:
    OpenFile

Description:
    Opens a file based on the provided mode
\*****************************************************************************/
inline void* FileOpen( const char * fileName,
                      const char * mode )
{
    FILE * pFile;
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
    pFile = NULL;
#elif defined(ISTDLIB_UMD)
    pFile = fopen( fileName , mode );
#if defined(_WIN32)
    // Clear extra error information = ERROR_ALREADY_EXISTS set by windows when function success
    // It is necessary, cause it could be wrongly interpreted as fail of other function.
    if ( pFile &&  GetLastError() == ERROR_ALREADY_EXISTS )
    {
        SetLastError( 0 );
    }
#endif
#endif
    return pFile;
}


/*****************************************************************************\
Inline Function:
    CloseFile

Description:
    Close a file
\*****************************************************************************/
inline void FileClose( void* pFile )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( pFile )
    {
        fclose ( (FILE*)pFile );
    }
#endif
}


/*****************************************************************************\
Inline Function:
    WriteFile

Description:
    Writes the str to the provide file if it exists
\*****************************************************************************/
inline void FileWrite( const void* pFile, const char * str, ... )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( str != NULL )
    {
        va_list args;

        va_start( args, str );
        const size_t length = _vscprintf( str, args );
        va_end( args );

        char* temp = new char[ length + 1 ];

        if( temp )
        {
            va_start( args, str );
            VSNPRINTF( temp, length + 1, length+ 1, str, args );
            va_end( args );

            if( pFile )
            {
                fwrite( temp , 1 , length, (FILE*)pFile );
            }
            delete[] temp;
        }
    }
#endif
}


/*****************************************************************************\
Inline Function:
    WriteFile

Description:
    Overloaded function writes stream to the provide file if it exists
\*****************************************************************************/
inline void FileWrite( const void * str, size_t size , size_t count, const void* pFile )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( str != NULL )
    {
        if( pFile )
        {
            fwrite( str , size , count , (FILE*)pFile );
        }
    }
#endif
}


/*****************************************************************************\
Inline Function:
    FileRead

Description:
    Reads bufSize bytes from given file, and saves it to pBuffer. Returns
    number of read bytes - it may be diffrent than bufSize, if file is
    shorter than bufSize.
\*****************************************************************************/
inline DWORD FileRead( const void* pFile, void* pBuffer, DWORD bufSize )
{
    DWORD bytesRead = 0;
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( pFile )
    {
        bytesRead = (DWORD) fread( pBuffer, sizeof(BYTE), bufSize, (FILE*)pFile );
    }
#endif
    return bytesRead;
}


/*****************************************************************************\
Inline Function:
    FileSize

Description:
    Returns size in bytes of given file.
\*****************************************************************************/
inline DWORD FileSize( const void* pFile )
{
    DWORD fileSize = 0;
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( pFile )
    {
        long int currPosition = ftell( (FILE*)pFile );
        fseek( (FILE*)pFile, 0, SEEK_END );

        // Clamp result to 0, ftell can return -1 in case of an error.
        long int endPosition = ftell( (FILE*)pFile );
        fileSize = (DWORD)( endPosition >= 0 ? endPosition : 0 );

        fseek( (FILE*)pFile, currPosition, SEEK_SET );
    }
#endif
    return fileSize;
}


/*****************************************************************************\
Inline Function:
    LogToFile

Description:
    Writes the str to the file with provided filename, creates the file if it
    does not exists, for debug purposes only
\*****************************************************************************/
inline void LogToFile( const char* filename, const char * str, ... )
{
#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)
    if( str != NULL )
    {
        va_list args;

        va_start( args, str );
        const size_t length = _vscprintf( str, args );
        va_end( args );

        char* temp = new char[ length + 1 ];

        if( temp )
        {
            va_start( args, str );
            VSNPRINTF( temp, length + 1, length + 1, str, args );
            va_end( args );

            FILE* file = fopen( filename, "a" );
            if( file )
            {
                fwrite( temp , 1 , length, (FILE*)file );
                fclose( file );
            }
            delete[] temp;
        }
    }
#endif
}


/*****************************************************************************\
Inline Function:
    ReadParamFromFile

Description:
    reads n-th line from file specified as param, converts it (if possible)
    to signed long and return its value, if conversion is impossible or if
    file does not exists returns 0, line length in file cannot exceed
    bufsize (currently 20) characters, for debug purposes only
\*****************************************************************************/
inline signed long ReadParamFromFile( char* filename, DWORD line = 1 )
{
    signed long ret = 0;

#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD)

    FILE* file = fopen( filename, "r" );
    if( file )
    {
        const char bufsize = 20;
        char buf[ bufsize + 1 ] = "";

        // skip first n-1 lines
        while( --line && !feof( file ) )
        {
            fgets( buf, bufsize, file );
        }

        if( !feof( file ) )
        {
            iSTD::SafeMemSet( buf, 0, bufsize );
            fgets( buf, bufsize, file );
            ret = atoi( buf );
        }
        fclose( file );
    }
#endif
    return ret;
}


/*****************************************************************************\
Inline Function:
    CreateAppOutputDir

Description:
    Creates folder path based on outputDirectory string and input parameters.
    Then writes it in pathBuf.

Input:
    unsigned int    bufSize
    const char*     outputDirectory
    bool            addSystemDrive
    bool            addProcName
    bool            pidEnabled

Output:
    char*           pathBuf
    int             ret             - return value: 0 - success, -1 - fail

\*****************************************************************************/
inline int CreateAppOutputDir(
    char*           pathBuf,
    unsigned int    bufSize,
    const char*     outputDirectory,
    bool            addSystemDrive,
    bool            addProcName,
    bool            pidEnabled )
{
    int ret = 0;

#if defined(ISTDLIB_KMD)
    // TO DO: Currently only UMD is implemented
#elif defined(ISTDLIB_UMD) && defined(_WIN32)
    const size_t size = 1024;

    char outputDirPath[size] = {0};

    if( addSystemDrive )
    {
        // get system drive from environment variables
        char* envSystemDrive = getenv( "SystemDrive" );
        if( envSystemDrive )
        {
            STRCPY( outputDirPath, size, envSystemDrive );
        }
        STRCAT( outputDirPath, size, outputDirectory );
    }
    else
    {
        STRCPY( outputDirPath, size, outputDirectory );
    }

    //check whether latest mark is backslash and insert it if not
    size_t pathLen = strnlen_s( outputDirPath, size );
    if( ( pathLen < size ) && ( outputDirPath[pathLen-1] != '\\' ) )
    {
        STRCAT( outputDirPath, size, "\\" );
    }

    if( addProcName )
    {
        char appPath[512] = {0};

        // check a process id and make an adequate directory for it:
        if( GetModuleFileName( appPath, sizeof(appPath) -1 ) )
        {
            char* pprocessName = strrchr( appPath, '\\' );
            STRCAT( outputDirPath, size, ++pprocessName );
            STRCAT( outputDirPath, size, "\\" );
        }
        else
        {
            STRCAT( outputDirPath, size, "unknownProcess\\" );
        }

        if ( pidEnabled )
        {
            //append process id
            size_t pid = _getpid();
            size_t pathLen = strnlen_s( outputDirPath, size );
            if( ( pathLen < size ) && ( pathLen > 0 ) )
            {
                //check latest mark and add pid number before backslash
                if( outputDirPath[pathLen-1] == '\\' )
                {
                    --pathLen;
                }
                SPRINTF( outputDirPath + pathLen, size - pathLen, "_%Id\\", pid );
            }
        }
    }

    char currDirectory[size] = {0};
    int currDirIter = 0;
    const char* cPtr = outputDirPath;

    bool afterFirstSlash = false;
    errno_t err;

    // Create directories in path one by one
    while( *cPtr )
    {
        currDirectory[currDirIter++] = *cPtr;
        currDirectory[currDirIter] = 0;

        // If we found backslash, create directory
        // Omit first backslash - this is the root
        if( *cPtr == '\\' )
        {
            if( afterFirstSlash )
            {
                if( DirectoryCreate( currDirectory ) != 0 )
                {
                    _get_errno( &err );
                    if ( err != EEXIST )
                    {
                        ret = -1;
                        break;
                    }
                }
            }
            else
            {
                afterFirstSlash = true;
            }
        }

        cPtr++;
    }

    DWORD length = ( DWORD ) strlen( outputDirPath );
    length = ( bufSize-1 < length ) ? bufSize-1 : length;
    MemCopy( pathBuf, outputDirPath, length );
    pathBuf[length] = 0;

#elif !defined(_WIN32)
//if not Win, need to be Linux or Android.
//not _WIN32 is needed because not all projects define ISTDLIB_UMD
    char *path = (char*)malloc(sizeof(char)*bufSize);
    char *outputDirectoryCopy = (char*)malloc(sizeof(char)*bufSize);

    if (NULL == path)
    {
        return -1;
    }

    STRCPY(outputDirectoryCopy, bufSize, outputDirectory);
    if (addProcName)
    {

        const int defaultBuffSize = 1024; //max size for file from /proc/%d/cmdline
        char cmdpath[defaultBuffSize];
        char cmdline[defaultBuffSize] = "\0";
        char cmdlineoutput[defaultBuffSize] = "/";
        unsigned int pid = getpid();

        snprintf(cmdpath, defaultBuffSize - 1, "/proc/%u/cmdline", pid);
        FILE * fp = fopen(cmdpath, "r");
        if (fp)
        {
            if (fgets(cmdline, defaultBuffSize, fp) == NULL)
            {
                STRCPY(cmdline, defaultBuffSize, "unknownProcess");
            }
            fclose(fp);
        }

        if (strcmp(cmdline, "") == 0)
        {
            snprintf(cmdline, defaultBuffSize - 1, "unknownProcess");
        }
        else
        {
            for (int i = 0; i < defaultBuffSize - 1 && cmdline[i] != '\0'; i++)
            {
                // If $APPNAME launches another process this another process is named "$APPNAME:another_process".
                if (cmdline[i] == ':')
                {
                    cmdline[i] = '\0';
                    break;
                }
            }

            // checking sizes.
            size_t srcLen = strnlen( cmdline, defaultBuffSize );
            size_t dstLen = strnlen( cmdlineoutput, defaultBuffSize );
            size_t maxCopyLen = defaultBuffSize - 1 - dstLen;
            size_t copyLen = srcLen < maxCopyLen ? srcLen : maxCopyLen;

            // using safe macro.
            STRCPY(cmdlineoutput, copyLen, cmdline);
            char* pch = strrchr(cmdlineoutput, '/');
            unsigned int i = 0;
            if (pch != NULL)
            {
                pch++; //remove last occurrence of '/'
                for (; i < defaultBuffSize - (pch - cmdlineoutput) && pch[i] != '\0'; i++)
                {
                    cmdlineoutput[i] = pch[i];
                }
            }
            cmdlineoutput[i] = '\0';
        }

        size_t pathLen = strnlen(outputDirectoryCopy, bufSize);
        if (pathLen < bufSize)
        {
            //check latest mark and add pid number before backslash
            if (pathLen > 1 && outputDirectoryCopy[pathLen - 1] != '/')
            {
                outputDirectoryCopy[pathLen] = '/';
                pathLen++;
            }

            if (pidEnabled)
            {
                snprintf(outputDirectoryCopy + pathLen, bufSize - pathLen, "%s_%u/", cmdlineoutput, pid);
            }
            else
            {
                snprintf(outputDirectoryCopy + pathLen, bufSize - pathLen, "%s/", cmdlineoutput);
            }
        }
    }

    struct stat statbuf;
    unsigned int i = 0;

    while (i < bufSize - 1)
    {
        if ((outputDirectoryCopy[i] == '/' && i != 0 ) || outputDirectoryCopy[i] == '\0')
        {
            path[i] = '\0';
            if (stat(path, &statbuf) != 0) //direcory doesn't exist
            {
                //create dir
                if (mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0)
                {
                    pathBuf[0] = '\0';
                    free(path);
                    return ret;
                }
            }
            else
            {
                if (!S_ISDIR(statbuf.st_mode)) //not dir
                {
                    pathBuf[0]= '\0';
                    free(path);
                    return ret;
                }
            }
            if (outputDirectoryCopy[i] == '\0')
            {
                break;
            }
        }
        path[i] = outputDirectoryCopy[i];
        i++;
    }

    if (i < bufSize-1) //fails if outputDirectory is longer than the bufSize
    {
        unsigned int length = (unsigned int)strlen(path);
        length = (bufSize-1 < length) ? bufSize-1 : length;
        memcpy(pathBuf, path, length);
        pathBuf[length] = 0;
    } else {
        pathBuf[0] = '\0';
    }

    free(path);
#endif //#elif !defined(_WIN32)
    return ret;
}


/*****************************************************************************\
Inline Function:
    CreateAppOutputDir

Description:
    Creates folder path based on outputDirectory string.
    Then writes it in pathBuf.

Input:
    unsigned int    bufSize
    const char*     outputDirectory

Output:
    char*           pathBuf
    int             ret         - return value: 0 - success, -1 - fail

\*****************************************************************************/
inline int CreateAppOutputDir(
    char*           pathBuf,
    unsigned int    bufSize,
    const char*     outputDirectory )
{
    int ret = CreateAppOutputDir( pathBuf, bufSize, outputDirectory, true, true, false );

    return ret;
}


/*****************************************************************************\
Inline Function:
    ParentDirectoryCreate

Description:
    Creates a directory to hold the given file
\*****************************************************************************/
inline int ParentDirectoryCreate(const char * filePath)
{
#if defined _WIN32 || _WIN64
#else
#include <limits.h>
#ifndef MAX_PATH
#define MAX_PATH PATH_MAX
#endif
#endif
    char pathBuf[MAX_PATH];
    char parentBuf[MAX_PATH];

#if defined _WIN32 || _WIN64
    char drive[MAX_PATH];
    char directory[MAX_PATH];

    if (_splitpath_s(
        filePath,
        drive,
        sizeof(drive),
        directory,
        sizeof(directory),
        NULL,
        0,
        NULL,
        0) != 0)
    {
        return -1;
    }

    _makepath(parentBuf, drive, directory, NULL, NULL);
#else
    // dirname may alter its parameter, so copy it to a buffer first.
    STRCPY(pathBuf, MAX_PATH, filePath);
    STRCPY(parentBuf, MAX_PATH, dirname(pathBuf));
#endif

return CreateAppOutputDir(pathBuf, sizeof(pathBuf), parentBuf, false, false, false);

}


} // iSTD

#if defined _WIN32
#   pragma warning(pop)
#endif