Debian Codegraph @

geanyctags/src/readtags.c

raw
1 /*
2 * Copyright (c) 1996-2003, Darren Hiebert
3 *
4 * This source code is released into the public domain.
5 *
6 * This module contains functions for reading tag files.
7 */
8
9 /*
10 * INCLUDE FILES
11 */
12 #include <stdlib.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <stdio.h>
16 #include <errno.h>
17 #include <sys/types.h> /* to declare off_t */
18
19 #include "readtags.h"
20
21 /*
22 * MACROS
23 */
24 #define TAB '\t'
25
26
27 /*
28 * DATA DECLARATIONS
29 */
30 typedef struct {
31 size_t size;
32 char *buffer;
33 } vstring;
34
35 /* Define readtags' own off_t. */
36 #ifdef _WIN32
37 typedef long long rt_off_t;
38 #else
39 typedef off_t rt_off_t;
40 #endif
41
42 /* Information about current tag file */
43 struct sTagFile {
44 /* has the file been opened and this structure initialized? */
45 unsigned char initialized;
46 /* format of tag file */
47 unsigned char format;
48 /* 1 "u-ctags" is set to !_TAG_OUTPUT_MODE pseudo tag
49 * and "slash" is set to !_TAG_OUTPUT_FILESEP
50 * pseudo tag in the tags file. */
51 unsigned char inputUCtagsMode;
52 /* how is the tag file sorted? */
53 tagSortType sortMethod;
54 /* pointer to file structure */
55 FILE* fp;
56 /* file position of first character of `line' */
57 rt_off_t pos;
58 /* size of tag file in seekable positions */
59 rt_off_t size;
60 /* last line read */
61 vstring line;
62 /* name of tag in last line read */
63 vstring name;
64 /* defines tag search state */
65 struct {
66 /* file position of last match for tag */
67 rt_off_t pos;
68 /* name of tag last searched for */
69 char *name;
70 /* length of name for partial matches */
71 size_t nameLength;
72 /* performing partial match */
73 short partial;
74 /* ignoring case */
75 short ignorecase;
76 } search;
77 /* miscellaneous extension fields */
78 struct {
79 /* number of entries in `list' */
80 unsigned short max;
81 /* list of key value pairs */
82 tagExtensionField *list;
83 } fields;
84 /* buffers to be freed at close */
85 struct {
86 /* name of program author */
87 char *author;
88 /* name of program */
89 char *name;
90 /* URL of distribution */
91 char *url;
92 /* program version */
93 char *version;
94 } program;
95 /* 0 (initial state set by calloc), errno value,
96 * or tagErrno typed value */
97 int err;
98 };
99
100 /*
101 * DATA DEFINITIONS
102 */
103 static const char *const EmptyString = "";
104 static const char *const PseudoTagPrefix = "!_";
105 static const size_t PseudoTagPrefixLength = 2;
106
107 /*
108 * FUNCTION DEFINITIONS
109 */
110
111 static rt_off_t readtags_ftell(FILE *fp)
112 {
113 rt_off_t pos;
114
115 #ifdef _WIN32
116 pos = _ftelli64(fp);
117 #else
118 pos = ftell(fp);
119 #endif
120
121 return pos;
122 }
123
124 static int readtags_fseek(FILE *fp, rt_off_t pos, int whence)
125 {
126 int ret;
127
128 #ifdef _WIN32
129 ret = _fseeki64(fp, pos, whence);
130 #else
131 ret = fseek(fp, pos, whence);
132 #endif
133
134 return ret;
135 }
136
137 /* Converts a hexadecimal digit to its value */
138 static int xdigitValue (unsigned char digit)
139 {
140 if (digit >= '0' && digit <= '9')
141 return digit - '0';
142 else if (digit >= 'a' && digit <= 'f')
143 return 10 + digit - 'a';
144 else if (digit >= 'A' && digit <= 'F')
145 return 10 + digit - 'A';
146 else
147 return 0;
148 }
149
150 /*
151 * Reads the first character from the string, possibly un-escaping it, and
152 * advances *s to the start of the next character.
153 */
154 static int readTagCharacter (const char **const s)
155 {
156 const unsigned char *p = (const unsigned char *) *s;
157 int c = *p;
158
159 p++;
160
161 if (c == '\\')
162 {
163 switch (*p)
164 {
165 case 't': c = '\t'; p++; break;
166 case 'r': c = '\r'; p++; break;
167 case 'n': c = '\n'; p++; break;
168 case '\\': c = '\\'; p++; break;
169 /* Universal-CTags extensions */
170 case 'a': c = '\a'; p++; break;
171 case 'b': c = '\b'; p++; break;
172 case 'v': c = '\v'; p++; break;
173 case 'f': c = '\f'; p++; break;
174 case 'x':
175 if (isxdigit (p[1]) && isxdigit (p[2]))
176 {
177 int val = (xdigitValue (p[1]) << 4) | xdigitValue (p[2]);
178 if (val < 0x80)
179 {
180 p += 3;
181 c = val;
182 }
183 }
184 break;
185 }
186 }
187
188 *s = (const char *) p;
189
190 return c;
191 }
192
193 /*
194 * Compare two strings, ignoring case.
195 * Return 0 for match, < 0 for smaller, > 0 for bigger
196 * Make sure case is folded to uppercase in comparison (like for 'sort -f')
197 * This makes a difference when one of the chars lies between upper and lower
198 * ie. one of the chars [ \ ] ^ _ ` for ascii. (The '_' in particular !)
199 */
200 static int taguppercmp (const char *s1, const char *s2)
201 {
202 int result;
203 int c1, c2;
204 do
205 {
206 c1 = (unsigned char)*s1++;
207 c2 = readTagCharacter (&s2);
208
209 result = toupper (c1) - toupper (c2);
210 } while (result == 0 && c1 != '\0' && c2 != '\0');
211 return result;
212 }
213
214 static int tagnuppercmp (const char *s1, const char *s2, size_t n)
215 {
216 int result;
217 int c1, c2;
218 do
219 {
220 c1 = (unsigned char)*s1++;
221 c2 = readTagCharacter (&s2);
222
223 result = toupper (c1) - toupper (c2);
224 } while (result == 0 && --n > 0 && c1 != '\0' && c2 != '\0');
225 return result;
226 }
227
228 static int tagcmp (const char *s1, const char *s2)
229 {
230 int result;
231 int c1, c2;
232 do
233 {
234 c1 = (unsigned char)*s1++;
235 c2 = readTagCharacter (&s2);
236
237 result = c1 - c2;
238 } while (result == 0 && c1 != '\0' && c2 != '\0');
239 return result;
240 }
241
242 static int tagncmp (const char *s1, const char *s2, size_t n)
243 {
244 int result;
245 int c1, c2;
246 do
247 {
248 c1 = *s1++;
249 c2 = readTagCharacter (&s2);
250
251 result = c1 - c2;
252 } while (result == 0 && --n > 0 && c1 != '\0' && c2 != '\0');
253 return result;
254 }
255
256 static tagResult growString (vstring *s)
257 {
258 tagResult result = TagFailure;
259 size_t newLength;
260 char *newLine;
261 if (s->size == 0)
262 {
263 newLength = 128;
264 newLine = (char*) malloc (newLength);
265 if (newLine)
266 *newLine = '\0';
267 }
268 else
269 {
270 newLength = 2 * s->size;
271 newLine = (char*) realloc (s->buffer, newLength);
272 }
273 if (newLine == NULL)
274 perror ("string too large");
275 else
276 {
277 s->buffer = newLine;
278 s->size = newLength;
279 result = TagSuccess;
280 }
281 return result;
282 }
283
284 /* Copy name of tag out of tag line */
285 static tagResult copyName (tagFile *const file)
286 {
287 size_t length;
288 const char *end = strchr (file->line.buffer, '\t');
289 if (end == NULL)
290 {
291 end = strchr (file->line.buffer, '\n');
292 if (end == NULL)
293 end = strchr (file->line.buffer, '\r');
294 }
295 if (end != NULL)
296 length = end - file->line.buffer;
297 else
298 length = strlen (file->line.buffer);
299 while (length >= file->name.size)
300 {
301 if (growString (&file->name) != TagSuccess)
302 return TagFailure;
303 }
304 strncpy (file->name.buffer, file->line.buffer, length);
305 file->name.buffer [length] = '\0';
306 return TagSuccess;
307 }
308
309 /* Return 1 on success.
310 * Return 0 on failure or EOF.
311 * errno is set to *err unless EOF.
312 */
313 static int readTagLineRaw (tagFile *const file, int *err)
314 {
315 int result = 1;
316 int reReadLine;
317
318 /* If reading the line places any character other than a null or a
319 * newline at the last character position in the buffer (one less than
320 * the buffer size), then we must resize the buffer and reattempt to read
321 * the line.
322 */
323 do
324 {
325 char *const pLastChar = file->line.buffer + file->line.size - 2;
326 char *line;
327
328 file->pos = readtags_ftell (file->fp);
329 if (file->pos < 0)
330 {
331 *err = errno;
332 result = 0;
333 break;
334 }
335 reReadLine = 0;
336 *pLastChar = '\0';
337 line = fgets (file->line.buffer, (int) file->line.size, file->fp);
338 if (line == NULL)
339 {
340 /* read error */
341 *err = 0;
342 if (! feof (file->fp))
343 *err = errno;
344 result = 0;
345 }
346 else if (*pLastChar != '\0' &&
347 *pLastChar != '\n' && *pLastChar != '\r')
348 {
349 /* buffer overflow */
350 if (growString (&file->line) != TagSuccess)
351 {
352 *err = ENOMEM;
353 result = 0;
354 }
355
356 if (readtags_fseek (file->fp, file->pos, SEEK_SET) < 0)
357 {
358 *err = errno;
359 result = 0;
360 }
361 reReadLine = 1;
362 }
363 else
364 {
365 size_t i = strlen (file->line.buffer);
366 while (i > 0 &&
367 (file->line.buffer [i - 1] == '\n' || file->line.buffer [i - 1] == '\r'))
368 {
369 file->line.buffer [i - 1] = '\0';
370 --i;
371 }
372 }
373 } while (reReadLine && result);
374 if (result)
375 {
376 if (copyName (file) != TagSuccess)
377 {
378 *err = ENOMEM;
379 result = 0;
380 }
381 }
382 return result;
383 }
384
385 /* Return 1 on success.
386 * Return 0 on failure or EOF.
387 * errno is set to *err unless EOF.
388 */
389 static int readTagLine (tagFile *const file, int *err)
390 {
391 int result;
392 do
393 {
394 result = readTagLineRaw (file, err);
395 } while (result && *file->name.buffer == '\0');
396 return result;
397 }
398
399 static tagResult growFields (tagFile *const file)
400 {
401 tagResult result = TagFailure;
402 unsigned short newCount = (unsigned short) 2 * file->fields.max;
403 tagExtensionField *newFields = (tagExtensionField*)
404 realloc (file->fields.list, newCount * sizeof (tagExtensionField));
405 if (newFields == NULL)
406 perror ("too many extension fields");
407 else
408 {
409 file->fields.list = newFields;
410 file->fields.max = newCount;
411 result = TagSuccess;
412 }
413 return result;
414 }
415
416 static tagResult parseExtensionFields (tagFile *const file, tagEntry *const entry,
417 char *const string, int *err)
418 {
419 char *p = string;
420 char *tail = string + (string? strlen(string):0);
421 size_t q_len;
422
423 while (p != NULL && *p != '\0')
424 {
425 while (*p == TAB)
426 *p++ = '\0';
427 if (*p != '\0')
428 {
429 char *colon;
430 char *field = p;
431 p = strchr (p, TAB);
432 if (p != NULL)
433 *p++ = '\0';
434 colon = strchr (field, ':');
435 if (colon == NULL)
436 entry->kind = field;
437 else
438 {
439 const char *key = field;
440 char *q = colon + 1;
441 const char *value = q;
442 const int key_len = colon - key;
443 *colon = '\0';
444
445 q_len = tail - q;
446
447 /* Unescaping */
448 while (*q != '\0')
449 {
450 const char *next = q;
451 int ch = readTagCharacter (&next);
452 size_t skip = next - q;
453
454 *q = (char) ch;
455 q++;
456 q_len -= skip;
457 if (skip > 1)
458 {
459 /* + 1 is for moving the area including the last '\0'. */
460 memmove (q, next, q_len + 1);
461 if (p)
462 p -= skip - 1;
463 if (tail != string)
464 tail -= skip - 1;
465 }
466 }
467
468 if (key_len == 4)
469 {
470 if (memcmp (key, "kind", 4) == 0)
471 entry->kind = value;
472 else if (memcmp (key, "file", 4) == 0)
473 entry->fileScope = 1;
474 else if (memcmp (key, "line", 4) == 0)
475 {
476 char *endptr = NULL;
477 long m = strtol (value, &endptr, 10);
478 if (*endptr != '\0' || m < 0)
479 {
480 *err = TagErrnoUnexpectedLineno;
481 return TagFailure;
482 }
483 entry->address.lineNumber = m;
484 }
485 else
486 goto normalField;
487 }
488 else
489 {
490 normalField:
491 if (entry->fields.count == file->fields.max)
492 {
493 if (growFields (file) != TagSuccess)
494 {
495 *err = ENOMEM;
496 return TagFailure;
497 }
498 }
499 file->fields.list [entry->fields.count].key = key;
500 file->fields.list [entry->fields.count].value = value;
501 ++entry->fields.count;
502 }
503 }
504 }
505 }
506 return TagSuccess;
507 }
508
509 static int isOdd (unsigned int i)
510 {
511 return (i % 2);
512 }
513
514 static unsigned int countContinuousBackslashesBackward(const char *from,
515 const char *till)
516 {
517 unsigned int counter = 0;
518
519 for (; from > till; from--)
520 {
521 if (*from == '\\')
522 counter++;
523 else
524 break;
525 }
526 return counter;
527 }
528
529 /* When unescaping, the input string becomes shorter.
530 * e.g. \t occupies two bytes on the tag file.
531 * It is converted to 0x9 and occupies one byte.
532 * memmove called here for shortening the line
533 * buffer. */
534 static char *unescapeInPlace (char *q, char **tab, size_t *p_len)
535 {
536 char *p = q;
537
538 while (*p != '\0')
539 {
540 const char *next = p;
541 int ch = readTagCharacter (&next);
542 size_t skip = next - p;
543
544 *p = (char) ch;
545 p++;
546 *p_len -= skip;
547 if (skip > 1)
548 {
549 /* + 1 is for moving the area including the last '\0'. */
550 memmove (p, next, *p_len + 1);
551 if (*tab)
552 *tab -= skip - 1;
553 }
554 }
555
556 return p;
557 }
558
559 static tagResult parseTagLine (tagFile *file, tagEntry *const entry, int *err)
560 {
561 int i;
562 char *p = file->line.buffer;
563 size_t p_len = strlen (p);
564 char *tab = strchr (p, TAB);
565
566 memset(entry, 0, sizeof(*entry));
567
568 entry->name = p;
569 if (tab != NULL)
570 {
571 *tab = '\0';
572 }
573
574 p = unescapeInPlace (p, &tab, &p_len);
575
576 if (tab != NULL)
577 {
578 p = tab + 1;
579 entry->file = p;
580 tab = strchr (p, TAB);
581 if (file->inputUCtagsMode)
582 {
583 if (tab != NULL)
584 {
585 *tab = '\0';
586 }
587 p = unescapeInPlace (p, &tab, &p_len);
588 }
589
590 if (tab != NULL)
591 {
592 int fieldsPresent;
593 int combinedPattern;
594 *tab = '\0';
595 p = tab + 1;
596 if (*p == '/' || *p == '?')
597 {
598 /* parse pattern */
599 int delimiter = *(unsigned char*) p;
600 entry->address.lineNumber = 0;
601 entry->address.pattern = p;
602 do
603 {
604 p = strchr (p + 1, delimiter);
605 } while (p != NULL
606 && isOdd (countContinuousBackslashesBackward (p - 1,
607 entry->address.pattern)));
608
609 if (p == NULL)
610 {
611 /* TODO: invalid pattern */
612 }
613 else
614 ++p;
615 }
616 else if (isdigit (*(unsigned char*) p))
617 {
618 /* parse line number */
619 entry->address.pattern = p;
620 entry->address.lineNumber = atol (p);
621 while (isdigit (*(unsigned char*) p))
622 ++p;
623 if (p)
624 {
625 combinedPattern = (strncmp (p, ";/", 2) == 0) ||
626 (strncmp (p, ";?", 2) == 0);
627 if (combinedPattern)
628 {
629 ++p;
630 /* parse pattern */
631 int delimiter = *(unsigned char*) p;
632 do
633 {
634 p = strchr (p + 1, delimiter);
635 } while (p != NULL
636 && isOdd (countContinuousBackslashesBackward (p - 1,
637 entry->address.pattern)));
638
639 if (p == NULL)
640 {
641 /* TODO: invalid pattern */
642 }
643 else
644 ++p;
645 }
646 }
647 }
648 else
649 {
650 /* TODO: invalid pattern */
651 }
652
653 if (p)
654 {
655 fieldsPresent = (strncmp (p, ";\"", 2) == 0);
656 *p = '\0';
657 if (fieldsPresent)
658 {
659 if (parseExtensionFields (file, entry, p + 2, err) != TagSuccess)
660 return TagFailure;
661 }
662 }
663 }
664 }
665 if (entry->fields.count > 0)
666 entry->fields.list = file->fields.list;
667 for (i = entry->fields.count ; i < file->fields.max ; ++i)
668 {
669 file->fields.list [i].key = NULL;
670 file->fields.list [i].value = NULL;
671 }
672 return TagSuccess;
673 }
674
675 static char *duplicate (const char *str)
676 {
677 char *result = NULL;
678 if (str != NULL)
679 {
680 result = strdup (str);
681 if (result == NULL)
682 perror (NULL);
683 }
684 return result;
685 }
686
687 static int isPseudoTagLine (const char *buffer)
688 {
689 return (strncmp (buffer, PseudoTagPrefix, PseudoTagPrefixLength) == 0);
690 }
691
692 static tagResult readPseudoTags (tagFile *const file, tagFileInfo *const info)
693 {
694 fpos_t startOfLine;
695 int err = 0;
696 tagResult result = TagSuccess;
697 const size_t prefixLength = strlen (PseudoTagPrefix);
698 int tag_output_mode_u_ctags = 0;
699 int tag_output_filesep_slash = 0;
700
701 info->file.format = 1;
702 info->file.sort = TAG_UNSORTED;
703 info->program.author = NULL;
704 info->program.name = NULL;
705 info->program.url = NULL;
706 info->program.version = NULL;
707
708 while (1)
709 {
710 if (fgetpos (file->fp, &startOfLine) < 0)
711 {
712 err = errno;
713 break;
714 }
715 if (! readTagLine (file, &err))
716 break;
717 if (!isPseudoTagLine (file->line.buffer))
718 break;
719 else
720 {
721 tagEntry entry;
722 const char *key, *value;
723 if (parseTagLine (file, &entry, &err) != TagSuccess)
724 break;
725 key = entry.name + prefixLength;
726 value = entry.file;
727 if (strcmp (key, "TAG_FILE_SORTED") == 0)
728 {
729 char *endptr = NULL;
730 long m = strtol (value, &endptr, 10);
731 if (*endptr != '\0' || m < 0 || m > 2)
732 {
733 err = TagErrnoUnexpectedSortedMethod;
734 break;
735 }
736 file->sortMethod = (tagSortType) m;
737 }
738 else if (strcmp (key, "TAG_FILE_FORMAT") == 0)
739 {
740 char *endptr = NULL;
741 long m = strtol (value, &endptr, 10);
742 if (*endptr != '\0' || m < 1 || m > 2)
743 {
744 err = TagErrnoUnexpectedFormat;
745 break;
746 }
747 file->format = (unsigned char) m;
748 }
749 else if (strcmp (key, "TAG_PROGRAM_AUTHOR") == 0)
750 {
751 file->program.author = duplicate (value);
752 if (value && file->program.author == NULL)
753 {
754 err = ENOMEM;
755 break;
756 }
757 }
758 else if (strcmp (key, "TAG_PROGRAM_NAME") == 0)
759 {
760 file->program.name = duplicate (value);
761 if (value && file->program.name == NULL)
762 {
763 err = ENOMEM;
764 break;
765 }
766 }
767 else if (strcmp (key, "TAG_PROGRAM_URL") == 0)
768 {
769 file->program.url = duplicate (value);
770 if (value && file->program.url == NULL)
771 {
772 err = ENOMEM;
773 break;
774 }
775 }
776 else if (strcmp (key, "TAG_PROGRAM_VERSION") == 0)
777 {
778 file->program.version = duplicate (value);
779 if (value && file->program.version == NULL)
780 {
781 err = ENOMEM;
782 break;
783 }
784 }
785 else if (strcmp (key, "TAG_OUTPUT_MODE") == 0)
786 {
787 if (strcmp (value, "u-ctags") == 0)
788 tag_output_mode_u_ctags = 1;
789 }
790 else if (strcmp (key, "TAG_OUTPUT_FILESEP") == 0)
791 {
792 if (strcmp (value, "slash") == 0)
793 tag_output_filesep_slash = 1;
794 }
795
796 info->file.format = file->format;
797 info->file.sort = file->sortMethod;
798 info->program.author = file->program.author;
799 info->program.name = file->program.name;
800 info->program.url = file->program.url;
801 info->program.version = file->program.version;
802 }
803 }
804
805 if (tag_output_mode_u_ctags && tag_output_filesep_slash)
806 file->inputUCtagsMode = 1;
807
808 if (fsetpos (file->fp, &startOfLine) < 0)
809 err = errno;
810
811 info->status.error_number = err;
812 if (err)
813 result = TagFailure;
814 return result;
815 }
816
817 static int doesFilePointPseudoTag (tagFile *const file, void *unused)
818 {
819 return isPseudoTagLine (file->name.buffer);
820 }
821
822 static tagResult gotoFirstLogicalTag (tagFile *const file)
823 {
824 fpos_t startOfLine;
825
826 if (readtags_fseek(file->fp, 0, SEEK_SET) == -1)
827 {
828 file->err = errno;
829 return TagFailure;
830 }
831
832 while (1)
833 {
834 if (fgetpos (file->fp, &startOfLine) < 0)
835 {
836 file->err = errno;
837 return TagFailure;
838 }
839 if (! readTagLine (file, &file->err))
840 {
841 if (file->err)
842 return TagFailure;
843 break;
844 }
845 if (!isPseudoTagLine (file->line.buffer))
846 break;
847 }
848 if (fsetpos (file->fp, &startOfLine) < 0)
849 {
850 file->err = errno;
851 return TagFailure;
852 }
853 return TagSuccess;
854 }
855
856 static tagFile *initialize (const char *const filePath, tagFileInfo *const info)
857 {
858 tagFile *result = (tagFile*) calloc ((size_t) 1, sizeof (tagFile));
859
860 if (result == NULL)
861 {
862 info->status.opened = 0;
863 info->status.error_number = ENOMEM;
864 return NULL;
865 }
866
867 if (growString (&result->line) != TagSuccess)
868 goto mem_error;
869 if (growString (&result->name) != TagSuccess)
870 goto mem_error;
871 result->fields.max = 20;
872 result->fields.list = (tagExtensionField*) calloc (
873 result->fields.max, sizeof (tagExtensionField));
874 if (result->fields.list == NULL)
875 goto mem_error;
876
877 #if defined(__GLIBC__) && (__GLIBC__ >= 2) \
878 && defined(__GLIBC_MINOR__) && (__GLIBC_MINOR__ >= 3)
879 result->fp = fopen (filePath, "rbm");
880 #endif
881 if (result->fp == NULL)
882 {
883 errno = 0;
884 result->fp = fopen (filePath, "rb");
885 }
886 if (result->fp == NULL)
887 {
888 info->status.error_number = errno;
889 goto file_error;
890 }
891
892 /* Record the size of the tags file to `size` field of result. */
893 if (readtags_fseek (result->fp, 0, SEEK_END) == -1)
894 {
895 info->status.error_number = errno;
896 goto file_error;
897 }
898 result->size = readtags_ftell (result->fp);
899 if (result->size == -1)
900 {
901 /* fseek() retruns an int value.
902 * We observed following behavior on Windows;
903 * if sizeof(int) of the platform is too small for
904 * representing the size of the tags file, fseek()
905 * returns -1 and it doesn't set errno.
906 */
907 info->status.error_number = errno;
908 if (info->status.error_number == 0)
909 info->status.error_number = TagErrnoFileMaybeTooBig;
910
911 goto file_error;
912 }
913 if (readtags_fseek(result->fp, 0, SEEK_SET) == -1)
914 {
915 info->status.error_number = errno;
916 goto file_error;
917 }
918
919 if (readPseudoTags (result, info) == TagFailure)
920 goto file_error;
921
922 info->status.opened = 1;
923 result->initialized = 1;
924
925 return result;
926 mem_error:
927 info->status.error_number = ENOMEM;
928 file_error:
929 free (result->line.buffer);
930 free (result->name.buffer);
931 free (result->fields.list);
932 if (result->fp)
933 fclose (result->fp);
934 free (result);
935 info->status.opened = 0;
936 return NULL;
937 }
938
939 static void terminate (tagFile *const file)
940 {
941 fclose (file->fp);
942
943 free (file->line.buffer);
944 free (file->name.buffer);
945 free (file->fields.list);
946
947 if (file->program.author != NULL)
948 free (file->program.author);
949 if (file->program.name != NULL)
950 free (file->program.name);
951 if (file->program.url != NULL)
952 free (file->program.url);
953 if (file->program.version != NULL)
954 free (file->program.version);
955 if (file->search.name != NULL)
956 free (file->search.name);
957
958 memset (file, 0, sizeof (tagFile));
959
960 free (file);
961 }
962
963 static tagResult readNext (tagFile *const file, tagEntry *const entry)
964 {
965 tagResult result;
966
967 if (file == NULL)
968 return TagFailure;
969
970 if (! file->initialized)
971 {
972 file->err = TagErrnoInvalidArgument;
973 return TagFailure;
974 }
975
976 if (! readTagLine (file, &file->err))
977 return TagFailure;
978
979 result = (entry != NULL)
980 ? parseTagLine (file, entry, &file->err)
981 : TagSuccess;
982
983 return result;
984 }
985
986 static const char *readFieldValue (
987 const tagEntry *const entry, const char *const key)
988 {
989 const char *result = NULL;
990 int i;
991 if (strcmp (key, "kind") == 0)
992 result = entry->kind;
993 else if (strcmp (key, "file") == 0)
994 result = EmptyString;
995 else for (i = 0 ; i < entry->fields.count && result == NULL ; ++i)
996 if (strcmp (entry->fields.list [i].key, key) == 0)
997 result = entry->fields.list [i].value;
998 return result;
999 }
1000
1001 static int readTagLineSeek (tagFile *const file, const rt_off_t pos)
1002 {
1003 if (readtags_fseek (file->fp, pos, SEEK_SET) < 0)
1004 {
1005 file->err = errno;
1006 return 0;
1007 }
1008
1009 /* read probable partial line */
1010 if (!readTagLine (file, &file->err))
1011 return 0;
1012
1013 /* read complete line */
1014 if (pos > 0)
1015 return readTagLine (file, &file->err);
1016
1017 return 1;
1018 }
1019
1020 static int nameComparison (tagFile *const file)
1021 {
1022 int result;
1023 if (file->search.ignorecase)
1024 {
1025 if (file->search.partial)
1026 result = tagnuppercmp (file->search.name, file->name.buffer,
1027 file->search.nameLength);
1028 else
1029 result = taguppercmp (file->search.name, file->name.buffer);
1030 }
1031 else
1032 {
1033 if (file->search.partial)
1034 result = tagncmp (file->search.name, file->name.buffer,
1035 file->search.nameLength);
1036 else
1037 result = tagcmp (file->search.name, file->name.buffer);
1038 }
1039 return result;
1040 }
1041
1042 static tagResult findFirstNonMatchBefore (tagFile *const file)
1043 {
1044 #define JUMP_BACK 512
1045 int more_lines;
1046 int comp;
1047 rt_off_t start = file->pos;
1048 rt_off_t pos = start;
1049 do
1050 {
1051 if (pos < (rt_off_t) JUMP_BACK)
1052 pos = 0;
1053 else
1054 pos = pos - JUMP_BACK;
1055 more_lines = readTagLineSeek (file, pos);
1056 if (more_lines == 0 && file->err)
1057 return TagFailure;
1058 comp = nameComparison (file);
1059 } while (more_lines && comp == 0 && pos > 0 && pos < start);
1060 return TagSuccess;
1061 }
1062
1063 static tagResult findFirstMatchBefore (tagFile *const file)
1064 {
1065 tagResult result = TagFailure;
1066 int more_lines;
1067 rt_off_t start = file->pos;
1068 if (findFirstNonMatchBefore (file) != TagSuccess)
1069 return TagFailure;
1070 do
1071 {
1072 more_lines = readTagLine (file, &file->err);
1073 if (more_lines == 0 && file->err)
1074 return TagFailure;
1075 if (nameComparison (file) == 0)
1076 result = TagSuccess;
1077 } while (more_lines && result != TagSuccess && file->pos < start);
1078 return result;
1079 }
1080
1081 static tagResult findBinary (tagFile *const file)
1082 {
1083 tagResult result = TagFailure;
1084 rt_off_t lower_limit = 0;
1085 rt_off_t upper_limit = file->size;
1086 rt_off_t last_pos = 0;
1087 rt_off_t pos = upper_limit / 2;
1088 while (result != TagSuccess)
1089 {
1090 if (! readTagLineSeek (file, pos))
1091 {
1092 if (file->err)
1093 break;
1094 /* in case we fell off end of file */
1095 result = findFirstMatchBefore (file);
1096 break;
1097 }
1098 else if (pos == last_pos)
1099 {
1100 /* prevent infinite loop if we backed up to beginning of file */
1101 break;
1102 }
1103 else
1104 {
1105 const int comp = nameComparison (file);
1106 last_pos = pos;
1107 if (comp < 0)
1108 {
1109 upper_limit = pos;
1110 pos = lower_limit + ((upper_limit - lower_limit) / 2);
1111 }
1112 else if (comp > 0)
1113 {
1114 lower_limit = pos;
1115 pos = lower_limit + ((upper_limit - lower_limit) / 2);
1116 }
1117 else if (pos == 0)
1118 result = TagSuccess;
1119 else
1120 {
1121 result = findFirstMatchBefore (file);
1122 if (result != TagSuccess && file->err)
1123 break;
1124 }
1125 }
1126 }
1127 return result;
1128 }
1129
1130 static tagResult findSequentialFull (tagFile *const file,
1131 int (* isAcceptable) (tagFile *const, void *),
1132 void *data)
1133 {
1134 if (file == NULL)
1135 return TagFailure;
1136
1137 if (!file->initialized || file->err)
1138 {
1139 file->err = TagErrnoInvalidArgument;
1140 return TagFailure;
1141 }
1142
1143 tagResult result = TagFailure;
1144 while (result == TagFailure)
1145 {
1146 if (! readTagLine (file, &file->err))
1147 break;
1148 if (isAcceptable (file, data))
1149 result = TagSuccess;
1150 }
1151 return result;
1152 }
1153
1154 static int nameAcceptable (tagFile *const file, void *unused)
1155 {
1156 return (nameComparison (file) == 0);
1157 }
1158
1159 static tagResult findSequential (tagFile *const file)
1160 {
1161 return findSequentialFull (file, nameAcceptable, NULL);
1162 }
1163
1164 static tagResult find (tagFile *const file, tagEntry *const entry,
1165 const char *const name, const int options)
1166 {
1167 tagResult result;
1168 if (file->search.name != NULL)
1169 free (file->search.name);
1170 file->search.name = duplicate (name);
1171 if (file->search.name == NULL)
1172 {
1173 file->err = ENOMEM;
1174 return TagFailure;
1175 }
1176 file->search.nameLength = strlen (name);
1177 file->search.partial = (options & TAG_PARTIALMATCH) != 0;
1178 file->search.ignorecase = (options & TAG_IGNORECASE) != 0;
1179 if (readtags_fseek (file->fp, 0, SEEK_END) < 0)
1180 {
1181 file->err = errno;
1182 return TagFailure;
1183 }
1184 file->size = readtags_ftell (file->fp);
1185 if (file->size == -1)
1186 {
1187 file->err = errno;
1188 return TagFailure;
1189 }
1190 if (readtags_fseek(file->fp, 0, SEEK_SET) == -1)
1191 {
1192 file->err = errno;
1193 return TagFailure;
1194 }
1195 if ((file->sortMethod == TAG_SORTED && !file->search.ignorecase) ||
1196 (file->sortMethod == TAG_FOLDSORTED && file->search.ignorecase))
1197 {
1198 result = findBinary (file);
1199 if (result == TagFailure && file->err)
1200 return TagFailure;
1201 }
1202 else
1203 {
1204 result = findSequential (file);
1205 if (result == TagFailure && file->err)
1206 return TagFailure;
1207 }
1208
1209 if (result != TagSuccess)
1210 file->search.pos = file->size;
1211 else
1212 {
1213 file->search.pos = file->pos;
1214 result = (entry != NULL)
1215 ? parseTagLine (file, entry, &file->err)
1216 : TagSuccess;
1217 }
1218 return result;
1219 }
1220
1221 static tagResult findNextFull (tagFile *const file, tagEntry *const entry,
1222 int sorted,
1223 int (* isAcceptable) (tagFile *const, void *),
1224 void *data)
1225 {
1226 tagResult result;
1227 if (sorted)
1228 {
1229 result = tagsNext (file, entry);
1230 if (result == TagSuccess && !isAcceptable (file, data))
1231 result = TagFailure;
1232 }
1233 else
1234 {
1235 result = findSequentialFull (file, isAcceptable, data);
1236 if (result == TagSuccess && entry != NULL)
1237 result = parseTagLine (file, entry, &file->err);
1238 }
1239 return result;
1240 }
1241
1242 static tagResult findNext (tagFile *const file, tagEntry *const entry)
1243 {
1244 return findNextFull (file, entry,
1245 (file->sortMethod == TAG_SORTED && !file->search.ignorecase) ||
1246 (file->sortMethod == TAG_FOLDSORTED && file->search.ignorecase),
1247 nameAcceptable, NULL);
1248 }
1249
1250 static tagResult findPseudoTag (tagFile *const file, int rewindBeforeFinding, tagEntry *const entry)
1251 {
1252 if (file == NULL)
1253 return TagFailure;
1254
1255 if (!file->initialized || file->err)
1256 {
1257 file->err = TagErrnoInvalidArgument;
1258 return TagFailure;
1259 }
1260
1261 if (rewindBeforeFinding)
1262 {
1263 if (readtags_fseek(file->fp, 0, SEEK_SET) == -1)
1264 {
1265 file->err = errno;
1266 return TagFailure;
1267 }
1268 }
1269 return findNextFull (file, entry,
1270 (file->sortMethod == TAG_SORTED || file->sortMethod == TAG_FOLDSORTED),
1271 doesFilePointPseudoTag,
1272 NULL);
1273 }
1274
1275
1276 /*
1277 * EXTERNAL INTERFACE
1278 */
1279
1280 extern tagFile *tagsOpen (const char *const filePath, tagFileInfo *const info)
1281 {
1282 tagFileInfo infoDummy;
1283 return initialize (filePath, info? info: &infoDummy);
1284 }
1285
1286 extern tagResult tagsSetSortType (tagFile *const file, const tagSortType type)
1287 {
1288 if (file == NULL)
1289 return TagFailure;
1290
1291 if (!file->initialized || file->err)
1292 {
1293 file->err = TagErrnoInvalidArgument;
1294 return TagFailure;
1295 }
1296
1297 switch (type)
1298 {
1299 case TAG_UNSORTED:
1300 case TAG_SORTED:
1301 case TAG_FOLDSORTED:
1302 file->sortMethod = type;
1303 return TagSuccess;
1304 default:
1305 file->err = TagErrnoUnexpectedSortedMethod;
1306 return TagFailure;
1307 }
1308 }
1309
1310 extern tagResult tagsFirst (tagFile *const file, tagEntry *const entry)
1311 {
1312 if (file == NULL)
1313 return TagFailure;
1314
1315 if (!file->initialized || file->err)
1316 {
1317 file->err = TagErrnoInvalidArgument;
1318 return TagFailure;
1319 }
1320
1321 if (gotoFirstLogicalTag (file) != TagSuccess)
1322 return TagFailure;
1323 return readNext (file, entry);
1324 }
1325
1326 extern tagResult tagsNext (tagFile *const file, tagEntry *const entry)
1327 {
1328 if (file == NULL)
1329 return TagFailure;
1330
1331 if (!file->initialized || file->err)
1332 {
1333 file->err = TagErrnoInvalidArgument;
1334 return TagFailure;
1335 }
1336
1337 return readNext (file, entry);
1338 }
1339
1340 extern const char *tagsField (const tagEntry *const entry, const char *const key)
1341 {
1342 const char *result = NULL;
1343 if (entry != NULL)
1344 result = readFieldValue (entry, key);
1345 return result;
1346 }
1347
1348 extern tagResult tagsFind (tagFile *const file, tagEntry *const entry,
1349 const char *const name, const int options)
1350 {
1351 if (file == NULL)
1352 return TagFailure;
1353
1354 if (!file->initialized || file->err)
1355 {
1356 file->err = TagErrnoInvalidArgument;
1357 return TagFailure;
1358 }
1359
1360 return find (file, entry, name, options);
1361 }
1362
1363 extern tagResult tagsFindNext (tagFile *const file, tagEntry *const entry)
1364 {
1365 if (file == NULL)
1366 return TagFailure;
1367
1368 if (!file->initialized || file->err)
1369 {
1370 file->err = TagErrnoInvalidArgument;
1371 return TagFailure;
1372 }
1373
1374 return findNext (file, entry);
1375 }
1376
1377 extern tagResult tagsFirstPseudoTag (tagFile *const file, tagEntry *const entry)
1378 {
1379 return findPseudoTag (file, 1, entry);
1380 }
1381
1382 extern tagResult tagsNextPseudoTag (tagFile *const file, tagEntry *const entry)
1383 {
1384 return findPseudoTag (file, 0, entry);
1385 }
1386
1387 extern tagResult tagsFindPseudoTag (tagFile *const file, tagEntry *const entry,
1388 const char *const name, const int match)
1389 {
1390 size_t len;
1391 tagEntry entry0;
1392 /* cppcheck-suppress uninitvar symbolName=&entry0 */
1393 tagEntry *entryp = entry? entry: &entry0;
1394
1395 tagResult r = tagsFirstPseudoTag (file, entryp);
1396 if (r != TagSuccess)
1397 return r;
1398
1399 if (match & TAG_PARTIALMATCH)
1400 len = strlen (name);
1401
1402 do
1403 {
1404 if (match & TAG_PARTIALMATCH)
1405 {
1406 if (strncmp (entryp->name, name, len) == 0)
1407 return TagSuccess;
1408 }
1409 else
1410 {
1411 if (strcmp (entryp->name, name) == 0)
1412 return TagSuccess;
1413 }
1414 r = tagsNextPseudoTag (file, entryp);
1415 }
1416 while (r == TagSuccess);
1417
1418 return r;
1419 }
1420
1421 extern tagResult tagsClose (tagFile *const file)
1422 {
1423 tagResult result = TagFailure;
1424 if (file != NULL && file->initialized)
1425 {
1426 terminate (file);
1427 result = TagSuccess;
1428 }
1429 return result;
1430 }
1431
1432 extern int tagsGetErrno (tagFile *const file)
1433 {
1434 if (file == NULL)
1435 return TagErrnoInvalidArgument;
1436 return file->err;
1437 }