[M68K] move include/asm-m68k to arch/m68k/include/asm
[barebox-mini2440.git] / lib / libbb.c
blobee91fec18baaffd3dda27bed77e7c997f4ccc877
1 /* vi: set sw=8 ts=8: */
2 /*
3 * Utility routines.
5 * Copyright (C) many different people.
6 * If you wrote this, please acknowledge your work.
8 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9 */
11 #include <common.h>
12 #include <libbb.h>
13 #include <linux/stat.h>
14 #include <fs.h>
15 #include <xfuncs.h>
16 #include <malloc.h>
17 #include <environment.h>
19 /* concatenate path and file name to new allocation buffer,
20 * not adding '/' if path name already has '/'
22 char *concat_path_file(const char *path, const char *filename)
24 char *lc, *str;
26 if (!path)
27 path = "";
28 lc = last_char_is(path, '/');
29 while (*filename == '/')
30 filename++;
32 str = xmalloc(strlen(path) + (lc==0 ? 1 : 0) + strlen(filename) + 1);
33 sprintf(str, "%s%s%s", path, (lc==NULL ? "/" : ""), filename);
35 return str;
37 EXPORT_SYMBOL(concat_path_file);
40 * This function make special for recursive actions with usage
41 * concat_path_file(path, filename)
42 * and skipping "." and ".." directory entries
45 char *concat_subpath_file(const char *path, const char *f)
47 if (f && DOT_OR_DOTDOT(f))
48 return NULL;
49 return concat_path_file(path, f);
51 EXPORT_SYMBOL(concat_subpath_file);
53 /* check if path points to an executable file;
54 * return 1 if found;
55 * return 0 otherwise;
57 int execable_file(const char *name)
59 struct stat s;
60 return (!stat(name, &s) && S_ISREG(s.st_mode));
62 EXPORT_SYMBOL(execable_file);
65 /* search $PATH for an executable file;
66 * return allocated string containing full path if found;
67 * return NULL otherwise;
69 char *find_execable(const char *filename)
71 char *path, *p, *n;
73 p = path = strdup(getenv("PATH"));
74 while (p) {
75 n = strchr(p, ':');
76 if (n)
77 *n++ = '\0';
78 if (*p != '\0') { /* it's not a PATH="foo::bar" situation */
79 p = concat_path_file(p, filename);
80 if (execable_file(p)) {
81 free(path);
82 return p;
84 free(p);
86 p = n;
88 free(path);
89 return NULL;
91 EXPORT_SYMBOL(find_execable);
93 /* Find out if the last character of a string matches the one given.
94 * Don't underrun the buffer if the string length is 0.
96 char* last_char_is(const char *s, int c)
98 if (s && *s) {
99 size_t sz = strlen(s) - 1;
100 s += sz;
101 if ( (unsigned char)*s == c)
102 return (char*)s;
104 return NULL;
106 EXPORT_SYMBOL(last_char_is);
108 /* Like strncpy but make sure the resulting string is always 0 terminated. */
109 char * safe_strncpy(char *dst, const char *src, size_t size)
111 if (!size) return dst;
112 dst[--size] = '\0';
113 return strncpy(dst, src, size);
115 EXPORT_SYMBOL(safe_strncpy);