-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathncvalidator.c
2418 lines (2122 loc) · 80.7 KB
/
ncvalidator.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
/*
Wei-keng Liao's ([email protected])
netcdf-3 validator program
(https://github.com/Parallel-NetCDF/PnetCDF/blob/master/src/utils/ncvalidator/ncvalidator.c)
*/
/*
Copyright (c) 2003 Northwestern University and Argonne National Laboratory
All rights reserved.
Portions of this software were developed by the Unidata Program at the
University Corporation for Atmospheric Research.
Access and use of this software shall impose the following obligations and
understandings on the user. The user is granted the right, without any
fee or
cost, to use, copy, modify, alter, enhance and distribute this
software, and
any derivative works thereof, and its supporting documentation for any
purpose
whatsoever, provided that this entire notice appears in all copies of the
software, derivative works and supporting documentation. Further,
Northwestern
University and Argonne National Laboratory request that the user credit
Northwestern University and Argonne National Laboratory in any
publications
that result from the use of this software or in any product that
includes this
software. The names Northwestern University and Argonne National
Laboratory,
however, may not be used in any advertising or publicity to endorse or
promote
any products or commercial entity unless specific written permission is
obtained from Northwestern University and Argonne National Laboratory.
The user
also understands that Northwestern University and Argonne National
Laboratory
are not obligated to provide the user with any support, consulting,
training or
assistance of any kind with regard to the use, operation and
performance of
this software nor to provide the user with any updates, revisions, new
versions
or "bug fixes."
THIS SOFTWARE IS PROVIDED BY NORTHWESTERN UNIVERSITY AND ARGONNE NATIONAL
LABORATORY "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 NORTHWESTERN
UNIVERSITY
AND ARGONNE NATIONAL LABORATORY BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR
PERFORMANCE OF
THIS SOFTWARE.
*/
#include "config.h"
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h> /* open() */
#include <sys/stat.h> /* open() */
#include <fcntl.h> /* open() */
#include <string.h> /* strcpy(), strncpy() */
#include <inttypes.h> /* check for Endianness, uint32_t*/
#include <assert.h>
#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> /* read() getopt() */
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#if defined(_WIN32) && !defined(__MINGW32__)
#include <io.h>
#include "XGetopt.h"
#endif
#define X_ALIGN 4
#define X_INT_MAX 2147483647
#define X_UINT_MAX 4294967295U
#define X_INT64_MAX 9223372036854775807LL
#ifndef EXIT_FAILURE
#ifndef vms
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
#else
/* In OpenVMS, success is indicated by odd values and failure by even values. */
#define EXIT_SUCCESS 1
#define EXIT_FAILURE 0
#endif
#endif
static int verbose, trace;
static int repair;
static const char nada[4] = {0, 0, 0, 0};
#ifndef MAX
#define MAX(mm,nn) (((mm) > (nn)) ? (mm) : (nn))
#endif
#ifndef MIN
#define MIN(mm,nn) (((mm) < (nn)) ? (mm) : (nn))
#endif
/* useful for aligning memory */
#define _RNDUP(x, unit) ((((x) + (unit) - 1) / (unit)) * (unit))
#define ERR_ADDR (((size_t) gbp->pos - (size_t) gbp->base) + (size_t) gbp->offset - gbp->size)
#define IS_RECVAR(vp) ((vp)->shape != NULL ? (*(vp)->shape == NC_UNLIMITED) : 0 )
#ifdef PNETCDF_DEBUG
#define DEBUG_RETURN_ERROR(err) { \
if (verbose) printf("\t(Error %s at line %d in file %s)\n", \
#err,__LINE__,__FILE__); \
return err; \
}
#define DEBUG_ASSIGN_ERROR(status, err) { \
if (verbose) printf("\t(Error %s at line %d in file %s)\n", \
#err,__LINE__,__FILE__); \
status = err; \
}
#else
#define DEBUG_RETURN_ERROR(err) return err;
#define DEBUG_ASSIGN_ERROR(status, err) { status = err; }
#endif
#define NC_UNLIMITED 0L
#define NC_ARRAY_GROWBY 64
#define NC_MAX_INT 2147483647
#define NC_MAX_DIMS NC_MAX_INT
#define NC_MAX_ATTRS NC_MAX_INT
#define NC_MAX_VARS NC_MAX_INT
#define NC_MAX_VAR_DIMS NC_MAX_INT /* max per-variable dimensions */
#define NC_NAT 0 /**< Not A Type */
#define NC_BYTE 1 /**< signed 1 byte integer */
#define NC_CHAR 2 /**< ISO/ASCII character */
#define NC_SHORT 3 /**< signed 2 byte integer */
#define NC_INT 4 /**< signed 4 byte integer */
#define NC_LONG NC_INT
#define NC_FLOAT 5 /**< single precision floating point number */
#define NC_DOUBLE 6 /**< double precision floating point number */
#define NC_UBYTE 7 /**< unsigned 1 byte int */
#define NC_USHORT 8 /**< unsigned 2-byte int */
#define NC_UINT 9 /**< unsigned 4-byte int */
#define NC_INT64 10 /**< signed 8-byte int */
#define NC_UINT64 11 /**< unsigned 8-byte int */
typedef int nc_type;
#define MIN_NC_XSZ 32
#define NC_DEFAULT_CHUNKSIZE 1048576
typedef enum {
NC_INVALID = -1, /* invalid */
NC_UNSPECIFIED = 0, /* ABSENT */
NC_DIMENSION = 10, /* \x00 \x00 \x00 \x0A */
NC_VARIABLE = 11, /* \x00 \x00 \x00 \x0B */
NC_ATTRIBUTE = 12 /* \x00 \x00 \x00 \x0C */
} NC_tag;
typedef struct {
char *name;
size_t name_len;
long long size;
} NC_dim;
typedef struct NC_dimarray {
int ndefined; /* number of defined dimensions */
int unlimited_id; /* ID of unlimited dimension */
NC_dim **value;
} NC_dimarray;
typedef struct {
long long xsz; /* amount of space at xvalue (4-byte aligned) */
char *name; /* name of the attributes */
size_t name_len;
nc_type xtype; /* the discriminant */
long long nelems; /* number of attribute elements */
void *xvalue; /* the actual data, in external representation */
} NC_attr;
typedef struct NC_attrarray {
int ndefined; /* number of defined attributes */
NC_attr **value;
} NC_attrarray;
typedef struct {
int xsz; /* byte size of 1 array element */
long long *shape; /* dim->size of each dim */
long long *dsizes; /* the right to left product of shape */
char *name; /* name of the variable */
size_t name_len;
int ndims; /* number of dimensions */
int *dimids; /* array of dimension IDs */
NC_attrarray attrs; /* attribute array */
nc_type xtype; /* variable's data type */
long long len; /* this is the "vsize" defined in header format, the
total size in bytes of the array variable.
For record variable, this is the record size */
long long begin; /* starting file offset of this variable */
} NC_var;
typedef struct NC_vararray {
int ndefined; /* number of defined variables */
int num_rec_vars;/* number of defined record variables */
NC_var **value;
} NC_vararray;
typedef struct NC {
int format;
char *path;
long long xsz; /* external size of this header, <= var[0].begin */
long long begin_var;/* file offset of the first (non-record) var */
long long begin_rec;/* file offset of the first 'record' */
long long recsize; /* length of 'record': sum of single record sizes
of all the record variables */
long long numrecs; /* number of 'records' allocated */
NC_dimarray dims; /* dimensions defined */
NC_attrarray attrs; /* global attributes defined */
NC_vararray vars; /* variables defined */
} NC;
typedef struct bufferinfo {
int is_little_endian;
int fd;
off_t offset; /* current read/write offset in the file */
int version; /* 1, 2, and 5 for CDF-1, 2, and 5 respectively */
void *base; /* beginning of read/write buffer */
void *pos; /* current position in buffer */
size_t size; /* size of the buffer */
} bufferinfo;
#define NC_NOERR 0 /**< No Error */
#define NC_EMAXDIMS (-41) /**< NC_MAX_DIMS or NC_MAX_VAR_DIMS exceeds */
#define NC_EMAXATTS (-44) /**< NC_MAX_ATTRS exceeded */
#define NC_EBADTYPE (-45) /**< Not a netcdf data type */
#define NC_EBADDIM (-46) /**< Invalid dimension id or name */
#define NC_EUNLIMPOS (-47) /**< NC_UNLIMITED in the wrong index */
#define NC_EMAXVARS (-48)
#define NC_ENOTNC (-51) /**< Not a netcdf file (file format violates CDF specification) */
#define NC_EUNLIMIT (-54) /**< NC_UNLIMITED size already in use */
#define NC_ENOMEM (-61) /**< Memory allocation (malloc) failure */
#define NC_EVARSIZE (-62) /**< One or more variable sizes violate format constraints */
#define NC_EFILE (-204) /**< Unknown error in file operation */
#define NC_ENOTSUPPORT (-214) /**< Feature is not yet supported */
#define NC_ENULLPAD (-134) /**< Header Bytes not Null-Byte padded */
/*
* "magic number" at beginning of file: 0x43444601 (big Endian)
*/
static const char ncmagic[] = {'C', 'D', 'F', 0x01};
#define ABSENT 0
#define SWAP4B(a) ( ((a) << 24) | \
(((a) << 8) & 0x00ff0000) | \
(((a) >> 8) & 0x0000ff00) | \
(((a) >> 24) & 0x000000ff) )
#define SWAP8B(a) ( (((a) & 0x00000000000000FFULL) << 56) | \
(((a) & 0x000000000000FF00ULL) << 40) | \
(((a) & 0x0000000000FF0000ULL) << 24) | \
(((a) & 0x00000000FF000000ULL) << 8) | \
(((a) & 0x000000FF00000000ULL) >> 8) | \
(((a) & 0x0000FF0000000000ULL) >> 24) | \
(((a) & 0x00FF000000000000ULL) >> 40) | \
(((a) & 0xFF00000000000000ULL) >> 56) )
static int check_little_endian(void)
{
/* return 0 for big endian, 1 for little endian. */
volatile uint32_t i=0x01234567;
return (*((uint8_t*)(&i))) == 0x67;
}
static void
swap4b(void *val)
{
uint32_t *op = (uint32_t*)val;
*op = SWAP4B(*op);
}
static void
swap8b(unsigned long long *val)
{
uint64_t *op = (uint64_t*)val;
*op = SWAP8B(*op);
}
static unsigned long long
get_uint64(bufferinfo *gbp)
{
/* retrieve a 64bit unsigned integer and return it as unsigned long long */
unsigned long long tmp;
memcpy(&tmp, gbp->pos, 8);
if (gbp->is_little_endian) swap8b(&tmp);
gbp->pos = (char*)gbp->pos + 8; /* advance gbp->pos 8 bytes */
return tmp;
}
static unsigned int
get_uint32(bufferinfo *gbp)
{
/* retrieve a 32bit unsigned integer and return it as unsigned int */
unsigned int tmp;
memcpy(&tmp, gbp->pos, 4);
if (gbp->is_little_endian) swap4b(&tmp);
gbp->pos = (char*)gbp->pos + 4; /* advance gbp->pos 4 bytes */
return tmp;
}
static void
free_NC_dim(NC_dim *dimp)
{
if (dimp == NULL) return;
free(dimp->name);
free(dimp);
}
static void
free_NC_dimarray(NC_dimarray *ncap)
{
int i;
assert(ncap != NULL);
if (ncap->value == NULL) return;
for (i=0; i<ncap->ndefined; i++)
if (ncap->value[i] != NULL)
free_NC_dim(ncap->value[i]);
free(ncap->value);
ncap->value = NULL;
ncap->ndefined = 0;
}
static void
free_NC_attr(NC_attr *attrp)
{
if (attrp == NULL) return;
free(attrp->name);
if (attrp->xvalue != NULL) free(attrp->xvalue);
free(attrp);
}
static void
free_NC_attrarray(NC_attrarray *ncap)
{
int i;
assert(ncap != NULL);
if (ncap->value == NULL) return;
for (i=0; i<ncap->ndefined; i++)
free_NC_attr(ncap->value[i]);
free(ncap->value);
ncap->value = NULL;
ncap->ndefined = 0;
}
static void
free_NC_var(NC_var *varp)
{
if (varp == NULL) return;
free_NC_attrarray(&varp->attrs);
free(varp->name);
free(varp->shape);
free(varp->dsizes);
free(varp->dimids);
free(varp);
}
static void
free_NC_vararray(NC_vararray *ncap)
{
int i;
assert(ncap != NULL);
if (ncap->value == NULL) return;
for (i=0; i<ncap->ndefined; i++) {
if (ncap->value[i] != NULL)
free_NC_var(ncap->value[i]);
}
free(ncap->value);
ncap->value = NULL;
ncap->ndefined = 0;
}
/*
* To compute how much space will the xdr'd header take
*/
/*----< hdr_len_NC_name() >--------------------------------------------------*/
static long long
hdr_len_NC_name(size_t nchars,
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* name = nelems namestring
* nelems = NON_NEG
* namestring = ID1 [IDN ...] padding
* ID1 = alphanumeric | '_'
* IDN = alphanumeric | special1 | special2
* padding = <0, 1, 2, or 3 bytes to next 4-byte boundary>
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
long long sz = sizeof_t; /* nelems */
if (nchars != 0) /* namestring */
sz += _RNDUP((long long)nchars, X_ALIGN);
return sz;
}
/*----< hdr_len_NC_dim() >---------------------------------------------------*/
static long long
hdr_len_NC_dim(const NC_dim *dimp,
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* ...
* dim = name dim_length
* dim_length = NON_NEG
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
long long sz;
assert(dimp != NULL);
sz = hdr_len_NC_name(dimp->name_len, sizeof_t); /* name */
sz += sizeof_t; /* dim_length */
return sz;
}
/*----< hdr_len_NC_dimarray() >----------------------------------------------*/
static long long
hdr_len_NC_dimarray(const NC_dimarray *ncap,
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* ...
* dim_list = ABSENT | NC_DIMENSION nelems [dim ...]
* ABSENT = ZERO ZERO | // list is not present for CDF-1 and 2
* ZERO ZERO64 // for CDF-5
* ZERO = \x00 \x00 \x00 \x00 // 32-bit zero
* ZERO64 = \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 // 64-bit zero
* NC_DIMENSION = \x00 \x00 \x00 \x0A // tag for list of dimensions
* nelems = NON_NEG // number of elements in following sequence
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
int i;
long long xlen;
xlen = 4; /* NC_DIMENSION */
xlen += sizeof_t; /* nelems */
if (ncap == NULL) /* ABSENT: no dimension is defined */
return xlen;
/* [dim ...] */
for (i=0; i<ncap->ndefined; i++)
xlen += hdr_len_NC_dim(ncap->value[i], sizeof_t);
return xlen;
}
/*----< hdr_len_NC_attr() >--------------------------------------------------*/
static long long
hdr_len_NC_attr(const NC_attr *attrp,
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* ...
* attr = name nc_type nelems [values ...]
* nc_type = NC_BYTE | NC_CHAR | NC_SHORT | ...
* nelems = NON_NEG // number of elements in following sequence
* values = bytes | chars | shorts | ints | floats | doubles
* bytes = [BYTE ...] padding
* chars = [CHAR ...] padding
* shorts = [SHORT ...] padding
* ints = [INT ...]
* floats = [FLOAT ...]
* doubles = [DOUBLE ...]
* padding = <0, 1, 2, or 3 bytes to next 4-byte boundary>
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
long long sz;
assert(attrp != NULL);
sz = hdr_len_NC_name(attrp->name_len, sizeof_t); /* name */
sz += 4; /* nc_type */
sz += sizeof_t; /* nelems */
sz += attrp->xsz; /* [values ...] */
return sz;
}
/*----< hdr_len_NC_attrarray() >---------------------------------------------*/
static long long
hdr_len_NC_attrarray(const NC_attrarray *ncap,
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* ...
* att_list = ABSENT | NC_ATTRIBUTE nelems [attr ...]
* ABSENT = ZERO ZERO | // list is not present for CDF-1 and 2
* ZERO ZERO64 // for CDF-5
* ZERO = \x00 \x00 \x00 \x00 // 32-bit zero
* ZERO64 = \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 // 64-bit zero
* NC_ATTRIBUTE = \x00 \x00 \x00 \x0C // tag for list of attributes
* nelems = NON_NEG // number of elements in following sequence
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
int i;
long long xlen;
xlen = 4; /* NC_ATTRIBUTE */
xlen += sizeof_t; /* nelems */
if (ncap == NULL) /* ABSENT: no attribute is defined */
return xlen;
for (i=0; i<ncap->ndefined; i++) /* [attr ...] */
xlen += hdr_len_NC_attr(ncap->value[i], sizeof_t);
return xlen;
}
/*----< hdr_len_NC_var() >---------------------------------------------------*/
static long long
hdr_len_NC_var(const NC_var *varp,
int sizeof_off_t, /* OFFSET */
int sizeof_t) /* NON_NEG */
{
/* netCDF file format:
* netcdf_file = header data
* header = magic numrecs dim_list gatt_list var_list
* ...
* var = name nelems [dimid ...] vatt_list nc_type vsize begin
* nelems = NON_NEG
* dimid = NON_NEG
* vatt_list = att_list
* nc_type = NC_BYTE | NC_CHAR | NC_SHORT | ...
* vsize = NON_NEG
* begin = OFFSET // Variable start location.
* OFFSET = <non-negative INT> | // CDF-1
* <non-negative INT64> // CDF-2 and CDF-5
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
long long sz;
assert(varp != NULL);
/* for CDF-1, sizeof_off_t == 4 && sizeof_t == 4
* for CDF-2, sizeof_off_t == 8 && sizeof_t == 4
* for CDF-5, sizeof_off_t == 8 && sizeof_t == 8
*/
sz = hdr_len_NC_name(varp->name_len, sizeof_t); /* name */
sz += sizeof_t; /* nelems */
sz += ((long long)sizeof_t) * varp->ndims; /* [dimid ...] */
sz += hdr_len_NC_attrarray(&varp->attrs, sizeof_t); /* vatt_list */
sz += 4; /* nc_type */
sz += sizeof_t; /* vsize */
sz += sizeof_off_t; /* begin */
return sz;
}
/*----< hdr_len_NC_vararray() >----------------------------------------------*/
static long long
hdr_len_NC_vararray(const NC_vararray *ncap,
int sizeof_t, /* NON_NEG */
int sizeof_off_t) /* OFFSET */
{
/* netCDF file format:
* netcdf_file = header data
* header = magic numrecs dim_list gatt_list var_list
* ...
* var_list = ABSENT | NC_VARIABLE nelems [var ...]
* ABSENT = ZERO ZERO | // list is not present for CDF-1 and 2
* ZERO ZERO64 // for CDF-5
* ZERO = \x00 \x00 \x00 \x00 // 32-bit zero
* ZERO64 = \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 // 64-bit zero
* NC_VARIABLE = \x00 \x00 \x00 \x0B // tag for list of variables
* nelems = NON_NEG // number of elements in following sequence
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
int i;
long long xlen;
xlen = 4; /* NC_VARIABLE */
xlen += sizeof_t; /* nelems */
if (ncap == NULL) /* ABSENT: no variable is defined */
return xlen;
/* for CDF-1, sizeof_off_t == 4 && sizeof_t == 4
* for CDF-2, sizeof_off_t == 8 && sizeof_t == 4
* for CDF-5, sizeof_off_t == 8 && sizeof_t == 8
*/
for (i=0; i<ncap->ndefined; i++) /* [var ...] */
xlen += hdr_len_NC_var(ncap->value[i], sizeof_off_t, sizeof_t);
return xlen;
}
/*----< hdr_len_NC() >-------------------------------------------------------*/
static long long
hdr_len_NC(const NC *ncp)
{
/* netCDF file format:
* netcdf_file = header data
* header = magic numrecs dim_list gatt_list var_list
* ...
* numrecs = NON_NEG | STREAMING // length of record dimension
* NON_NEG = <non-negative INT> | // CDF-1 and CDF-2
* <non-negative INT64> // CDF-5
*/
int sizeof_t, sizeof_off_t;
long long xlen;
assert(ncp != NULL);
if (ncp->format == 5) { /* CDF-5 */
sizeof_t = 8; /* 8-byte integer for all integers */
sizeof_off_t = 8; /* 8-byte integer for var begin */
}
else if (ncp->format == 2) { /* CDF-2 */
sizeof_t = 4; /* 4-byte integer in CDF-1 */
sizeof_off_t = 8; /* 8-byte integer for var begin */
}
else { /* CDF-1 */
sizeof_t = 4; /* 4-byte integer in CDF-1 */
sizeof_off_t = 4; /* 4-byte integer in CDF-1 */
}
xlen = sizeof(ncmagic); /* magic */
xlen += sizeof_t; /* numrecs */
xlen += hdr_len_NC_dimarray(&ncp->dims, sizeof_t); /* dim_list */
xlen += hdr_len_NC_attrarray(&ncp->attrs, sizeof_t); /* gatt_list */
xlen += hdr_len_NC_vararray(&ncp->vars, sizeof_t, sizeof_off_t); /* var_list */
return xlen; /* return the header size (not yet aligned) */
}
/*----< ncmpio_xlen_nc_type() >----------------------------------------------*/
/* return the length of external NC data type */
static int
xlen_nc_type(nc_type xtype) {
switch(xtype) {
case NC_BYTE:
case NC_CHAR:
case NC_UBYTE: return 1;
case NC_SHORT:
case NC_USHORT: return 2;
case NC_INT:
case NC_UINT:
case NC_FLOAT: return 4;
case NC_DOUBLE:
case NC_INT64:
case NC_UINT64: return 8;
default: DEBUG_RETURN_ERROR(NC_EBADTYPE)
}
}
static NC_dim *
elem_NC_dimarray(const NC_dimarray *ncap,
int dimid)
{
/* returns the dimension ID defined earlier */
assert(ncap != NULL);
if (dimid < 0 || ncap->ndefined == 0 || dimid >= ncap->ndefined)
return NULL;
assert(ncap->value != NULL);
return ncap->value[dimid];
}
static int
var_shape64(NC_var *varp,
const NC_dimarray *dims,
const char *loc)
{
int i;
long long product = 1;
/* set the size of 1 element */
varp->xsz = xlen_nc_type(varp->xtype);
if (varp->ndims == 0) goto out;
/*
* use the user supplied dimension indices to determine the shape
*/
for (i=0; i<varp->ndims; i++) {
const NC_dim *dimp;
if (varp->dimids[i] < 0) {
if (verbose) printf("Error:\n");
if (verbose) printf("\t%s: dimension ID [%d] invalid (%d)\n",loc,i,varp->dimids[i]);
DEBUG_RETURN_ERROR(NC_EBADDIM);
}
if (varp->dimids[i] >= ((dims != NULL) ? dims->ndefined : 1)) {
if (verbose) printf("Error:\n");
if (verbose) printf("\t%s: dimension ID [%d] (%d) larger than defined (%d)\n",loc,i,varp->dimids[i], ((dims != NULL) ? dims->ndefined : 1));
DEBUG_RETURN_ERROR(NC_EBADDIM);
}
/* get the pointer to the dim object */
dimp = elem_NC_dimarray(dims, varp->dimids[i]);
varp->shape[i] = dimp->size;
/* check for record variable, only the highest dimension can
* be unlimited */
if (varp->shape[i] == NC_UNLIMITED && i != 0) {
if (verbose) printf("Error:\n");
if (verbose) printf("\t%s: dimension ID [%d] is NC_UNLIMITED in the wrong index\n",loc,i);
DEBUG_RETURN_ERROR(NC_EUNLIMPOS);
}
}
/*
* compute the dsizes, the right to left product of shape
*/
product = 1;
if (varp->ndims == 1) {
if (varp->shape[0] == NC_UNLIMITED)
varp->dsizes[0] = 1;
else {
varp->dsizes[0] = varp->shape[0];
product = varp->shape[0];
}
}
else { /* varp->ndims > 1 */
varp->dsizes[varp->ndims-1] = varp->shape[varp->ndims-1];
product = varp->shape[varp->ndims-1];
for (i=varp->ndims-2; i>=0; i--) {
if (varp->shape[i] != NC_UNLIMITED)
product *= varp->shape[i];
varp->dsizes[i] = product;
}
}
out :
/*
* For CDF-1 and CDF-2 formats, the total number of array elements
* cannot exceed 2^32, unless this variable is the last fixed-size
* variable, there is no record variable, and the file starting
* offset of this variable is less than 2GiB.
* We will check this in ncmpi_enddef() which calls ncmpii_NC_enddef()
* which calls ncmpii_NC_check_vlens()
if (ncp->format != 5 && product >= X_UINT_MAX)
DEBUG_RETURN_ERROR(NC_EVARSIZE);
*/
/*
* align variable size to 4 byte boundary, required by all netcdf file
* formats
*/
varp->len = product * varp->xsz;
if (varp->len % 4 > 0)
varp->len += 4 - varp->len % 4; /* round up */
return NC_NOERR;
}
/* calculate the following
* ncp->begin_var first variable's offset, file header extent
* ncp->begin_rec first record variable's offset
* ncp->recsize sum of all single record size of all variables
* ncp->vars.value[*]->len individual variable size (record size)
*/
static int
compute_var_shape(NC *ncp)
{
int i, j, err;
char xloc[1024];
NC_var *first_var = NULL; /* first "non-record" var */
NC_var *first_rec = NULL; /* first "record" var */
if (ncp->vars.ndefined == 0) return NC_NOERR;
ncp->begin_var = ncp->xsz;
ncp->begin_rec = ncp->xsz;
ncp->recsize = 0;
for (i=0; i<ncp->vars.ndefined; i++) {
snprintf(xloc,sizeof(xloc),"var %s:",ncp->vars.value[i]->name);
/* check if dimids are valid */
for (j=0; j<ncp->vars.value[i]->ndims; j++) {
if (ncp->vars.value[i]->dimids[j] < 0) {
if (verbose) printf("Error:\n");
if (verbose) printf("\t%s: dimension ID [%d] invalid (%d)\n",xloc,i,ncp->vars.value[i]->dimids[i]);
DEBUG_RETURN_ERROR(NC_EBADDIM) /* dimid is not defined */
}
else if (ncp->vars.value[i]->dimids[j] >= ncp->dims.ndefined) {
if (verbose) printf("Error:\n");
if (verbose) printf("\t%s: dimension ID [%d] (%d) larger than defined (%d)\n",xloc,i,ncp->vars.value[i]->dimids[i], ncp->dims.ndefined);
DEBUG_RETURN_ERROR(NC_EBADDIM);
}
}
/* ncp->vars.value[i]->len will be recomputed from dimensions in
* var_shape64() */
err = var_shape64(ncp->vars.value[i], &ncp->dims, xloc);
if (err != NC_NOERR) return err;
if (IS_RECVAR(ncp->vars.value[i])) {
if (first_rec == NULL) first_rec = ncp->vars.value[i];
ncp->recsize += ncp->vars.value[i]->len;
}
else { /* fixed-size variable */
if (first_var == NULL) first_var = ncp->vars.value[i];
ncp->begin_rec = ncp->vars.value[i]->begin
+ ncp->vars.value[i]->len;
}
}
if (first_rec != NULL) {
if (ncp->begin_rec > first_rec->begin) {
if (verbose) printf("Error:\n");
if (verbose) printf("\tbegin of record section (%lld) greater than the begin of first record (%lld)\n",ncp->begin_rec, first_rec->begin);
DEBUG_RETURN_ERROR(NC_ENOTNC) /* not a netCDF file or corrupted */
}
ncp->begin_rec = first_rec->begin;
/*
* for special case of exactly one record variable, pack value
*/
if (ncp->recsize == first_rec->len)
ncp->recsize = *first_rec->dsizes * first_rec->xsz;
}
if (first_var != NULL)
ncp->begin_var = first_var->begin;
else
ncp->begin_var = ncp->begin_rec;
if (ncp->begin_var <= 0) {
if (verbose) printf("Error:\n");
if (verbose) printf("\tbegin of variable section (%lld) is negative\n",ncp->begin_var);
DEBUG_RETURN_ERROR(NC_ENOTNC) /* not a netCDF file or corrupted */
}
else if (ncp->xsz > ncp->begin_var) {
if (verbose) printf("Error:\n");
if (verbose) printf("\tfile header size (%lld) is larger than the begin of data section (%lld)\n",ncp->xsz, ncp->begin_var);
DEBUG_RETURN_ERROR(NC_ENOTNC) /* not a netCDF file or corrupted */
}
else if (ncp->begin_rec <= 0) {
if (verbose) printf("Error:\n");
if (verbose) printf("\tbegin of record section (%lld) is zero or negative\n",ncp->begin_rec);
DEBUG_RETURN_ERROR(NC_ENOTNC) /* not a netCDF file or corrupted */
}
else if (ncp->begin_var > ncp->begin_rec) {
if (verbose) printf("Error:\n");
if (verbose) printf("\tbegin of data section (%lld) is larger than record section (%lld)\n",ncp->begin_var, ncp->begin_rec);
DEBUG_RETURN_ERROR(NC_ENOTNC) /* not a netCDF file or corrupted */
}
return NC_NOERR;
}
/*
* repair file contents
*/
static int
val_repair(int fd, off_t offset, size_t len, void *buf)
{
ssize_t nn;
if (-1 == lseek(fd, offset, SEEK_SET)) {
if (verbose)
printf("Error at line %d: lseek %s\n",__LINE__,strerror(errno));
return -1;
}
nn = write(fd, buf, len);
if (nn == -1) {
if (verbose)
printf("Error at line %d: write %s\n",__LINE__,strerror(errno));
return -1;
}
if (nn != len) {
if (verbose)
printf("Error at line %d: writing %zd bytes but only %zd written\n",
__LINE__,len, nn);
return -1;
}
return NC_NOERR;
}
/*
* Fetch the next header chunk.
*/
static int
val_fetch(int fd, bufferinfo *gbp) {
ssize_t nn = 0;
long long slack; /* any leftover data in the buffer */
size_t pos_addr, base_addr;
assert(gbp->base != NULL);
pos_addr = (size_t) gbp->pos;
base_addr = (size_t) gbp->base;
slack = gbp->size - (pos_addr - base_addr);
/* if gbp->pos and gbp->base are the same, there is no leftover buffer data
* to worry about.
* In the other extreme, where gbp->size == (gbp->pos - gbp->base), then all
* data in the buffer has been consumed */
if (slack == gbp->size) slack = 0;
memset(gbp->base, 0, gbp->size);
gbp->pos = gbp->base;
if (-1 == lseek(fd, gbp->offset-slack, SEEK_SET)) {
fprintf(stderr,"Error at line %d: lseek %s\n",__LINE__,strerror(errno));
return -1;
}
nn = read(fd, gbp->base, gbp->size);
if (nn == -1) {
fprintf(stderr,"Error at line %d: read %s\n",__LINE__,strerror(errno));
return -1;
}
gbp->offset += (off_t)(gbp->size - (size_t)slack);
return NC_NOERR;
}
/*
* Ensure that 'nextread' bytes are available.
*/
static int
val_check_buffer(int fd,
bufferinfo *gbp,
size_t nextread)
{
size_t pos_addr, base_addr;
pos_addr = (size_t) gbp->pos;
base_addr = (size_t) gbp->base;
if (pos_addr + nextread <= base_addr + gbp->size)
return NC_NOERR;
return val_fetch(fd, gbp);
}
static int
val_get_NC_tag(int fd, bufferinfo *gbp, NC_tag *tagp, const char *loc)
{
int status;
size_t err_addr;
unsigned int tag;
err_addr = ERR_ADDR;
status = val_check_buffer(fd, gbp, (gbp->version < 5) ? 4 : 8);
if (status != NC_NOERR) goto fn_exit;
tag = get_uint32(gbp);
switch(tag) {
case 0: *tagp = NC_UNSPECIFIED; break;
case 10: *tagp = NC_DIMENSION; break;
case 11: *tagp = NC_VARIABLE; break;
case 12: *tagp = NC_ATTRIBUTE; break;
default:
*tagp = NC_INVALID;
if (verbose) printf("Error @ [0x%8.8zx]:\n", err_addr);
if (verbose) printf("\tInvalid NC component tag (%d)\n",tag);
return NC_ENOTNC;
}