forked from modelica/ModelicaStandardLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModelicaInternal.c
1372 lines (1238 loc) · 44.1 KB
/
ModelicaInternal.c
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ModelicaInternal.c - External functions for Modelica.Utilities
Copyright (C) 2002-2020, Modelica Association and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder nor the names of its
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 HOLDER 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.
*/
/* Changelog:
Nov. 17, 2020: by Thomas Beutlich
Fixed reading files with Unix-style line endings on Windows
for ModelicaInternal_readLine/_readFile (ticket #3631)
Nov. 11, 2020: by Thomas Beutlich
Added getcwd fallback in ModelicaInternal_fullPathName if
realpath fails for non-existing path (ticket #3660)
Nov. 13, 2019: by Thomas Beutlich
Utilized blockwise I/O in ModelicaInternal_copyFile
(ticket #3229)
Oct. 10, 2019: by Thomas Beutlich
Fixed month and year correction in ModelicaInternal_getTime
(ticket #3143)
Jun. 24, 2019: by Thomas Beutlich
Fixed uninitialized memory and realpath behaviour in
ModelicaInternal_fullPathName (ticket #3003)
Jun. 28, 2018: by Hans Olsson, Dassault Systemes
Proper error message when out of string memory
in ModelicaInternal_readLine (ticket #2676)
Oct. 23, 2017: by Thomas Beutlich, ESI ITI GmbH
Utilized non-fatal hash insertion, called by HASH_ADD_KEYPTR in
function CacheFileForReading (ticket #2097)
Apr. 09, 2017: by Thomas Beutlich, ESI ITI GmbH
Fixed macOS support of ModelicaInternal_setenv
(ticket #2235)
Mar. 27, 2017: by Thomas Beutlich, ESI ITI GmbH
Replaced localtime by re-entrant function
Jan. 31, 2017: by Thomas Beutlich, ESI ITI GmbH
Fixed WIN32 support of a directory name with a trailing
forward/backward slash character in ModelicaInternal_stat
(ticket #1976)
Mar. 02, 2016: by Thomas Beutlich, ITI GmbH
Fixed repeated opening of cached file in case of line miss in
ModelicaStreams_openFileForReading (ticket #1939)
Dec. 10, 2015: by Martin Otter, DLR
Added flags NO_PID and NO_TIME (ticket #1805)
Oct. 27, 2015: by Thomas Beutlich, ITI GmbH
Added nonnull attributes/annotations (ticket #1436)
Oct. 05, 2015: by Thomas Beutlich, ITI GmbH
Added functions ModelicaInternal_getpid/_getTime from
ModelicaRandom.c of https://github.com/DLR-SR/Noise
(ticket #1662)
Nov. 20, 2014: by Thomas Beutlich, ITI GmbH
Fixed platform dependency of ModelicaInternal_readLine/_readFile
(ticket #1580)
Aug. 22, 2014: by Thomas Beutlich, ITI GmbH
Fixed multi-threaded access of common/shared file cache
(ticket #1556)
Aug. 11, 2014: by Thomas Beutlich, ITI GmbH
Increased cache size of opened files and made it
thread-safe (ticket #1433)
Made getenv/putenv thread-safe for Visual Studio 2005 and
later (ticket #1433)
May 21, 2013: by Martin Otter, DLR
Included the improvements from DS Lund (ticket #1104):
- Changed implementation of print to do nothing in case of
missing file-system. Otherwise we just end up with an
error message that is not written, and the failure in
itself is not sufficiently fatal to just stop.
- Caching when reading from file
Mar, 26, 2013: by Martin Otter, DLR
Changed type of variable valueStart from int to size_t
(ticket #1032)
Jan. 05, 2013: by Martin Otter, DLR
Removed "static" declarations from the Modelica interface
functions
Sep. 26, 2004: by Martin Otter, DLR
Added missing implementations, merged code from previous
ModelicaFiles and clean-up of code
Sep. 09, 2004: by Dag Brueck, Dynasim AB
Further implementation and clean-up of code
Aug. 24, 2004: by Martin Otter, DLR
Adapted to Dymola 5.3 with minor improvements
Jan. 07, 2002: by Martin Otter, DLR
First version implemented:
Only tested for _WIN32, but implemented all
functions also for _POSIX_, with the exception of
ModelicaInternal_getFullPath
*/
#include "ModelicaInternal.h"
#include "ModelicaUtilities.h"
MODELICA_NORETURN static void ModelicaNotExistError(const char* name) MODELICA_NORETURNATTR;
static void ModelicaNotExistError(const char* name) {
/* Print error message if a function is not implemented */
ModelicaFormatError("C-Function \"%s\" is called\n"
"but is not implemented for the actual environment\n"
"(e.g., because there is no file system available on the machine\n"
"as for dSPACE or xPC systems)", name);
}
#ifdef NO_FILE_SYSTEM
void ModelicaInternal_mkdir(_In_z_ const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_mkdir"); }
void ModelicaInternal_rmdir(_In_z_ const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_rmdir"); }
int ModelicaInternal_stat(_In_z_ const char* name) {
ModelicaNotExistError("ModelicaInternal_stat"); return 0; }
void ModelicaInternal_rename(_In_z_ const char* oldName,
_In_z_ const char* newName) {
ModelicaNotExistError("ModelicaInternal_rename"); }
void ModelicaInternal_removeFile(_In_z_ const char* file) {
ModelicaNotExistError("ModelicaInternal_removeFile"); }
void ModelicaInternal_copyFile(_In_z_ const char* oldFile,
_In_z_ const char* newFile) {
ModelicaNotExistError("ModelicaInternal_copyFile"); }
void ModelicaInternal_readDirectory(_In_z_ const char* directory,
int nFiles, _Out_ const char** files) {
ModelicaNotExistError("ModelicaInternal_readDirectory"); }
int ModelicaInternal_getNumberOfFiles(_In_z_ const char* directory) {
ModelicaNotExistError("ModelicaInternal_getNumberOfFiles"); return 0; }
const char* ModelicaInternal_fullPathName(_In_z_ const char* name) {
ModelicaNotExistError("ModelicaInternal_fullPathName"); return NULL; }
const char* ModelicaInternal_temporaryFileName(void) {
ModelicaNotExistError("ModelicaInternal_temporaryFileName"); return NULL; }
void ModelicaStreams_closeFile(_In_z_ const char* fileName) {
ModelicaNotExistError("ModelicaStreams_closeFile"); }
void ModelicaInternal_print(_In_z_ const char* string,
_In_z_ const char* fileName) {
if ( fileName[0] == '\0' ) {
/* Write string to terminal */
ModelicaFormatMessage("%s\n", string);
}
return; }
int ModelicaInternal_countLines(_In_z_ const char* fileName) {
ModelicaNotExistError("ModelicaInternal_countLines"); return 0; }
void ModelicaInternal_readFile(_In_z_ const char* fileName,
_Out_ const char** string, size_t nLines) {
ModelicaNotExistError("ModelicaInternal_readFile"); }
const char* ModelicaInternal_readLine(_In_z_ const char* fileName,
int lineNumber, _Out_ int* endOfFile) {
ModelicaNotExistError("ModelicaInternal_readLine"); return NULL; }
void ModelicaInternal_chdir(_In_z_ const char* directoryName) {
ModelicaNotExistError("ModelicaInternal_chdir"); }
const char* ModelicaInternal_getcwd(int dummy) {
ModelicaNotExistError("ModelicaInternal_getcwd"); return NULL; }
void ModelicaInternal_getenv(_In_z_ const char* name, int convertToSlash,
_Out_ const char** content, _Out_ int* exist) {
ModelicaNotExistError("ModelicaInternal_getenv"); }
void ModelicaInternal_setenv(_In_z_ const char* name,
_In_z_ const char* value, int convertFromSlash) {
ModelicaNotExistError("ModelicaInternal_setenv"); }
#else
/* The standard way to detect POSIX is to check _POSIX_VERSION,
* which is defined in <unistd.h>
*/
#if defined(__unix__) || defined(__linux__) || defined(__APPLE_CC__)
#include <unistd.h>
#endif
#if !defined(_POSIX_) && defined(_POSIX_VERSION)
#define _POSIX_ 1
#endif
#define HASH_NONFATAL_OOM 1
#include "uthash.h"
#include "gconstructor.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#if defined(__WATCOMC__)
#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>
#elif defined(__BORLANDC__)
#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#elif defined(_WIN32)
#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(__MINGW32__) || defined(__CYGWIN__) /* MinGW and Cygwin have dirent.h */
#include <dirent.h>
#else /* include the opendir/readdir/closedir interface for _WIN32 */
#include "win32_dirent.h"
#endif
#elif defined(_POSIX_) || defined(__GNUC__)
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif
#if PATH_MAX > 1024
#define BUFFER_LENGTH PATH_MAX
#else
#define BUFFER_LENGTH 1024
#endif
typedef enum {
FileType_NoFile = 1,
FileType_RegularFile,
FileType_Directory,
FileType_SpecialFile /* pipe, FIFO, device, etc. */
} ModelicaFileType;
/* Convert to Unix directory separators: */
#if defined(_WIN32)
static void ModelicaConvertToUnixDirectorySeparator(char* string) {
/* Convert to Unix directory separators */
char* c = string;
while ( *c ) {
if ( *c == '\\' ) {
*c = '/';
}
c++;
}
}
static void ModelicaConvertFromUnixDirectorySeparator(char* string) {
/* Convert from Unix directory separators */
char* c = string;
while ( *c ) {
if ( *c == '/' ) {
*c = '\\';
}
c++;
}
}
#else
#define ModelicaConvertToUnixDirectorySeparator(string) ;
#define ModelicaConvertFromUnixDirectorySeparator(string) ;
#endif
static int readLine(_In_ char** buf, _In_ int* bufLen, _In_ FILE* fp) MODELICA_NONNULLATTR;
/* Read line (of unknown and arbitrary length) from a text file */
/* --------------------- Modelica_Utilities.Internal --------------------------------- */
void ModelicaInternal_mkdir(_In_z_ const char* directoryName) {
/* Create directory */
#if defined(__WATCOMC__) || defined(__LCC__)
int result = mkdir(directoryName);
#elif defined(__BORLANDC__) || defined(_WIN32)
int result = _mkdir(directoryName);
#elif defined(_POSIX_) || defined(__GNUC__)
int result = mkdir(directoryName, S_IRUSR | S_IWUSR | S_IXUSR);
#else
ModelicaNotExistError("ModelicaInternal_mkdir");
#endif
#if defined(__WATCOMC__) || defined(__LCC__) || defined(__BORLANDC__) || defined(_WIN32) || defined(_POSIX_) || defined(__GNUC__)
if (result != 0) {
ModelicaFormatError("Not possible to create new directory\n"
"\"%s\":\n%s", directoryName, strerror(errno));
}
#endif
}
void ModelicaInternal_rmdir(_In_z_ const char* directoryName) {
/* Remove directory */
#if defined(__WATCOMC__) || defined(__LCC__) || defined(_POSIX_) || defined(__GNUC__)
int result = rmdir(directoryName);
#elif defined(__BORLANDC__) || defined(_WIN32)
int result = _rmdir(directoryName);
#else
ModelicaNotExistError("ModelicaInternal_rmdir");
#endif
#if defined(__WATCOMC__) || defined(__LCC__) || defined(__BORLANDC__) || defined(_WIN32) || defined(_POSIX_) || defined(__GNUC__)
if (result != 0) {
ModelicaFormatError("Not possible to remove directory\n"
"\"%s\":\n%s", directoryName, strerror(errno));
}
#endif
}
static ModelicaFileType Internal_stat(_In_z_ const char* name) {
/* Inquire type of file */
ModelicaFileType type;
#if defined(_WIN32)
struct _stat fileInfo;
int statReturn = _stat(name, &fileInfo);
if (0 != statReturn) {
/* For some reason _stat requires "a:\" and "a:\test1" but fails
* on "a:" and "a:\test1\", respectively. It could be handled in the
* Modelica code, but seems better to have it here.
*/
const char* firstSlash = strpbrk(name, "/\\");
const char* firstColon = strchr(name, ':');
const char c = (NULL != firstColon) ? firstColon[1] : '\0';
size_t len = strlen(name);
if (NULL == firstSlash && NULL != firstColon && '\0' == c) {
char* nameTmp = (char*)malloc((len + 2)*(sizeof(char)));
if (NULL != nameTmp) {
strcpy(nameTmp, name);
strcat(nameTmp, "\\");
statReturn = _stat(nameTmp, &fileInfo);
free(nameTmp);
}
}
else if (NULL != firstSlash && len > 1 &&
('/' == name[len - 1] || '\\' == name[len - 1])) {
char* nameTmp = (char*)malloc(len*(sizeof(char)));
if (NULL != nameTmp) {
strncpy(nameTmp, name, len - 1);
nameTmp[len - 1] = '\0';
statReturn = _stat(nameTmp, &fileInfo);
free(nameTmp);
}
}
}
if ( statReturn != 0 ) {
type = FileType_NoFile;
}
else if ( fileInfo.st_mode & S_IFREG ) {
type = FileType_RegularFile;
}
else if ( fileInfo.st_mode & S_IFDIR ) {
type = FileType_Directory;
}
else {
type = FileType_SpecialFile;
}
#elif defined(_POSIX_) || defined(__GNUC__)
struct stat fileInfo;
int statReturn;
statReturn = stat(name, &fileInfo);
if ( statReturn != 0 ) {
type = FileType_NoFile;
}
else if ( S_ISREG(fileInfo.st_mode) ) {
type = FileType_RegularFile;
}
else if ( S_ISDIR(fileInfo.st_mode) ) {
type = FileType_Directory;
}
else {
type = FileType_SpecialFile;
}
#else
type = FileType_NoFile;
#endif
return type;
}
int ModelicaInternal_stat(_In_z_ const char* name) {
#if defined(_WIN32) || defined(_POSIX_) || defined(__GNUC__)
ModelicaFileType type = Internal_stat(name);
#else
ModelicaFileType type = FileType_NoFile;
ModelicaNotExistError("ModelicaInternal_stat");
#endif
return type;
}
void ModelicaInternal_rename(_In_z_ const char* oldName,
_In_z_ const char* newName) {
/* Change the name of a file or of a directory */
if ( rename(oldName, newName) != 0 ) {
ModelicaFormatError("renaming \"%s\" to \"%s\" failed:\n%s",
oldName, newName, strerror(errno));
}
}
void ModelicaInternal_removeFile(_In_z_ const char* file) {
/* Remove file */
if ( remove(file) != 0 ) {
ModelicaFormatError("Not possible to remove file \"%s\":\n%s",
file, strerror(errno));
}
}
void ModelicaInternal_copyFile(_In_z_ const char* oldFile,
_In_z_ const char* newFile) {
/* Copy file */
const char* modeOld = "rb";
const char* modeNew = "wb";
FILE* fpOld;
FILE* fpNew;
ModelicaFileType type;
/* Check file existence */
type = Internal_stat(oldFile);
if ( type == FileType_NoFile ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause it does not exist", oldFile);
return;
}
else if ( type == FileType_Directory ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause it is a directory", oldFile);
return;
}
else if ( type == FileType_SpecialFile ) {
ModelicaFormatError("\"%s\" cannot be copied\n"
"because it is not a regular file", oldFile);
return;
}
type = Internal_stat(newFile);
if ( type != FileType_NoFile ) {
ModelicaFormatError("\"%s\" cannot be copied\nbecause the target "
"\"%s\" exists", oldFile, newFile);
return;
}
/* Copy file */
fpOld = fopen(oldFile, modeOld);
if ( fpOld == NULL ) {
ModelicaFormatError("\"%s\" cannot be copied:\n%s", oldFile, strerror(errno));
return;
}
fpNew = fopen(newFile, modeNew);
if ( fpNew == NULL ) {
fclose(fpOld);
ModelicaFormatError("\"%s\" cannot be copied to \"%s\":\n%s",
oldFile, newFile, strerror(errno));
return;
}
{
size_t len;
char buf[BUFSIZ] = {'\0'};
while ( (len = fread(buf, sizeof(char), BUFSIZ, fpOld)) > 0 ) {
if ( len != fwrite(buf, sizeof(char), len, fpNew) ) {
fclose(fpOld);
fclose(fpNew);
ModelicaFormatError("Error writing to file \"%s\".", newFile);
return;
}
}
}
fclose(fpOld);
fclose(fpNew);
}
void ModelicaInternal_readDirectory(_In_z_ const char* directory, int nFiles,
_Out_ const char** files) {
/* Get all file and directory names in a directory in any order
(must be very careful, to call closedir if an error occurs)
*/
#if defined(__WATCOMC__) || defined(__BORLANDC__) || defined(_WIN32) || defined(_POSIX_) || defined(__GNUC__)
int errnoTemp;
int iFiles = 0;
char *pName;
struct dirent *pinfo;
DIR* pdir;
/* Open directory information inquiry */
pdir = opendir(directory);
if ( pdir == NULL ) {
ModelicaFormatError("1: Not possible to get file names of \"%s\":\n%s",
directory, strerror(errno));
}
/* Read file and directory names and store them in vector "files" */
errno = 0;
while ( (pinfo = readdir(pdir)) != NULL ) {
if ( (strcmp(pinfo->d_name, "." ) != 0) &&
(strcmp(pinfo->d_name, "..") != 0) ) {
/* Check if enough space in "files" vector */
if ( iFiles >= nFiles ) {
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"More files in this directory as reported by nFiles (= %i)",
directory, nFiles);
}
/* Allocate Modelica memory for file/directory name and copy name */
pName = ModelicaDuplicateStringWithErrorReturn(pinfo->d_name);
if ( pName == NULL ) {
errnoTemp = errno;
closedir(pdir);
if ( errnoTemp == 0 ) {
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"Not enough storage", directory);
}
else {
ModelicaFormatError("Not possible to get file names of \"%s\":\n%s",
directory, strerror(errnoTemp));
}
}
/* Save pointer to file */
files[iFiles] = pName;
iFiles++;
}
}
if ( errno != 0 ) {
errnoTemp = errno;
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n%s",
directory, strerror(errnoTemp));
}
/* Check, whether the whole "files" vector is filled and close inquiry */
if ( iFiles != nFiles) {
closedir(pdir);
ModelicaFormatError("Not possible to get file names of \"%s\":\n"
"Less files (= %d) found as defined by argument nNames (= %d)",
directory, iFiles, nFiles);
}
else if ( closedir(pdir) != 0 ) {
ModelicaFormatError("Not possible to get file names of \"%s\":\n%s",
directory, strerror(errno));
}
#else
ModelicaNotExistError("ModelicaInternal_readDirectory");
#endif
}
int ModelicaInternal_getNumberOfFiles(_In_z_ const char* directory) {
/* Get number of files and directories in a directory */
#if defined(__WATCOMC__) || defined(__BORLANDC__) || defined(_WIN32) || defined(_POSIX_) || defined(__GNUC__)
int nFiles = 0;
int errnoTemp;
struct dirent *pinfo;
DIR* pdir;
pdir = opendir(directory);
if ( pdir == NULL ) {
goto Modelica_ERROR;
}
errno = 0;
while ( (pinfo = readdir(pdir)) != NULL ) {
if ( (strcmp(pinfo->d_name, "." ) != 0) &&
(strcmp(pinfo->d_name, "..") != 0) ) {
nFiles++;
}
}
errnoTemp = errno;
closedir(pdir);
if ( errnoTemp != 0 ) {
errno = errnoTemp;
goto Modelica_ERROR;
}
return nFiles;
Modelica_ERROR:
ModelicaFormatError("Not possible to get number of files in \"%s\":\n%s",
directory, strerror(errno));
return 0;
#else
ModelicaNotExistError("ModelicaInternal_getNumberOfFiles");
return 0;
#endif
}
/* --------------------- Modelica_Utilities.Files ------------------------------------- */
_Ret_z_ const char* ModelicaInternal_fullPathName(_In_z_ const char* name) {
/* Get full path name of file or directory */
#if defined(_WIN32)
char* fullName;
char localbuf[BUFFER_LENGTH];
char* tempName = _fullpath(localbuf, name, sizeof(localbuf));
if (tempName == NULL) {
ModelicaFormatError("Not possible to construct full path name of \"%s\"\n%s",
name, strerror(errno));
return "";
}
fullName = ModelicaDuplicateString(tempName);
ModelicaConvertToUnixDirectorySeparator(fullName);
return fullName;
#elif (_BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || _POSIX_VERSION >= 200112L)
char* fullName;
char localbuf[BUFFER_LENGTH];
size_t len;
/* realpath availability: 4.4BSD, POSIX.1-2001. Using the behaviour of NULL: POSIX.1-2008 */
char* tempName = realpath(name, localbuf);
if (tempName == NULL) {
goto FALLBACK_getcwd;
}
fullName = ModelicaAllocateString(strlen(tempName) + 1);
strcpy(fullName, tempName);
ModelicaConvertToUnixDirectorySeparator(fullName);
/* Retain trailing slash to match _fullpath behaviour */
len = strlen(name);
if (len > 0 && '/' == name[len - 1]) {
strcat(fullName, "/");
}
return fullName;
#elif defined(_POSIX_)
char* fullName;
char localbuf[BUFFER_LENGTH];
#else
char* fullName = "";
ModelicaNotExistError("ModelicaInternal_fullPathName");
return fullName;
#endif
#if (_BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || _POSIX_VERSION >= 200112L)
FALLBACK_getcwd:
#endif
#if (_BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || _POSIX_VERSION >= 200112L || _POSIX_)
{
/* No such system call in _POSIX_ available (except realpath for existing paths) */
char* cwd = getcwd(localbuf, sizeof(localbuf));
if (cwd == NULL) {
ModelicaFormatError("Not possible to get current working directory:\n%s",
strerror(errno));
}
fullName = ModelicaAllocateString(strlen(cwd) + strlen(name) + 1);
if (name[0] != '/') {
/* Any name beginning with "/" is regarded as already being a full path. */
strcpy(fullName, cwd);
strcat(fullName, "/");
}
else {
fullName[0] = '\0';
}
strcat(fullName, name);
}
return fullName;
#endif
}
_Ret_z_ const char* ModelicaInternal_temporaryFileName(void) {
/* Get full path name of a temporary file name which does not exist */
char* fullName;
char* tempName = tmpnam(NULL);
if (tempName == NULL) {
ModelicaFormatError("Not possible to get temporary filename\n%s", strerror(errno));
return "";
}
fullName = ModelicaDuplicateString(tempName);
ModelicaConvertToUnixDirectorySeparator(fullName);
return fullName;
}
/* --------------------- Abstract data type for stream handles --------------------- */
/* Improved for caching of the open files */
typedef struct FileCache {
char* fileName; /* Key = File name */
FILE* fp /* File pointer */;
char* buf;
int bufLen;
int lineNumber;
UT_hash_handle hh; /* Hashable structure */
} FileCache;
static FileCache* fileCache = NULL;
#if defined(_POSIX_) && !defined(NO_MUTEX)
#include <pthread.h>
#if defined(G_HAS_CONSTRUCTORS)
static pthread_mutex_t m;
G_DEFINE_CONSTRUCTOR(initializeMutex)
static void initializeMutex(void) {
if (pthread_mutex_init(&m, NULL) != 0) {
ModelicaError("Initialization of mutex failed\n");
}
}
G_DEFINE_DESTRUCTOR(destroyMutex)
static void destroyMutex(void) {
if (pthread_mutex_destroy(&m) != 0) {
ModelicaError("Destruction of mutex failed\n");
}
}
#else
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
#endif
#define MUTEX_LOCK() pthread_mutex_lock(&m)
#define MUTEX_UNLOCK() pthread_mutex_unlock(&m)
#elif defined(_WIN32) && defined(G_HAS_CONSTRUCTORS)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
static CRITICAL_SECTION cs;
#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(ModelicaInternal_initializeCS)
#endif
G_DEFINE_CONSTRUCTOR(ModelicaInternal_initializeCS)
static void ModelicaInternal_initializeCS(void) {
InitializeCriticalSection(&cs);
}
#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(ModelicaInternal_deleteCS)
#endif
G_DEFINE_DESTRUCTOR(ModelicaInternal_deleteCS)
static void ModelicaInternal_deleteCS(void) {
DeleteCriticalSection(&cs);
}
#define MUTEX_LOCK() EnterCriticalSection(&cs)
#define MUTEX_UNLOCK() LeaveCriticalSection(&cs)
#else
#define MUTEX_LOCK()
#define MUTEX_UNLOCK()
#endif
#if !defined(LINE_BUFFER_LENGTH)
#define LINE_BUFFER_LENGTH (64)
#endif
static void CacheFileForReading(FILE* fp, const char* fileName, int lineNumber, char* buf, int bufLen) {
FileCache* fv;
size_t len;
if (fileName == NULL) {
/* Do not add, close file */
if (fp != NULL) {
fclose(fp);
}
return;
}
len = strlen(fileName);
MUTEX_LOCK();
HASH_FIND(hh, fileCache, fileName, (unsigned)len, fv);
if (fv != NULL) {
fv->fp = fp;
fv->lineNumber = lineNumber;
fv->buf = buf;
fv->bufLen = bufLen;
}
else {
fv = (FileCache*)malloc(sizeof(FileCache));
if (fv != NULL) {
char* key = (char*)malloc((len + 1)*sizeof(char));
if (key != NULL) {
strcpy(key, fileName);
fv->fileName = key;
fv->fp = fp;
fv->lineNumber = lineNumber;
fv->buf = buf;
fv->bufLen = bufLen;
HASH_ADD_KEYPTR(hh, fileCache, key, (unsigned)len, fv);
if (NULL == fv->hh.tbl) {
free(key);
free(fv);
}
}
else {
free(fv);
}
}
}
MUTEX_UNLOCK();
}
static void CloseCachedFile(const char* fileName) {
FileCache* fv;
size_t len = strlen(fileName);
MUTEX_LOCK();
HASH_FIND(hh, fileCache, fileName, (unsigned)len, fv);
if (fv != NULL) {
if (fv->fp != NULL) {
fclose(fv->fp);
}
free(fv->buf);
free(fv->fileName);
HASH_DEL(fileCache, fv);
free(fv);
}
MUTEX_UNLOCK();
}
static FILE* ModelicaStreams_openFileForReading(const char* fileName, int lineNumber, int* lineNumberOffset, char** buf, int* bufLen) {
/* Open text file for reading */
FILE* fp;
int c = 1;
FileCache* fv;
size_t len = strlen(fileName);
*lineNumberOffset = 0;
*buf = NULL;
*bufLen = LINE_BUFFER_LENGTH;
MUTEX_LOCK();
HASH_FIND(hh, fileCache, fileName, (unsigned)len, fv);
/* Open file */
if (fv != NULL) {
/* Cached value */
if (fv->fp != NULL) {
if (lineNumber != 0 && lineNumber >= fv->lineNumber - 1) {
*lineNumberOffset = fv->lineNumber;
fp = fv->fp;
*buf = fv->buf;
*bufLen = fv->bufLen;
}
else {
if ( fseek(fv->fp, 0L, SEEK_SET) == 0 ) {
fp = fv->fp;
*buf = fv->buf;
*bufLen = fv->bufLen;
}
else {
fclose(fv->fp);
fp = NULL;
free(fv->buf);
}
}
fv->fp = NULL;
fv->buf = NULL;
}
else {
fp = NULL;
}
}
else {
fp = NULL;
}
MUTEX_UNLOCK();
if (fp == NULL) {
fp = fopen(fileName, "r");
if ( fp == NULL ) {
ModelicaFormatError("Not possible to open file \"%s\" for reading:\n"
"%s\n", fileName, strerror(errno));
}
}
return fp;
}
void ModelicaStreams_closeFile(_In_z_ const char* fileName) {
/* Close file */
CloseCachedFile(fileName); /* Closes it */
}
static FILE* ModelicaStreams_openFileForWriting(const char* fileName) {
/* Open text file for writing (with append) */
FILE* fp;
/* Check fileName */
if ( fileName[0] == '\0' ) {
ModelicaError("fileName is an empty string.\n"
"Opening of file is aborted\n");
}
/* Open file */
ModelicaStreams_closeFile(fileName);
fp = fopen(fileName, "a");
if ( fp == NULL ) {
ModelicaFormatError("Not possible to open file \"%s\" for writing:\n"
"%s\n", fileName, strerror(errno));
}
return fp;
}
static int readLine(_In_ char** buf, _In_ int* bufLen, _In_ FILE* fp) {
char* offset;
int oldBufLen;
if (fgets(*buf, *bufLen, fp) == NULL) {
return EOF;
}
do {
char* p;
char* tmp;
if ((p = strchr(*buf, '\n')) != NULL) {
*p = '\0';
return 0;
}
if ((p = memchr(*buf, 0, (size_t)(*bufLen - 1))) != NULL) {
return 1;
}
oldBufLen = *bufLen;
*bufLen *= 2;
tmp = (char*)realloc(*buf, (size_t)*bufLen);
if (NULL == tmp) {
fclose(fp);
free(*buf);
ModelicaError("Memory allocation error\n");
return 1;
}
*buf = tmp;
offset = &((*buf)[oldBufLen - 1]);
} while (fgets(offset, oldBufLen + 1, fp));
return 0;
}
/* --------------------- Modelica_Utilities.Streams ----------------------------------- */
void ModelicaInternal_print(_In_z_ const char* string,
_In_z_ const char* fileName) {
/* Write string to terminal or to file */
if ( fileName[0] == '\0' ) {
/* Write string to terminal */
ModelicaFormatMessage("%s\n", string);
}
else {
/* Write string to file */
FILE* fp = ModelicaStreams_openFileForWriting(fileName);
if ( fputs(string,fp) < 0 ) {
goto Modelica_ERROR2;
}
if ( fputs("\n",fp) < 0 ) {
goto Modelica_ERROR2;
}
fclose(fp);
return;
Modelica_ERROR2:
fclose(fp);
ModelicaFormatError("Error when writing string to file \"%s\":\n"
"%s\n", fileName, strerror(errno));
}
}
int ModelicaInternal_countLines(_In_z_ const char* fileName) {
/* Get number of lines of a file */
int lineNumberOffset;
int bufLen;
char* buf;
int c;
int nLines = 0;
int start_of_line = 1;
/* If true, next character starts a new line. */
FILE* fp = ModelicaStreams_openFileForReading(fileName, 0, &lineNumberOffset, &buf, &bufLen);
/* Count number of lines */
while ((c = fgetc(fp)) != EOF) {
if (start_of_line) {
nLines++;
start_of_line = 0;
}
if (c == '\n') {
start_of_line = 1;
}
}
fclose(fp);
return nLines;
}
void ModelicaInternal_readFile(_In_z_ const char* fileName,
_Out_ const char** string, size_t nLines) {
/* Read file into string vector string[nLines] */
int lineNumberOffset;
int bufLen;
char* buf;
FILE* fp = ModelicaStreams_openFileForReading(fileName, 0, &lineNumberOffset, &buf, &bufLen);
char* line;
size_t iLines = 1;
if (buf == NULL) {
buf = (char*)calloc(bufLen, sizeof(char));
if (buf == NULL) {
goto Modelica_OOM_ERROR1;
}
}
/* Read data from file */
while (iLines <= nLines) {
readLine(&buf, &bufLen, fp);