-
Notifications
You must be signed in to change notification settings - Fork 26
/
easel.c
2814 lines (2535 loc) · 102 KB
/
easel.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
/* Easel's foundation.
*
* Contents:
* 1. Exception and fatal error handling.
* 2. Memory allocation/deallocation conventions.
* 3. Standard banner for Easel miniapplications.
* 4. Improved replacements for some C library functions.
* 5. Portable drop-in replacements for nonstandard C functions.
* 6. Additional string functions, esl_str*()
* 7. File path/name manipulation, including tmpfiles.
* 8. Typed comparison functions.
* 9. Other miscellaneous functions.
* 10. Unit tests.
* 11. Test driver.
* 12. Examples.
*/
#include <esl_config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _POSIX_VERSION
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifdef HAVE_MPI
#include <mpi.h> /* MPI_Abort() may be used in esl_fatal() or other program killers */
#endif
#include "easel.h"
#include <syslog.h>
/*****************************************************************
* 1. Exception and fatal error handling.
*****************************************************************/
static esl_exception_handler_f esl_exception_handler = NULL;
/* Function: esl_fail()
* Synopsis: Handle a normal failure code/message before returning to caller.
*
* Purpose: A "failure" is a normal error that we want to handle
* without terminating the program; we're going to return
* control to the caller with a nonzero error code and
* (optionally) an informative error message formatted
* in <errbuf>.
*
* <esl_fail()> is called internally by the <ESL_FAIL()>
* and <ESL_XFAIL()> macros (see easel.h). The reason to
* have the failure macros call such a simple little
* function is to give us a convenient debugging
* breakpoint. For example, in a <_Validate()> routine that
* needs to do a normal return to a caller, you can set a
* breakpoint in <esl_fail()> to see exactly where the
* validation failed.
*/
void
esl_fail(char *errbuf, const char *format, ...)
{
if (format)
{
va_list ap;
/* Check whether we are running as a daemon so we can do the
* right thing about logging instead of printing errors
*/
if (getppid() != 1)
{ // we aren't running as a daemon, so print the error normally
va_start(ap, format);
if (errbuf) vsnprintf(errbuf, eslERRBUFSIZE, format, ap);
va_end(ap);
}
else
{
va_start(ap, format);
vsyslog(LOG_ERR, format, ap);
va_end(ap);
}
}
}
/* Function: esl_exception()
* Synopsis: Throw an exception.
*
* Purpose: Throw an exception. An "exception" is defined by Easel
* as an internal error that shouldn't happen and/or is
* outside the user's control; as opposed to "failures", that
* are to be expected, and within user control, and
* therefore normal. By default, exceptions are fatal.
* A program that wishes to be more robust can register
* a non-fatal exception handler.
*
* Easel programs normally call one of the exception-handling
* wrappers <ESL_EXCEPTION()> or <ESL_XEXCEPTION()>, which
* handle the overhead of passing in <use_errno>, <sourcefile>,
* and <sourceline>. <esl_exception> is rarely called directly.
*
* If no custom exception handler has been registered, the
* default behavior is to print a brief message to <stderr>
* then <abort()>, resulting in a nonzero exit code from the
* program. Depending on what <errcode>, <sourcefile>,
* <sourceline>, and the <sprintf()>-formatted <format>
* are, this output looks like:
*
* Fatal exception (source file foo.c, line 42):
* Something wicked this way came.
*
* Additionally, in an MPI parallel program, the default fatal
* handler aborts all processes (with <MPI_Abort()>), not just
* the one that called <esl_exception()>.
*
* Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
* use_errno - if TRUE, also use perror() to report POSIX errno message.
* sourcefile - Name of offending source file; normally __FILE__.
* sourceline - Name of offending source line; normally __LINE__.
* format - <sprintf()> formatted exception message, followed
* by any additional necessary arguments for that
* message.
*
* Returns: void.
*
* Throws: No abnormal error conditions. (Who watches the watchers?)
*/
void
esl_exception(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, ...)
{
va_list argp;
#ifdef HAVE_MPI
int mpiflag;
#endif
if (esl_exception_handler != NULL)
{ // If the custom exception handler tries to print to stderr/stdout, the error may get eaten if we're running as a daemon
// Not sure how to prevent that, since we can't control what custom handlers get written.
va_start(argp, format);
(*esl_exception_handler)(errcode, use_errno, sourcefile, sourceline, format, argp);
va_end(argp);
return;
}
else
{
/* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
if (getppid() != 1)
{ // we're not running as a daemon, so print the error normally
fprintf(stderr, "Fatal exception (source file %s, line %d):\n", sourcefile, sourceline);
va_start(argp, format);
vfprintf(stderr, format, argp);
va_end(argp);
fprintf(stderr, "\n");
if (use_errno && errno) perror("system error");
fflush(stderr);
}
else
{
va_start(argp, format);
vsyslog(LOG_ERR, format, argp);
va_end(argp);
}
#ifdef HAVE_MPI
MPI_Initialized(&mpiflag); /* we're assuming we can do this, even in a corrupted, dying process...? */
if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
#endif
abort();
}
}
/* Function: esl_exception_SetHandler()
* Synopsis: Register a different exception handling function.
*
* Purpose: Register a different exception handling function,
* <handler>. When an exception occurs, the handler
* receives at least four arguments: <errcode>, <sourcefile>,
* <sourceline>, and <format>.
*
* <errcode> is an Easel error code, such as
* <eslEINVAL>. See <easel.h> for a list of all codes.
*
* <use_errno> is TRUE for POSIX system call failures. The
* handler may then use POSIX <errno> to format/print an
* additional message, using <perror()> or <strerror_r()>.
*
* <sourcefile> is the name of the Easel source code file
* in which the exception occurred, and <sourceline> is
* the line number.
*
* <format> is a <vprintf()>-formatted string, followed by
* a <va_list> containing any additional arguments that
* formatted message needs. Your custom exception handler
* will probably use <vfprintf()> or <vsnprintf()> to format
* its error message.
*
* Args: handler - ptr to your custom exception handler.
*
* Returns: void.
*
* Throws: (no abnormal error conditions)
*/
void
esl_exception_SetHandler(void (*handler)(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp))
{
esl_exception_handler = handler;
}
/* Function: esl_exception_ResetDefaultHandler()
* Synopsis: Restore default exception handling.
*
* Purpose: Restore default exception handling, which is to print
* a simple error message to <stderr> then <abort()> (see
* <esl_exception()>.
*
* An example where this might be useful is in a program
* that only temporarily wants to catch one or more types
* of normally fatal exceptions.
*
* If the default handler is already in effect, this
* call has no effect (is a no-op).
*
* Args: (void)
*
* Returns: (void)
*
* Throws: (no abnormal error conditions)
*/
void
esl_exception_ResetDefaultHandler(void)
{
esl_exception_handler = NULL;
}
/* Function: esl_nonfatal_handler()
* Synopsis: A trivial example of a nonfatal exception handler.
*
* Purpose: This serves two purposes. First, it is the simplest
* example of a nondefault exception handler. Second, this
* is used in test harnesses, when they have
* <eslTEST_THROWING> turned on to test that thrown errors
* are handled properly when a nonfatal error handler is
* registered by the application.
*
* Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
* use_errno - TRUE on POSIX system call failures; use <errno>
* sourcefile - Name of offending source file; normally __FILE__.
* sourceline - Name of offending source line; normally __LINE__.
* format - <sprintf()> formatted exception message.
* argp - <va_list> containing any additional necessary arguments for
* the <format> message.
*
* Returns: void.
*
* Throws: (no abnormal error conditions)
*/
void
esl_nonfatal_handler(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp)
{
return;
}
/* Function: esl_fatal()
* Synopsis: Kill a program immediately, for a "violation".
*
* Purpose: Kill a program for a "violation". In general this should only be used
* in development or testing code, not in production
* code. The main use of <esl_fatal()> is in unit tests.
* Another use is in assertions used in dev code.
*
* The only other case (and the only case that should be allowed in
* production code) is in a true "function" (a function that returns
* its answer, rather than an Easel error code), where Easel error
* conventions can't be used (because it can't return an error code),
* AND the error is guaranteed to be a coding error. For an example,
* see <esl_opt_IsOn()>, which triggers a violation if the code
* checks for an option that isn't in the code.
*
* In an MPI-parallel program, the entire job is
* terminated; all processes are aborted (<MPI_Abort()>,
* not just the one that called <esl_fatal()>.
*
* If caller is feeling lazy and just wants to terminate
* without any informative message, use <abort()>.
*
* Args: format - <sprintf()> formatted exception message, followed
* by any additional necessary arguments for that
* message.
*
* Returns: (void)
*
* Throws: (no abnormal error conditions)
*/
void
esl_fatal(const char *format, ...)
{
va_list argp;
#ifdef HAVE_MPI
int mpiflag;
#endif
/* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
if (getppid() != 1)
{ // we're not running as a daemon, so print the error normally
va_start(argp, format);
vfprintf(stderr, format, argp);
va_end(argp);
fprintf(stderr, "\n");
fflush(stderr);
}
else
{
va_start(argp, format);
vsyslog(LOG_ERR, format, argp);
va_end(argp);
}
#ifdef HAVE_MPI
MPI_Initialized(&mpiflag);
if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
#endif
exit(1);
}
/*---------------- end, error handling conventions --------------*/
/*****************************************************************
* 2. Memory allocation/deallocation conventions.
*****************************************************************/
/* Function: esl_resize()
* Synopsis: Implement idiomatic resize-by-doubling + redline allocation rules.
* Incept: SRE, Sun 21 Feb 2021
*
* Purpose: Return a recommended allocation size, given minimum required allocation
* size <n>, current allocation size <a>, and "redline" <r>. Implements
* Easel's idiom for growing an allocation exponentially, while trying
* to keep it capped at a maximum redline.
*
* Let's call the return value <b>: $b \geq n$, i.e. the returned <b> is
* always sufficient to fit <n>.
*
* - If $n >= r$, the requested allocation is above redline, so return
* $b=n$ exactly. This includes when we need to grow the allocation
* ($a < n$), and cases where the current allocation would suffice
* ($a >= n$) but we can shrink it back toward the redline somewhat.
*
* - If $n \leq a$ then the current allocation suffices. If $a \leq r$,
* return $b=a$ (signifying "don't reallocate"). If $a > r$, the
* current allocation is excessive (we know $n < r$) so pull it
* back to redline, returning $b=r$.
*
* - If $n > a$ then increase the current allocation by doubling, until
* it suffices. Cap it at the redline if necessary and don't allow
* doubling to overflow an integer. Now $b \leq r$ and $n \leq b <
* 2n$.
*
* If the caller wants to allow both growing and shrinking (for example,
* supporting an object that has a <Resize()> but not a <Reuse()>), the idiom
* is:
*
* ```
* if ( ( newalloc = esl_resize(n, obj->nalloc, obj->redline)) != a) {
* ESL_REALLOC(obj, ...);
* obj->nalloc = newalloc;
* }
* ```
*
* If the caller only wants <Resize()> to grow, not shrink (because there's
* a <Reuse()> to handle shrinking):
*
* ```
* if (n > obj->nalloc) {
* newalloc = esl_resize(n, obj->nalloc, obj->redline);
* ESL_REALLOC(obj, ...);
* obj->nalloc = newalloc;
* }
* ```
*
* If the caller is a <Reuse()> that's only responsible for shrinking
* allocations back to redline, pass $n=0$, so the allocation will only
* change if $a>r$:
*
* ```
* if (( newalloc = esl_resize(0, obj->nalloc, obj->redline)) != a) {
* ESL_REALLOC(obj, ...);
* obj->nalloc = newalloc;
* }
* ```
*
* Growing allocations exponentially (by doubling) minimizes the number of
* expensive reallocation calls we have to make, when we're expecting to
* reuse/reallocate a space a lot... either because we're growing it
* dynamically (perhaps one unit at a time, like a list), or because we're
* dynamically resizing it for each task in an iteration over different
* tasks.
*
* The "redline" tries to cap or at least minimize allocation size when it
* would exceed <r>. We're often in a situation where the allocations we
* need for an iterated set of tasks have a long-tailed distribution -
* sequence lengths, for example. We may only need to occasionally make
* excursions into very large allocations. Thus, it's advantageous to just
* make a transient exceptional allocation of exactly enough size. In
* Easel's idioms, the next <_Reuse()> or <_Resize()> call pulls an
* exceptional allocation size back down to the redline.
*
* The redline is only useful in the iterated-set-of-different-sized-tasks
* use case. It's not useful in the grow-one-unit-each-step use case (over
* redline, you'd start inefficiently making a reallocation at each step).
* If you're in the grow-one-unit-each-step use case, you want to set the
* redline to <INT_MAX>; or for convenience, if you pass <r=0>, this will
* also turn the redline off (by setting it to INT_MAX internally).
*
* The <n> argument is _inclusive_ of any constant additional allocation
* that the caller needs for edge effects - for example, if caller has
* <s=2> sentinels at positions 0 and m+1 of an array of elements 1..m, it
* passes <n=m+s> as the argument to esl_resize.
*
* Args: n : requested allocation size (n >= 0)
* a : current allocation size (a >= 0)
* r : redline limit (r >= 0; 0 means don't use a redline)
*
* Returns: b, the suggested new allocation (b >= n and b >= 1)
*/
int
esl_resize(int n, int a, int r)
{
const int overflow_limit = INT_MAX / 2;
ESL_DASSERT1(( n >= 0 && a >= 0 && r >= 0));
if (r == 0) r = INT_MAX; // r=0 allows caller to conveniently turn redline off
if (a == 0) a = 1; // 0*=2 isn't going to go anywhere now is it?
if (n >= r) return n; // this could be n < a (shrink), n=a (stay), or n > a (grow)
if (n <= a) { // current allocation a suffices...
if (a <= r) return a; // ... and is below redline, so fine
else return r; // ... but a>r, and r suffices, so shrink back to redline r
}
while (a < n && a <= overflow_limit) a *= 2;
if (a < n) return r; // Doublings of <a> didn't suffice, because n >= (INT_MAX/2) +1. We know r > n here; use r.
else if (a > r) return r; // Cap the allocation at the redline. (Again, we already know r > n here.)
return a; // a has been successfully increased by doubling.
}
/* Function: esl_free()
* Synopsis: free(), while allowing ptr to be NULL.
* Incept: SRE, Fri Nov 3 17:12:01 2017
*
* Purpose: Easel uses a convention of initializing ptrs to be NULL
* before allocating them. When cleaning up after errors, a
* routine can check for non-NULL ptrs to know what to
* free(). Easel code is slightly cleaner if we have a
* free() that no-ops on NULL ptrs.
*
* OBSOLETE. C99 free() allows NULL already.
*/
void
esl_free(void *p)
{
if (p) free(p);
}
/* Function: esl_Free2D()
*
* Purpose: Free a 2D pointer array <p>, where first dimension is
* <dim1>. (That is, the array is <p[0..dim1-1][]>.)
* Tolerates any of the pointers being NULL, to allow
* sparse arrays.
*
* Returns: void.
*
* DEPRECATED. Replace with esl_arr2_Destroy()
*/
void
esl_Free2D(void **p, int dim1)
{
int i;
if (p != NULL) {
for (i = 0; i < dim1; i++)
if (p[i] != NULL) free(p[i]);
free(p);
}
return;
}
/* Function: esl_Free3D()
*
* Purpose: Free a 3D pointer array <p>, where first and second
* dimensions are <dim1>,<dim2>. (That is, the array is
* <p[0..dim1-1][0..dim2-1][]>.) Tolerates any of the
* pointers being NULL, to allow sparse arrays.
*
* Returns: void.
*
* DEPRECATED. Replace with esl_arr3_Destroy()
*/
void
esl_Free3D(void ***p, int dim1, int dim2)
{
int i, j;
if (p != NULL) {
for (i = 0; i < dim1; i++)
if (p[i] != NULL) {
for (j = 0; j < dim2; j++)
if (p[i][j] != NULL) free(p[i][j]);
free(p[i]);
}
free(p);
}
}
/*------------- end, memory allocation conventions --------------*/
/*****************************************************************
* 3. Standard banner for Easel miniapplications.
*****************************************************************/
/* Function: esl_banner()
* Synopsis: print standard Easel application output header
*
* Purpose: Print the standard Easel command line application banner
* to <fp>, constructing it from <progname> (the name of the
* program) and a short one-line description <banner>.
* For example,
* <esl_banner(stdout, "compstruct", "compare RNA structures");>
* might result in:
*
* \begin{cchunk}
* # compstruct :: compare RNA structures
* # Easel 0.1 (February 2005)
* # Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus
* # Freely licensed under the Janelia Software License.
* # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* \end{cchunk}
*
* <progname> would typically be an application's
* <argv[0]>, rather than a fixed string. This allows the
* program to be renamed, or called under different names
* via symlinks. Any path in the <progname> is discarded;
* for instance, if <progname> is "/usr/local/bin/esl-compstruct",
* "esl-compstruct" is used as the program name.
*
* Note:
* Needs to pick up preprocessor #define's from easel.h,
* as set by ./configure:
*
* symbol example
* ------ ----------------
* EASEL_VERSION "0.1"
* EASEL_DATE "May 2007"
* EASEL_COPYRIGHT "Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus"
* EASEL_LICENSE "Freely licensed under the Janelia Software License."
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error.
* <eslEWRITE> on write error.
*/
int
esl_banner(FILE *fp, const char *progname, char *banner)
{
char *appname = NULL;
int status;
if ((status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
if (fprintf(fp, "# %s :: %s\n", appname, banner) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# Easel %s (%s)\n", EASEL_VERSION, EASEL_DATE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# %s\n", EASEL_COPYRIGHT) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# %s\n", EASEL_LICENSE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (appname) free(appname);
return eslOK;
ERROR:
if (appname) free(appname);
return status;
}
/* Function: esl_usage()
* Synopsis: print standard Easel application usage help line
*
* Purpose: Given a usage string <usage> and the name of the program
* <progname>, output a standardized usage/help
* message. <usage> is minimally a one line synopsis like
* "[options] <filename>", but it may extend to multiple
* lines to explain the command line arguments in more
* detail. It should not describe the options; that's the
* job of the getopts module, and its <esl_opt_DisplayHelp()>
* function.
*
* This is used by the Easel miniapps, and may be useful in
* other applications as well.
*
* As in <esl_banner()>, the <progname> is typically passed
* as <argv[0]>, and any path prefix is ignored.
*
* For example, if <argv[0]> is </usr/local/bin/esl-compstruct>,
* then
*
* \begin{cchunk}
* esl_usage(stdout, argv[0], "[options] <trusted file> <test file>">
* \end{cchunk}
*
* produces
*
* \begin{cchunk}
* Usage: esl-compstruct [options] <trusted file> <test file>
* \end{cchunk}
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEWRITE> on write failure.
*/
int
esl_usage(FILE *fp, const char *progname, char *usage)
{
char *appname = NULL;
int status;
if ( (status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
if (fprintf(fp, "Usage: %s %s\n", appname, usage) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (appname) free(appname);
return eslOK;
ERROR:
if (appname) free(appname);
return status;
}
/* Function: esl_dataheader()
* Synopsis: Standard #-prefixed header lines for output data table
*
* Purpose: Print column headers for a space-delimited, fixed-column-width
* data table to <fp>.
*
* Takes a variable number of argument pairs. Each pair is
* <width, label>. The absolute value of <width> is the max
* width of the column. <label> is the column label.
*
* If <width> is negative, left justify the label. (This is
* supposed to mirror the %-8s vs %8s of a printf format.)
*
* Caller marks the end of the argument list
* with a 0 sentinel.
*
* Example: <esl_dataheader(stdout, 8, "name", 3, "A", -4, "B", 0)>
* gives three columns:
*
* \begin{cchunk}
* # name A B
* #------- --- ----
* \end{cchunk}
*
* The <width> arguments match the widths given in
* <fprintf()>'s or whatever generates the data rows.
* Because the first header line is prefixed by \verb+#+, the
* first column's width argument is inclusive of these two
* extra chars, and therefore the first column label must
* have no more than its <width>-2 chars. For all other
* column labels, a label's length cannot exceed its
* <width>.
*
* Up to 1024 columns are allowed. (The only reason there's
* a limit is because you're going to forget to add the 0
* sentinel, and we don't want to risk a <while(1)> infinite
* loop.)
*
* Args: <fp> : output stream
* [<width>, <label]... : width, label pairs
* 0 : sentinel for end of argument list
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if a label is too wide for its width, or if
* the number of columns exceeds the max limit.
* <eslEWRITE> if a write to <fp> fails, which can happen
* if a disk fills up, for example.
*/
int
esl_dataheader(FILE *fp, ...)
{
va_list ap, ap2;
int width, len;
char *s;
int col = 0;
int maxcols = 1024; // limit, to avoid scary while(1) alternative
int leftjustify;
int status;
va_start(ap, fp);
va_copy(ap2, ap);
if ( fputc('#', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
for (col = 0; col < maxcols; col++)
{
width = va_arg(ap, int);
if (width == 0) break;
if (width < 0) { leftjustify = TRUE; width = -width; }
else { leftjustify = FALSE; }
if (col == 0) width -= 2; // First column header -2 char for the "# " prefix
s = va_arg(ap, char *);
len = strlen(s);
if (len > width) {
if (col == 0) ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): first arg (%s) too wide for %d-char column ('# ' leader took 2 chars)", s, width);
else ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): arg %d (%s) too wide for %d-char column", col, s, width);
}
if (leftjustify) { if ( fprintf(fp, " %-*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
else { if ( fprintf(fp, " %*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
}
if (col == maxcols) ESL_XEXCEPTION( eslEINVAL, "esl_dataheader(): too many args");
if ( fputc('\n', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
maxcols = col;
for (col = 0; col < maxcols; col++)
{
width = va_arg(ap2, int);
if (width < 0) width = -width;
if (col == 0) width -= 1;
(void) va_arg(ap2, char *);
if (col == 0) { if ( fputc('#', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
else { if ( fputc(' ', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
while (width--)
if ( fputc('-', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
}
if (fputc('\n', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
va_end(ap);
va_end(ap2);
return eslOK;
ERROR:
va_end(ap);
va_end(ap2);
return status;
}
/*-------------------- end, standard miniapp banner --------------------------*/
/******************************************************************************
* 4. Replacements for C library functions
* fgets() -> esl_fgets() fgets() with dynamic allocation
* printf() -> esl_printf() printf() wrapped in our exception handling
* strdup() -> esl_strdup() strdup() is not ANSI
* strcat() -> esl_strcat() strcat() with dynamic allocation
* strtok() -> esl_strtok() threadsafe strtok()
* sprintf() -> esl_sprintf() sprintf() with dynamic allocation
* strcmp() -> esl_strcmp() strcmp() tolerant of NULL strings
*****************************************************************************/
/* Function: esl_fgets()
*
* Purpose: Dynamic allocation version of fgets(),
* capable of reading almost unlimited line lengths.
*
* Args: buf - ptr to a string (may be reallocated)
* n - ptr to current allocated length of buf,
* (may be changed)
* fp - open file ptr for reading
*
* Before the first call to esl_fgets(),
* initialize buf to NULL and n to 0.
* They're a linked pair, so don't muck with the
* allocation of buf or the value of n while
* you're still doing esl_fgets() calls with them.
*
* Returns: <eslOK> on success.
* Returns <eslEOF> on normal end-of-file.
*
* When <eslOK>:
* <*buf> points to a <NUL>-terminated line from the file.
* <*n> contains the current allocated length for <*buf>.
*
* Caller must free <*buf> eventually.
*
* Throws: <eslEMEM> on an allocation failure.
*
* Example: char *buf = NULL;
* int n = 0;
* FILE *fp = fopen("my_file", "r");
*
* while (esl_fgets(&buf, &n, fp) == eslOK)
* {
* do stuff with buf;
* }
* if (buf != NULL) free(buf);
*/
int
esl_fgets(char **buf, int *n, FILE *fp)
{
int status;
char *s;
int len;
int pos;
if (*n == 0)
{
ESL_ALLOC(*buf, sizeof(char) * 128);
*n = 128;
}
/* Simple case 1. We're sitting at EOF, or there's an error.
* fgets() returns NULL, so we return EOF.
*/
if (fgets(*buf, *n, fp) == NULL) return eslEOF;
/* Simple case 2. fgets() got a string, and it reached EOF doing it.
* return success status, so caller can use
* the last line; on the next call we'll
* return the 0 for the EOF.
*/
if (feof(fp)) return eslOK;
/* Simple case 3. We got a complete string, with \n,
* and don't need to extend the buffer.
*/
len = strlen(*buf);
if ((*buf)[len-1] == '\n') return eslOK;
/* The case we're waiting for. We have an incomplete string,
* and we have to extend the buffer one or more times. Make
* sure we overwrite the previous fgets's \0 (hence +(n-1)
* in first step, rather than 128, and reads of 129, not 128).
*/
pos = (*n)-1;
while (1) {
ESL_REALLOC(*buf, sizeof(char) * (*n+128));
*n += 128;
s = *buf + pos;
if (fgets(s, 129, fp) == NULL) return eslOK;
len = strlen(s);
if (s[len-1] == '\n') return eslOK;
pos += 128;
}
/*NOTREACHED*/
return eslOK;
ERROR:
if (*buf != NULL) free(*buf);
*buf = NULL;
*n = 0;
return status;
}
/* Function: esl_fprintf()
* Synopsis: fprintf() wrapped in our exception handling
* Incept: SRE, Thu Jun 14 09:43:59 2018
*
* Purpose: <fprintf()> wrapped in Easel exception handling. See
* <esl_printf()> for rationale.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEWRITE> on failure.
*/
int
esl_fprintf(FILE *fp, const char *format, ...)
{
if (fp && format)
{
va_list argp;
va_start(argp, format);
if ( vfprintf(fp, format, argp) < 0 ) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
va_end(argp);
}
return eslOK;
}
/* Function: esl_printf()
* Synopsis: printf() wrapped in our exception handling
* Incept: SRE, Thu Jun 14 09:17:17 2018
*
* Purpose: <printf()> wrapped in Easel exception handling.
*
* Rarely and insidiously, <printf()> can fail -- for
* example, when output is redirected to a file and a disk
* fills up. Every <printf()> needs to guard against this,
* else output could silently fail. It seems slightly
* cleaner to use Easel's idiomatic:
*
* ```
* if ((status = esl_printf(...)) != eslOK) return status; // no cleanup
* if ((status = esl_printf(...)) != eslOK) goto ERROR; // with cleanup
* ```
*
* as opposed to having to invoke
* <ESL_EXCEPTION_SYS(eslEWRITE, "write failed")> each
* time.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEWRITE> on failure.
*/
int
esl_printf(const char *format, ...)
{
if (format)
{
va_list argp;
va_start(argp, format);
if ( vprintf(format, argp) < 0 ) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
va_end(argp);
}
return eslOK;
}
/* Function: esl_strdup()
*
* Purpose: Makes a duplicate of string <s>, puts it in <ret_dup>.
* Caller can pass string length <n>, if it's known,
* to save a strlen() call; else pass -1 to have the string length
* determined.
*
* Tolerates <s> being <NULL>; in which case,
* returns <eslOK> with <*ret_dup> set to <NULL>.
*
* Args: s - string to duplicate (NUL-terminated)
* n - length of string, if known; -1 if unknown.
* ret_dup - RETURN: duplicate of <s>.
*
* Returns: <eslOK> on success, and <ret_dup> is valid.
*
* Throws: <eslEMEM> on allocation failure.
*/
int
esl_strdup(const char *s, int64_t n, char **ret_dup)
{
int status;
char *new = NULL;
if (s == NULL) {*ret_dup = NULL; return eslOK; }
if (n < 0) n = strlen(s);
ESL_ALLOC(new, sizeof(char) * (n+1));
strcpy(new, s);
*ret_dup = new;
return eslOK;
ERROR:
if (new) free(new);
*ret_dup = NULL;
return status;
}
/* Function: esl_strcat()
*
* Purpose: Dynamic memory version of strcat().
* Appends <src> to the string that <dest> points to,
* extending allocation for dest if necessary. Caller
* can optionally provide the length of <*dest> in
* <ldest>, and the length of <src> in <lsrc>; if
* either of these is -1, <esl_strcat()> calls <strlen()>
* to determine the length. Providing length information,
* if known, accelerates the routine.
*
* <*dest> may be <NULL>, in which case this is equivalent
* to a <strdup()> of <src> (that is, <*dest> is allocated
* rather than reallocated).
*
* <src> may be <NULL>, in which case <dest> is unmodified.
*
* Note: One timing experiment (100 successive appends of