Remove xcalloc() and convert its callers to xzalloc(). About half of them
[platform/upstream/busybox.git] / coreutils / sort.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * SuS3 compliant sort implementation for busybox
4  *
5  * Copyright (C) 2004 by Rob Landley <rob@landley.net>
6  *
7  * MAINTAINER: Rob Landley <rob@landley.net>
8  * 
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  *
11  * See SuS3 sort standard at:
12  * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
13  */
14
15 #include "busybox.h"
16
17 static int global_flags;
18
19 /*
20         sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
21         sort -c [-bdfinru][-t char][-k keydef][file]
22 */
23
24 /* These are sort types */
25 #define FLAG_n                  1               /* Numeric sort */
26 #define FLAG_g                  2               /* Sort using strtod() */
27 #define FLAG_M                  4               /* Sort date */
28 /* ucsz apply to root level only, not keys.  b at root level implies bb */
29 #define FLAG_u                  8               /* Unique */
30 #define FLAG_c                  16              /* Check: no output, exit(!ordered) */
31 #define FLAG_s                  32              /* Stable sort, no ascii fallback at end */
32 #define FLAG_z                  64              /* Input is null terminated, not \n */
33 /* These can be applied to search keys, the previous four can't */
34 #define FLAG_b                  128             /* Ignore leading blanks */
35 #define FLAG_r                  256             /* Reverse */
36 #define FLAG_d                  512             /* Ignore !(isalnum()|isspace()) */
37 #define FLAG_f                  1024    /* Force uppercase */
38 #define FLAG_i                  2048    /* Ignore !isprint() */
39 #define FLAG_bb                 32768   /* Ignore trailing blanks  */
40
41
42 #ifdef CONFIG_FEATURE_SORT_BIG
43 static char key_separator;
44
45 static struct sort_key
46 {
47         struct sort_key *next_key;      /* linked list */
48         unsigned short range[4];        /* start word, start char, end word, end char */
49         int flags;
50 } *key_list;
51
52 static char *get_key(char *str, struct sort_key *key, int flags)
53 {
54         int start=0,end,len,i,j;
55
56         /* Special case whole string, so we don't have to make a copy */
57         if(key->range[0]==1 && !key->range[1] && !key->range[2] && !key->range[3]
58                 && !(flags&(FLAG_b&FLAG_d&FLAG_f&FLAG_i&FLAG_bb))) return str;
59         /* Find start of key on first pass, end on second pass*/
60         len=strlen(str);
61
62         for(j=0;j<2;j++) {
63                 if(!key->range[2*j]) end=len;
64                 /* Loop through fields */
65                 else {
66                         end=0;
67                         for(i=1;i<key->range[2*j]+j;i++) {
68                                 /* Skip leading blanks or first separator */
69                                 if(str[end]) {
70                                         if(!key_separator && isspace(str[end]))
71                                                 while(isspace(str[end])) end++;
72                                 }
73                                 /* Skip body of key */
74                                 for(;str[end];end++) {
75                                         if(key_separator) {
76                                                 if(str[end]==key_separator) break;
77                                         } else if(isspace(str[end])) break;
78                                 }
79                         }
80                 }
81                 if(!j) start=end;
82         }
83         /* Key with explicit separator starts after separator */
84         if(key_separator && str[start]==key_separator) start++;
85         /* Strip leading whitespace if necessary */
86         if(flags&FLAG_b) while(isspace(str[start])) start++;
87         /* Strip trailing whitespace if necessary */
88         if(flags&FLAG_bb) while(end>start && isspace(str[end-1])) end--;
89         /* Handle offsets on start and end */
90         if(key->range[3]) {
91                 end+=key->range[3]-1;
92                 if(end>len) end=len;
93         }
94         if(key->range[1]) {
95                 start+=key->range[1]-1;
96                 if(start>len) start=len;
97         }
98         /* Make the copy */
99         if(end<start) end=start;
100         str=xstrndup(str+start,end-start);
101         /* Handle -d */
102         if(flags&FLAG_d) {
103                 for(start=end=0;str[end];end++)
104                         if(isspace(str[end]) || isalnum(str[end])) str[start++]=str[end];
105                 str[start]=0;
106         }
107         /* Handle -i */
108         if(flags&FLAG_i) {
109                 for(start=end=0;str[end];end++)
110                         if(isprint(str[end])) str[start++]=str[end];
111                 str[start]=0;
112         }
113         /* Handle -f */
114         if(flags*FLAG_f) for(i=0;str[i];i++) str[i]=toupper(str[i]);
115
116         return str;
117 }
118
119 static struct sort_key *add_key(void)
120 {
121         struct sort_key **pkey=&key_list;
122         while(*pkey) pkey=&((*pkey)->next_key);
123         return *pkey = xzalloc(sizeof(struct sort_key));
124 }
125
126 #define GET_LINE(fp) (global_flags&FLAG_z) ? bb_get_chunk_from_file(fp,NULL) \
127                                                                                    : bb_get_chomped_line_from_file(fp)
128 #else
129 #define GET_LINE(fp)            bb_get_chomped_line_from_file(fp)
130 #endif
131
132 /* Iterate through keys list and perform comparisons */
133 static int compare_keys(const void *xarg, const void *yarg)
134 {
135         int flags=global_flags,retval=0;
136         char *x,*y;
137
138 #ifdef CONFIG_FEATURE_SORT_BIG
139         struct sort_key *key;
140
141         for(key=key_list;!retval && key;key=key->next_key) {
142                 flags=(key->flags) ? key->flags : global_flags;
143                 /* Chop out and modify key chunks, handling -dfib */
144                 x=get_key(*(char **)xarg,key,flags);
145                 y=get_key(*(char **)yarg,key,flags);
146 #else
147         /* This curly bracket serves no purpose but to match the nesting
148            level of the for() loop we're not using */
149         {
150                 x=*(char **)xarg;
151                 y=*(char **)yarg;
152 #endif
153                 /* Perform actual comparison */
154                 switch(flags&7) {
155                         default:
156                                 bb_error_msg_and_die("Unknown sort type.");
157                                 break;
158                         /* Ascii sort */
159                         case 0:
160                                 retval=strcmp(x,y);
161                                 break;
162 #ifdef CONFIG_FEATURE_SORT_BIG
163                         case FLAG_g:
164                         {
165                                 char *xx,*yy;
166                                 double dx=strtod(x,&xx), dy=strtod(y,&yy);
167                                 /* not numbers < NaN < -infinity < numbers < +infinity) */
168                                 if(x==xx) retval=(y==yy ? 0 : -1);
169                                 else if(y==yy) retval=1;
170                                 /* Check for isnan */
171                                 else if(dx != dx) retval = (dy != dy) ? 0 : -1;
172                                 else if(dy != dy) retval = 1;
173                                 /* Check for infinity.  Could underflow, but it avoids libm. */
174                                 else if(1.0/dx == 0.0) {
175                                         if(dx<0) retval=((1.0/dy == 0.0 && dy<0) ? 0 : -1);
176                                         else retval=((1.0/dy == 0.0 && dy>0) ? 0 : 1);
177                                 } else if(1.0/dy == 0.0) retval=dy<0 ? 1 : -1;
178                                 else retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
179                                 break;
180                         }
181                         case FLAG_M:
182                         {
183                                 struct tm thyme;
184                                 int dx;
185                                 char *xx,*yy;
186
187                                 xx=strptime(x,"%b",&thyme);
188                                 dx=thyme.tm_mon;
189                                 yy=strptime(y,"%b",&thyme);
190                                 if(!xx) retval=(!yy ? 0 : -1);
191                                 else if(!yy) retval=1;
192                                 else retval=(dx==thyme.tm_mon ? 0 : dx-thyme.tm_mon);
193                                 break;
194                         }
195                         /* Full floating point version of -n */
196                         case FLAG_n:
197                         {
198                                 double dx=atof(x),dy=atof(y);
199                                 retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
200                                 break;
201                         }
202                 }
203                 /* Free key copies. */
204                 if(x!=*(char **)xarg) free(x);
205                 if(y!=*(char **)yarg) free(y);
206                 if(retval) break;
207 #else
208                         /* Integer version of -n for tiny systems */
209                         case FLAG_n:
210                                 retval=atoi(x)-atoi(y);
211                                 break;
212                 }
213 #endif
214         }
215         /* Perform fallback sort if necessary */
216         if(!retval && !(global_flags&FLAG_s))
217                         retval=strcmp(*(char **)xarg, *(char **)yarg);
218         return ((flags&FLAG_r)?-1:1)*retval;
219 }
220
221 int sort_main(int argc, char **argv)
222 {
223         FILE *fp,*outfile=NULL;
224         int linecount=0,i,flag;
225         char *line,**lines=NULL,*optlist="ngMucszbrdfimS:T:o:k:t:";
226         int c;
227
228         bb_default_error_retval = 2;
229         /* Parse command line options */
230         while((c=getopt(argc,argv,optlist))>0) {
231                 line=strchr(optlist,c);
232                 if(!line) bb_show_usage();
233                 switch(*line) {
234 #ifdef CONFIG_FEATURE_SORT_BIG
235                         case 'o':
236                                 if(outfile) bb_error_msg_and_die("Too many -o.");
237                                 outfile=xfopen(optarg,"w");
238                                 break;
239                         case 't':
240                                 if(key_separator || optarg[1])
241                                         bb_error_msg_and_die("Too many -t.");
242                                 key_separator=*optarg;
243                                 break;
244                         /* parse sort key */
245                         case 'k':
246                         {
247                                 struct sort_key *key=add_key();
248                                 char *temp, *temp2;
249
250                                 temp=optarg;
251                                 for(i=0;*temp;) {
252                                         /* Start of range */
253                                         key->range[2*i]=(unsigned short)strtol(temp,&temp,10);
254                                         if(*temp=='.')
255                                                 key->range[(2*i)+1]=(unsigned short)strtol(temp+1,&temp,10);
256                                         for(;*temp;temp++) {
257                                                 if(*temp==',' && !i++) {
258                                                         temp++;
259                                                         break;
260                                                 } /* no else needed: fall through to syntax error
261                                                          because comma isn't in optlist */
262                                                 temp2=strchr(optlist,*temp);
263                                                 flag=(1<<(temp2-optlist));
264                                                 if(!temp2 || (flag>FLAG_M && flag<FLAG_b))
265                                                         bb_error_msg_and_die("Unknown key option.");
266                                                 /* b after , means strip _trailing_ space */
267                                                 if(i && flag==FLAG_b) flag=FLAG_bb;
268                                                 key->flags|=flag;
269                                         }
270                                 }
271                                 break;
272                         }
273 #endif
274                         default:
275                                 global_flags|=(1<<(line-optlist));
276                                 /* global b strips leading and trailing spaces */
277                                 if(global_flags&FLAG_b) global_flags|=FLAG_bb;
278                                 break;
279                 }
280         }
281         /* Open input files and read data */
282         for(i=argv[optind] ? optind : optind-1;argv[i];i++) {
283                 if(i<optind || (*argv[i]=='-' && !argv[i][1])) fp=stdin;
284                 else fp=xfopen(argv[i],"r");
285                 for(;;) {
286                         line=GET_LINE(fp);
287                         if(!line) break;
288                         if(!(linecount&63))
289                                 lines=xrealloc(lines, sizeof(char *)*(linecount+64));
290                         lines[linecount++]=line;
291                 }
292                 fclose(fp);
293         }
294 #ifdef CONFIG_FEATURE_SORT_BIG
295         /* if no key, perform alphabetic sort */
296     if(!key_list) add_key()->range[0]=1;
297         /* handle -c */
298         if(global_flags&FLAG_c) {
299                 int j=(global_flags&FLAG_u) ? -1 : 0;
300                 for(i=1;i<linecount;i++)
301                         if(compare_keys(&lines[i-1],&lines[i])>j) {
302                                 fprintf(stderr,"Check line %d\n",i);
303                                 return 1;
304                         }
305                 return 0;
306         }
307 #endif
308         /* Perform the actual sort */
309         qsort(lines,linecount,sizeof(char *),compare_keys);
310         /* handle -u */
311         if(global_flags&FLAG_u) {
312                 for(flag=0,i=1;i<linecount;i++) {
313                         if(!compare_keys(&lines[flag],&lines[i])) free(lines[i]);
314                         else lines[++flag]=lines[i];
315                 }
316                 if(linecount) linecount=flag+1;
317         }
318         /* Print it */
319         if(!outfile) outfile=stdout;
320         for(i=0;i<linecount;i++) fprintf(outfile,"%s\n",lines[i]);
321         bb_fflush_stdout_and_exit(EXIT_SUCCESS);
322 }