PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
port.h File Reference
#include <ctype.h>
#include <netdb.h>
#include <pwd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
Include dependency graph for port.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define PGINVALID_SOCKET   (-1)
 
#define IS_DIR_SEP(ch)   ((ch) == '/')
 
#define is_absolute_path(filename)
 
#define EXE   ""
 
#define DEVNULL   "/dev/null"
 
#define TIMEZONE_GLOBAL   timezone
 
#define TZNAME_GLOBAL   tzname
 
#define closesocket   close
 
#define PG_IOLBF   _IOLBF
 
#define pgoff_t   off_t
 
#define fseeko(a, b, c)   fseek(a, b, c)
 
#define ftello(a)   ftell(a)
 
#define SSL_get_current_compression(x)   0
 
#define qsort(a, b, c, d)   pg_qsort(a,b,c,d)
 

Typedefs

typedef int pgsocket
 
typedef int(* qsort_arg_comparator )(const void *a, const void *b, void *arg)
 
typedef void(* pqsigfunc )(int signo)
 

Functions

bool pg_set_noblock (pgsocket sock)
 
bool pg_set_block (pgsocket sock)
 
bool has_drive_prefix (const char *filename)
 
char * first_dir_separator (const char *filename)
 
char * last_dir_separator (const char *filename)
 
char * first_path_var_separator (const char *pathlist)
 
void join_path_components (char *ret_path, const char *head, const char *tail)
 
void canonicalize_path (char *path)
 
void make_native_path (char *path)
 
void cleanup_path (char *path)
 
bool path_contains_parent_reference (const char *path)
 
bool path_is_relative_and_below_cwd (const char *path)
 
bool path_is_prefix_of_path (const char *path1, const char *path2)
 
char * make_absolute_path (const char *path)
 
const char * get_progname (const char *argv0)
 
void get_share_path (const char *my_exec_path, char *ret_path)
 
void get_etc_path (const char *my_exec_path, char *ret_path)
 
void get_include_path (const char *my_exec_path, char *ret_path)
 
void get_pkginclude_path (const char *my_exec_path, char *ret_path)
 
void get_includeserver_path (const char *my_exec_path, char *ret_path)
 
void get_lib_path (const char *my_exec_path, char *ret_path)
 
void get_pkglib_path (const char *my_exec_path, char *ret_path)
 
void get_locale_path (const char *my_exec_path, char *ret_path)
 
void get_doc_path (const char *my_exec_path, char *ret_path)
 
void get_html_path (const char *my_exec_path, char *ret_path)
 
void get_man_path (const char *my_exec_path, char *ret_path)
 
bool get_home_path (char *ret_path)
 
void get_parent_directory (char *path)
 
char ** pgfnames (const char *path)
 
void pgfnames_cleanup (char **filenames)
 
void set_pglocale_pgservice (const char *argv0, const char *app)
 
int find_my_exec (const char *argv0, char *retpath)
 
int find_other_exec (const char *argv0, const char *target, const char *versionstr, char *retpath)
 
void pg_usleep (long microsec)
 
int pg_strcasecmp (const char *s1, const char *s2)
 
int pg_strncasecmp (const char *s1, const char *s2, size_t n)
 
unsigned char pg_toupper (unsigned char ch)
 
unsigned char pg_tolower (unsigned char ch)
 
unsigned char pg_ascii_toupper (unsigned char ch)
 
unsigned char pg_ascii_tolower (unsigned char ch)
 
void simple_prompt (const char *prompt, char *destination, size_t destlen, bool echo)
 
int pclose_check (FILE *stream)
 
bool rmtree (const char *path, bool rmtopdir)
 
char * crypt (const char *key, const char *setting)
 
double pg_erand48 (unsigned short xseed[3])
 
long pg_lrand48 (void)
 
long pg_jrand48 (unsigned short xseed[3])
 
void pg_srand48 (long seed)
 
int fls (int mask)
 
int getpeereid (int sock, uid_t *uid, gid_t *gid)
 
int isinf (double x)
 
char * mkdtemp (char *path)
 
double rint (double x)
 
int inet_aton (const char *cp, struct in_addr *addr)
 
size_t strlcat (char *dst, const char *src, size_t siz)
 
size_t strlcpy (char *dst, const char *src, size_t siz)
 
long random (void)
 
void unsetenv (const char *name)
 
void srandom (unsigned int seed)
 
char * pqStrerror (int errnum, char *strerrbuf, size_t buflen)
 
int pqGetpwuid (uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
 
int pqGethostbyname (const char *name, struct hostent *resultbuf, char *buffer, size_t buflen, struct hostent **result, int *herrno)
 
void pg_qsort (void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
 
int pg_qsort_strcmp (const void *a, const void *b)
 
void qsort_arg (void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
 
int pg_get_encoding_from_locale (const char *ctype, bool write_message)
 
char * inet_net_ntop (int af, const void *src, int bits, char *dst, size_t size)
 
int pg_check_dir (const char *dir)
 
int pg_mkdir_p (char *path, int omode)
 
pqsigfunc pqsignal (int signo, pqsigfunc func)
 
pqsigfunc pqsignal_no_restart (int signo, pqsigfunc func)
 
char * escape_single_quotes_ascii (const char *src)
 
char * wait_result_to_str (int exit_status)
 

Macro Definition Documentation

#define DEVNULL   "/dev/null"
#define EXE   ""

Definition at line 110 of file port.h.

Referenced by find_other_exec(), and get_progname().

#define fseeko (   a,
  b,
  c 
)    fseek(a, b, c)

Definition at line 372 of file port.h.

#define ftello (   a)    ftell(a)

Definition at line 373 of file port.h.

#define PG_IOLBF   _IOLBF

Definition at line 340 of file port.h.

Referenced by logfile_open(), and main().

#define pgoff_t   off_t

Definition at line 355 of file port.h.

#define qsort (   a,
  b,
  c,
 
)    pg_qsort(a,b,c,d)

Definition at line 440 of file port.h.

Referenced by _ltree_picksplit(), aclitemsort(), aclmembers(), acquire_sample_rows(), add_guc_variable(), AddEnumLabel(), AlterSubscription_refresh(), array_to_tsvector(), associate(), BufferSync(), build_guc_variables(), BuildEventTriggerCache(), buildIndexArray(), calc_word_similarity(), carcsort(), CheckConstraintFetch(), choose_bitmap_and(), compactify_tuples(), compileTheLexeme(), compute_array_stats(), compute_range_stats(), compute_scalar_stats(), compute_tsvector_stats(), CreateStatistics(), dsynonym_init(), eliminate_duplicate_dependencies(), entry_dealloc(), EnumValuesCreate(), expand_grouping_sets(), filemap_finalize(), fill_in_constant_lengths(), find_inheritance_children(), findObjectByCatalogId(), g_int_picksplit(), g_intbig_picksplit(), generate_trgm(), generate_wildcard_trgm(), get_docrep(), get_loadable_libraries(), ghstore_picksplit(), ginGetBAEntry(), gist_box_picksplit(), gseg_picksplit(), gtrgm_picksplit(), gtsquery_picksplit(), gtsvector_picksplit(), hstoreUniquePairs(), IssuePendingWritebacks(), load_domaintype_info(), load_enum_cache_data(), lookupVariable(), ltree_picksplit(), ltsGetFreeBlock(), main(), mcelem_array_contained_selec(), mergeins(), mXactCacheGetBySet(), mXactCachePut(), NIImportOOAffixes(), NISortAffixes(), NISortDictionary(), packGraph(), perform_base_backup(), ProcArrayApplyRecoveryInfo(), process_target_file(), QTNSort(), range_gist_double_sorting_split(), rankSort(), read_dictionary(), readstoplist(), rebuild_database_list(), ReorderBufferCopySnap(), selectColorTrigrams(), SerializeTransactionState(), setExtensionMembership(), setup_pct_info(), SnapBuildBuildSnapshot(), sort_policies_by_name(), sort_pool(), sort_snapshot(), sortDataAndIndexObjectsBySize(), sortDumpableObjectsByTypeName(), sortins(), sortouts(), spg_box_quad_picksplit(), spg_kd_picksplit(), spg_quad_picksplit(), spg_text_picksplit(), spgPageIndexMultiDelete(), SyncRepGetNthLatestSyncRecPtr(), tbm_begin_iterate(), TidListEval(), tsq_mcontains(), tsvector_delete_by_indices(), uniqueint(), uniqueLongPos(), uniquePos(), uniqueWORD(), UpdateLogicalMappings(), and writezone().

#define SSL_get_current_compression (   x)    0

Definition at line 419 of file port.h.

Referenced by be_tls_get_compression(), PerformAuthentication(), and PQsslAttribute().

#define TIMEZONE_GLOBAL   timezone

Definition at line 222 of file port.h.

Referenced by abstime2tm(), get_timezone_offset(), and timestamp2tm().

#define TZNAME_GLOBAL   tzname

Definition at line 223 of file port.h.

Referenced by abstime2tm(), and timestamp2tm().

Typedef Documentation

Definition at line 22 of file port.h.

typedef void(* pqsigfunc)(int signo)

Definition at line 470 of file port.h.

typedef int(* qsort_arg_comparator)(const void *a, const void *b, void *arg)

Definition at line 442 of file port.h.

Function Documentation

void canonicalize_path ( char *  path)

Definition at line 254 of file path.c.

References skip_drive, trim_directory(), and trim_trailing_separator().

Referenced by adjust_data_dir(), check_canonical_path(), convert_and_check_filename(), create_script_for_old_cluster_deletion(), create_xlog_or_symlink(), CreateTableSpace(), do_copy(), exec_command_edit(), exec_command_write(), find_in_dynamic_libpath(), find_my_exec(), find_other_exec(), load_libraries(), main(), make_absolute_path(), make_relative_path(), parseCommandLine(), process_file(), resolve_symlinks(), set_pglocale_pgservice(), setup(), setup_bin_paths(), setup_pgdata(), SplitDirectoriesString(), tablespace_list_append(), and tokenize_inc_file().

255 {
256  char *p,
257  *to_p;
258  char *spath;
259  bool was_sep = false;
260  int pending_strips;
261 
262 #ifdef WIN32
263 
264  /*
265  * The Windows command processor will accept suitably quoted paths with
266  * forward slashes, but barfs badly with mixed forward and back slashes.
267  */
268  for (p = path; *p; p++)
269  {
270  if (*p == '\\')
271  *p = '/';
272  }
273 
274  /*
275  * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
276  * as argv[2], so trim off trailing quote.
277  */
278  if (p > path && *(p - 1) == '"')
279  *(p - 1) = '/';
280 #endif
281 
282  /*
283  * Removing the trailing slash on a path means we never get ugly double
284  * trailing slashes. Also, Win32 can't stat() a directory with a trailing
285  * slash. Don't remove a leading slash, though.
286  */
288 
289  /*
290  * Remove duplicate adjacent separators
291  */
292  p = path;
293 #ifdef WIN32
294  /* Don't remove leading double-slash on Win32 */
295  if (*p)
296  p++;
297 #endif
298  to_p = p;
299  for (; *p; p++, to_p++)
300  {
301  /* Handle many adjacent slashes, like "/a///b" */
302  while (*p == '/' && was_sep)
303  p++;
304  if (to_p != p)
305  *to_p = *p;
306  was_sep = (*p == '/');
307  }
308  *to_p = '\0';
309 
310  /*
311  * Remove any trailing uses of "." and process ".." ourselves
312  *
313  * Note that "/../.." should reduce to just "/", while "../.." has to be
314  * kept as-is. In the latter case we put back mistakenly trimmed ".."
315  * components below. Also note that we want a Windows drive spec to be
316  * visible to trim_directory(), but it's not part of the logic that's
317  * looking at the name components; hence distinction between path and
318  * spath.
319  */
320  spath = skip_drive(path);
321  pending_strips = 0;
322  for (;;)
323  {
324  int len = strlen(spath);
325 
326  if (len >= 2 && strcmp(spath + len - 2, "/.") == 0)
327  trim_directory(path);
328  else if (strcmp(spath, ".") == 0)
329  {
330  /* Want to leave "." alone, but "./.." has to become ".." */
331  if (pending_strips > 0)
332  *spath = '\0';
333  break;
334  }
335  else if ((len >= 3 && strcmp(spath + len - 3, "/..") == 0) ||
336  strcmp(spath, "..") == 0)
337  {
338  trim_directory(path);
339  pending_strips++;
340  }
341  else if (pending_strips > 0 && *spath != '\0')
342  {
343  /* trim a regular directory name canceled by ".." */
344  trim_directory(path);
345  pending_strips--;
346  /* foo/.. should become ".", not empty */
347  if (*spath == '\0')
348  strcpy(spath, ".");
349  }
350  else
351  break;
352  }
353 
354  if (pending_strips > 0)
355  {
356  /*
357  * We could only get here if path is now totally empty (other than a
358  * possible drive specifier on Windows). We have to put back one or
359  * more ".."'s that we took off.
360  */
361  while (--pending_strips > 0)
362  strcat(path, "../");
363  strcat(path, "..");
364  }
365 }
static void trim_directory(char *path)
Definition: path.c:868
#define skip_drive(path)
Definition: path.c:78
static void trim_trailing_separator(char *path)
Definition: path.c:899
void cleanup_path ( char *  path)

Definition at line 185 of file path.c.

References MAXPGPATH.

Referenced by get_configdata().

186 {
187 #ifdef WIN32
188  char *ptr;
189 
190  /*
191  * GetShortPathName() will fail if the path does not exist, or short names
192  * are disabled on this file system. In both cases, we just return the
193  * original path. This is particularly useful for --sysconfdir, which
194  * might not exist.
195  */
196  GetShortPathName(path, path, MAXPGPATH - 1);
197 
198  /* Replace '\' with '/' */
199  for (ptr = path; *ptr; ptr++)
200  {
201  if (*ptr == '\\')
202  *ptr = '/';
203  }
204 #endif
205 }
#define MAXPGPATH
char* crypt ( const char *  key,
const char *  setting 
)

Referenced by chkpass_eq(), chkpass_in(), and chkpass_ne().

char* escape_single_quotes_ascii ( const char *  src)

Definition at line 33 of file quotes.c.

References i, malloc, NULL, result, and SQL_STR_DOUBLE.

Referenced by escape_quotes(), and write_auto_conf_file().

34 {
35  int len = strlen(src),
36  i,
37  j;
38  char *result = malloc(len * 2 + 1);
39 
40  if (!result)
41  return NULL;
42 
43  for (i = 0, j = 0; i < len; i++)
44  {
45  if (SQL_STR_DOUBLE(src[i], true))
46  result[j++] = src[i];
47  result[j++] = src[i];
48  }
49  result[j] = '\0';
50  return result;
51 }
return result
Definition: formatting.c:1632
#define malloc(a)
Definition: header.h:50
#define NULL
Definition: c.h:229
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:507
int find_my_exec ( const char *  argv0,
char *  retpath 
)

Definition at line 119 of file exec.c.

References _, canonicalize_path(), first_dir_separator(), first_path_var_separator(), is_absolute_path, join_path_components(), log_error, MAXPGPATH, Min, NULL, resolve_symlinks(), strerror(), StrNCpy, and validate_exec().

Referenced by find_other_exec(), find_other_exec_or_die(), getInstallationPaths(), InitStandaloneProcess(), main(), process_psqlrc(), set_pglocale_pgservice(), setup(), setup_bin_paths(), and syncTargetDirectory().

120 {
121  char cwd[MAXPGPATH],
122  test_path[MAXPGPATH];
123  char *path;
124 
125  if (!getcwd(cwd, MAXPGPATH))
126  {
127  log_error(_("could not identify current directory: %s"),
128  strerror(errno));
129  return -1;
130  }
131 
132  /*
133  * If argv0 contains a separator, then PATH wasn't used.
134  */
136  {
137  if (is_absolute_path(argv0))
138  StrNCpy(retpath, argv0, MAXPGPATH);
139  else
140  join_path_components(retpath, cwd, argv0);
141  canonicalize_path(retpath);
142 
143  if (validate_exec(retpath) == 0)
144  return resolve_symlinks(retpath);
145 
146  log_error(_("invalid binary \"%s\""), retpath);
147  return -1;
148  }
149 
150 #ifdef WIN32
151  /* Win32 checks the current directory first for names without slashes */
152  join_path_components(retpath, cwd, argv0);
153  if (validate_exec(retpath) == 0)
154  return resolve_symlinks(retpath);
155 #endif
156 
157  /*
158  * Since no explicit path was supplied, the user must have been relying on
159  * PATH. We'll search the same PATH.
160  */
161  if ((path = getenv("PATH")) && *path)
162  {
163  char *startp = NULL,
164  *endp = NULL;
165 
166  do
167  {
168  if (!startp)
169  startp = path;
170  else
171  startp = endp + 1;
172 
173  endp = first_path_var_separator(startp);
174  if (!endp)
175  endp = startp + strlen(startp); /* point to end */
176 
177  StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
178 
179  if (is_absolute_path(test_path))
180  join_path_components(retpath, test_path, argv0);
181  else
182  {
183  join_path_components(retpath, cwd, test_path);
184  join_path_components(retpath, retpath, argv0);
185  }
186  canonicalize_path(retpath);
187 
188  switch (validate_exec(retpath))
189  {
190  case 0: /* found ok */
191  return resolve_symlinks(retpath);
192  case -1: /* wasn't even a candidate, keep looking */
193  break;
194  case -2: /* found but disqualified */
195  log_error(_("could not read binary \"%s\""),
196  retpath);
197  break;
198  }
199  } while (*endp);
200  }
201 
202  log_error(_("could not find a \"%s\" to execute"), argv0);
203  return -1;
204 }
static char * argv0
Definition: pg_ctl.c:89
#define log_error(str, param)
Definition: exec.c:31
static int resolve_symlinks(char *path)
Definition: exec.c:219
#define Min(x, y)
Definition: c.h:806
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:58
#define is_absolute_path(filename)
Definition: port.h:77
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define NULL
Definition: c.h:229
#define StrNCpy(dst, src, len)
Definition: c.h:830
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
const char * strerror(int errnum)
Definition: strerror.c:19
#define _(x)
Definition: elog.c:84
char * first_path_var_separator(const char *pathlist)
Definition: path.c:120
int find_other_exec ( const char *  argv0,
const char *  target,
const char *  versionstr,
char *  retpath 
)

Definition at line 307 of file exec.c.

References canonicalize_path(), EXE, find_my_exec(), last_dir_separator(), MAXPGPATH, pipe_read_line(), snprintf(), and validate_exec().

Referenced by find_other_exec_or_die(), getInstallationPaths(), isolation_start_test(), main(), setup_bin_paths(), and syncTargetDirectory().

309 {
310  char cmd[MAXPGPATH];
311  char line[100];
312 
313  if (find_my_exec(argv0, retpath) < 0)
314  return -1;
315 
316  /* Trim off program name and keep just directory */
317  *last_dir_separator(retpath) = '\0';
318  canonicalize_path(retpath);
319 
320  /* Now append the other program's name */
321  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
322  "/%s%s", target, EXE);
323 
324  if (validate_exec(retpath) != 0)
325  return -1;
326 
327  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
328 
329  if (!pipe_read_line(cmd, line, sizeof(line)))
330  return -1;
331 
332  if (strcmp(line, versionstr) != 0)
333  return -2;
334 
335  return 0;
336 }
static char * argv0
Definition: pg_ctl.c:89
void canonicalize_path(char *path)
Definition: path.c:254
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:58
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define EXE
Definition: port.h:110
static char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:348
char* first_dir_separator ( const char *  filename)

Definition at line 103 of file path.c.

References IS_DIR_SEP, NULL, and skip_drive.

Referenced by check_restricted_library_name(), check_valid_extension_name(), check_valid_version_name(), expand_dynamic_library_name(), find_in_dynamic_libpath(), find_my_exec(), load_libraries(), and substitute_libpath_macro().

104 {
105  const char *p;
106 
107  for (p = skip_drive(filename); *p; p++)
108  if (IS_DIR_SEP(*p))
109  return (char *) p;
110  return NULL;
111 }
#define skip_drive(path)
Definition: path.c:78
#define IS_DIR_SEP(ch)
Definition: port.h:75
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:89
char* first_path_var_separator ( const char *  pathlist)

Definition at line 120 of file path.c.

References IS_PATH_VAR_SEP, and NULL.

Referenced by find_in_dynamic_libpath(), and find_my_exec().

121 {
122  const char *p;
123 
124  /* skip_drive is not needed */
125  for (p = pathlist; *p; p++)
126  if (IS_PATH_VAR_SEP(*p))
127  return (char *) p;
128  return NULL;
129 }
#define IS_PATH_VAR_SEP(ch)
Definition: path.c:42
#define NULL
Definition: c.h:229
int fls ( int  mask)

Definition at line 55 of file fls.c.

References bit().

Referenced by _hash_get_oldblock_from_newbucket().

56 {
57  int bit;
58 
59  if (mask == 0)
60  return (0);
61  for (bit = 1; mask != 1; bit++)
62  mask = (unsigned int) mask >> 1;
63  return (bit);
64 }
Datum bit(PG_FUNCTION_ARGS)
Definition: varbit.c:361
void get_doc_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 776 of file path.c.

References make_relative_path().

Referenced by get_configdata().

777 {
778  make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
779 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_etc_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 713 of file path.c.

References make_relative_path().

Referenced by get_configdata(), process_psqlrc(), and set_pglocale_pgservice().

714 {
715  make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
716 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
bool get_home_path ( char *  ret_path)

Definition at line 807 of file path.c.

References MAXPGPATH, NULL, pqGetpwuid(), snprintf(), and strlcpy().

Referenced by expand_tilde(), initializeInput(), and process_psqlrc().

808 {
809 #ifndef WIN32
810  char pwdbuf[BUFSIZ];
811  struct passwd pwdstr;
812  struct passwd *pwd = NULL;
813 
814  (void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
815  if (pwd == NULL)
816  return false;
817  strlcpy(ret_path, pwd->pw_dir, MAXPGPATH);
818  return true;
819 #else
820  char *tmppath;
821 
822  /*
823  * Note: We use getenv() here because the more modern SHGetFolderPath()
824  * would force the backend to link with shell32.lib, which eats valuable
825  * desktop heap. XXX This function is used only in psql, which already
826  * brings in shell32 via libpq. Moving this function to its own file
827  * would keep it out of the backend, freeing it from this concern.
828  */
829  tmppath = getenv("APPDATA");
830  if (!tmppath)
831  return false;
832  snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
833  return true;
834 #endif
835 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define MAXPGPATH
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:229
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:95
void get_html_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 785 of file path.c.

References make_relative_path().

Referenced by get_configdata().

786 {
787  make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
788 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_include_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 722 of file path.c.

References make_relative_path().

Referenced by get_configdata(), and main().

723 {
724  make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
725 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_includeserver_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 740 of file path.c.

References make_relative_path().

Referenced by get_configdata().

741 {
742  make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
743 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_lib_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 749 of file path.c.

References make_relative_path().

Referenced by get_configdata().

750 {
751  make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
752 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_locale_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 767 of file path.c.

References make_relative_path().

Referenced by get_configdata(), pg_bindtextdomain(), and set_pglocale_pgservice().

768 {
769  make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
770 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_man_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 794 of file path.c.

References make_relative_path().

Referenced by get_configdata().

795 {
796  make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
797 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_parent_directory ( char *  path)

Definition at line 854 of file path.c.

References trim_directory().

Referenced by destroy_tablespace_directories(), fsync_parent_path(), main(), process_file(), TablespaceCreateDbspace(), and tokenize_inc_file().

855 {
856  trim_directory(path);
857 }
static void trim_directory(char *path)
Definition: path.c:868
void get_pkginclude_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 731 of file path.c.

References make_relative_path().

Referenced by get_configdata(), and main().

732 {
733  make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
734 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_pkglib_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 758 of file path.c.

References make_relative_path().

Referenced by get_configdata(), getInstallationPaths(), and InitStandaloneProcess().

759 {
760  make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
761 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
const char* get_progname ( const char *  argv0)

Definition at line 453 of file path.c.

References EXE, last_dir_separator(), NULL, pg_strcasecmp(), progname, and skip_drive.

Referenced by get_opts(), handle_help_version_opts(), main(), parseCommandLine(), and regression_main().

454 {
455  const char *nodir_name;
456  char *progname;
457 
458  nodir_name = last_dir_separator(argv0);
459  if (nodir_name)
460  nodir_name++;
461  else
462  nodir_name = skip_drive(argv0);
463 
464  /*
465  * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
466  * called only once.
467  */
468  progname = strdup(nodir_name);
469  if (progname == NULL)
470  {
471  fprintf(stderr, "%s: out of memory\n", nodir_name);
472  abort(); /* This could exit the postmaster */
473  }
474 
475 #if defined(__CYGWIN__) || defined(WIN32)
476  /* strip ".exe" suffix, regardless of case */
477  if (strlen(progname) > sizeof(EXE) - 1 &&
478  pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
479  progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
480 #endif
481 
482  return progname;
483 }
static char * argv0
Definition: pg_ctl.c:89
#define skip_drive(path)
Definition: path.c:78
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * progname
Definition: pg_standby.c:37
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define NULL
Definition: c.h:229
#define EXE
Definition: port.h:110
void get_share_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 704 of file path.c.

References make_relative_path().

Referenced by get_configdata(), get_extension_control_directory(), get_extension_control_filename(), get_extension_script_directory(), get_tsearch_config_filename(), ParseTzFile(), pg_TZDIR(), and setup_bin_paths().

705 {
706  make_relative_path(ret_path, PGSHAREDIR, PGBINDIR, my_exec_path);
707 }
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:539
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
int getpeereid ( int  sock,
uid_t uid,
gid_t gid 
)

Definition at line 35 of file getpeereid.c.

References NULL.

Referenced by PQconnectPoll().

36 {
37 #if defined(SO_PEERCRED)
38  /* Linux: use getsockopt(SO_PEERCRED) */
39  struct ucred peercred;
40  ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
41 
42  if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
43  so_len != sizeof(peercred))
44  return -1;
45  *uid = peercred.uid;
46  *gid = peercred.gid;
47  return 0;
48 #elif defined(LOCAL_PEERCRED)
49  /* Debian with FreeBSD kernel: use getsockopt(LOCAL_PEERCRED) */
50  struct xucred peercred;
51  ACCEPT_TYPE_ARG3 so_len = sizeof(peercred);
52 
53  if (getsockopt(sock, 0, LOCAL_PEERCRED, &peercred, &so_len) != 0 ||
54  so_len != sizeof(peercred) ||
55  peercred.cr_version != XUCRED_VERSION)
56  return -1;
57  *uid = peercred.cr_uid;
58  *gid = peercred.cr_gid;
59  return 0;
60 #elif defined(HAVE_GETPEERUCRED)
61  /* Solaris: use getpeerucred() */
62  ucred_t *ucred;
63 
64  ucred = NULL; /* must be initialized to NULL */
65  if (getpeerucred(sock, &ucred) == -1)
66  return -1;
67 
68  *uid = ucred_geteuid(ucred);
69  *gid = ucred_getegid(ucred);
70  ucred_free(ucred);
71 
72  if (*uid == (uid_t) (-1) || *gid == (gid_t) (-1))
73  return -1;
74  return 0;
75 #else
76  /* No implementation available on this platform */
77  errno = ENOSYS;
78  return -1;
79 #endif
80 }
int gid_t
Definition: win32.h:251
int uid_t
Definition: win32.h:250
#define NULL
Definition: c.h:229
bool has_drive_prefix ( const char *  filename)

Definition at line 87 of file path.c.

References skip_drive.

Referenced by process_file().

88 {
89 #ifdef WIN32
90  return skip_drive(path) != path;
91 #else
92  return false;
93 #endif
94 }
#define skip_drive(path)
Definition: path.c:78
int inet_aton ( const char *  cp,
struct in_addr *  addr 
)

Definition at line 54 of file inet_aton.c.

References val.

Referenced by getaddrinfo().

55 {
56  unsigned int val;
57  int base,
58  n;
59  char c;
60  u_int parts[4];
61  u_int *pp = parts;
62 
63  for (;;)
64  {
65  /*
66  * Collect number up to ``.''. Values are specified as for C: 0x=hex,
67  * 0=octal, other=decimal.
68  */
69  val = 0;
70  base = 10;
71  if (*cp == '0')
72  {
73  if (*++cp == 'x' || *cp == 'X')
74  base = 16, cp++;
75  else
76  base = 8;
77  }
78  while ((c = *cp) != '\0')
79  {
80  if (isdigit((unsigned char) c))
81  {
82  val = (val * base) + (c - '0');
83  cp++;
84  continue;
85  }
86  if (base == 16 && isxdigit((unsigned char) c))
87  {
88  val = (val << 4) +
89  (c + 10 - (islower((unsigned char) c) ? 'a' : 'A'));
90  cp++;
91  continue;
92  }
93  break;
94  }
95  if (*cp == '.')
96  {
97  /*
98  * Internet format: a.b.c.d a.b.c (with c treated as 16-bits)
99  * a.b (with b treated as 24 bits)
100  */
101  if (pp >= parts + 3 || val > 0xff)
102  return 0;
103  *pp++ = val, cp++;
104  }
105  else
106  break;
107  }
108 
109  /*
110  * Check for trailing junk.
111  */
112  while (*cp)
113  if (!isspace((unsigned char) *cp++))
114  return 0;
115 
116  /*
117  * Concoct the address according to the number of parts specified.
118  */
119  n = pp - parts + 1;
120  switch (n)
121  {
122 
123  case 1: /* a -- 32 bits */
124  break;
125 
126  case 2: /* a.b -- 8.24 bits */
127  if (val > 0xffffff)
128  return 0;
129  val |= parts[0] << 24;
130  break;
131 
132  case 3: /* a.b.c -- 8.8.16 bits */
133  if (val > 0xffff)
134  return 0;
135  val |= (parts[0] << 24) | (parts[1] << 16);
136  break;
137 
138  case 4: /* a.b.c.d -- 8.8.8.8 bits */
139  if (val > 0xff)
140  return 0;
141  val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
142  break;
143  }
144  if (addr)
145  addr->s_addr = htonl(val);
146  return 1;
147 }
char * c
long val
Definition: informix.c:689
char* inet_net_ntop ( int  af,
const void *  src,
int  bits,
char *  dst,
size_t  size 
)

Definition at line 77 of file inet_net_ntop.c.

References EAFNOSUPPORT, inet_net_ntop_ipv4(), inet_net_ntop_ipv6(), NULL, PGSQL_AF_INET, and PGSQL_AF_INET6.

Referenced by connectFailureMessage(), getnameinfo(), inet_abbrev(), network_host(), network_out(), and network_show().

78 {
79  /*
80  * We need to cover both the address family constants used by the PG inet
81  * type (PGSQL_AF_INET and PGSQL_AF_INET6) and those used by the system
82  * libraries (AF_INET and AF_INET6). We can safely assume PGSQL_AF_INET
83  * == AF_INET, but the INET6 constants are very likely to be different. If
84  * AF_INET6 isn't defined, silently ignore it.
85  */
86  switch (af)
87  {
88  case PGSQL_AF_INET:
89  return (inet_net_ntop_ipv4(src, bits, dst, size));
90  case PGSQL_AF_INET6:
91 #if defined(AF_INET6) && AF_INET6 != PGSQL_AF_INET6
92  case AF_INET6:
93 #endif
94  return (inet_net_ntop_ipv6(src, bits, dst, size));
95  default:
96  errno = EAFNOSUPPORT;
97  return (NULL);
98  }
99 }
#define PGSQL_AF_INET
Definition: inet.h:39
#define PGSQL_AF_INET6
Definition: inet.h:40
static char * inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size)
#define EAFNOSUPPORT
Definition: win32.h:289
#define NULL
Definition: c.h:229
static char * inet_net_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size)
void join_path_components ( char *  ret_path,
const char *  head,
const char *  tail 
)

Definition at line 218 of file path.c.

References IS_DIR_SEP, MAXPGPATH, skip_drive, snprintf(), and strlcpy().

Referenced by find_my_exec(), main(), make_relative_path(), process_file(), resolve_symlinks(), and tokenize_inc_file().

220 {
221  if (ret_path != head)
222  strlcpy(ret_path, head, MAXPGPATH);
223 
224  /*
225  * Remove any leading "." in the tail component.
226  *
227  * Note: we used to try to remove ".." as well, but that's tricky to get
228  * right; now we just leave it to be done by canonicalize_path() later.
229  */
230  while (tail[0] == '.' && IS_DIR_SEP(tail[1]))
231  tail += 2;
232 
233  if (*tail)
234  {
235  /* only separate with slash if head wasn't empty */
236  snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
237  "%s%s",
238  (*(skip_drive(head)) != '\0') ? "/" : "",
239  tail);
240  }
241 }
#define skip_drive(path)
Definition: path.c:78
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define IS_DIR_SEP(ch)
Definition: port.h:75
#define MAXPGPATH
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char* last_dir_separator ( const char *  filename)

Definition at line 138 of file path.c.

References IS_DIR_SEP, NULL, and skip_drive.

Referenced by ECPGconnect(), find_other_exec(), get_progname(), main(), resolve_symlinks(), setup(), and setup_bin_paths().

139 {
140  const char *p,
141  *ret = NULL;
142 
143  for (p = skip_drive(filename); *p; p++)
144  if (IS_DIR_SEP(*p))
145  ret = p;
146  return (char *) ret;
147 }
#define skip_drive(path)
Definition: path.c:78
#define IS_DIR_SEP(ch)
Definition: port.h:75
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:89
char* make_absolute_path ( const char *  path)

Definition at line 608 of file path.c.

References _, buf, canonicalize_path(), elog, ereport, errcode(), errmsg(), ERROR, free, is_absolute_path, malloc, MAXPGPATH, NULL, and strerror().

Referenced by regression_main(), SelectConfigFiles(), and SetDataDir().

609 {
610  char *new;
611 
612  /* Returning null for null input is convenient for some callers */
613  if (path == NULL)
614  return NULL;
615 
616  if (!is_absolute_path(path))
617  {
618  char *buf;
619  size_t buflen;
620 
621  buflen = MAXPGPATH;
622  for (;;)
623  {
624  buf = malloc(buflen);
625  if (!buf)
626  {
627 #ifndef FRONTEND
628  ereport(ERROR,
629  (errcode(ERRCODE_OUT_OF_MEMORY),
630  errmsg("out of memory")));
631 #else
632  fprintf(stderr, _("out of memory\n"));
633  return NULL;
634 #endif
635  }
636 
637  if (getcwd(buf, buflen))
638  break;
639  else if (errno == ERANGE)
640  {
641  free(buf);
642  buflen *= 2;
643  continue;
644  }
645  else
646  {
647  int save_errno = errno;
648 
649  free(buf);
650  errno = save_errno;
651 #ifndef FRONTEND
652  elog(ERROR, "could not get current working directory: %m");
653 #else
654  fprintf(stderr, _("could not get current working directory: %s\n"),
655  strerror(errno));
656  return NULL;
657 #endif
658  }
659  }
660 
661  new = malloc(strlen(buf) + strlen(path) + 2);
662  if (!new)
663  {
664  free(buf);
665 #ifndef FRONTEND
666  ereport(ERROR,
667  (errcode(ERRCODE_OUT_OF_MEMORY),
668  errmsg("out of memory")));
669 #else
670  fprintf(stderr, _("out of memory\n"));
671  return NULL;
672 #endif
673  }
674  sprintf(new, "%s/%s", buf, path);
675  free(buf);
676  }
677  else
678  {
679  new = strdup(path);
680  if (!new)
681  {
682 #ifndef FRONTEND
683  ereport(ERROR,
684  (errcode(ERRCODE_OUT_OF_MEMORY),
685  errmsg("out of memory")));
686 #else
687  fprintf(stderr, _("out of memory\n"));
688  return NULL;
689 #endif
690  }
691  }
692 
693  /* Make sure punctuation is canonical, too */
694  canonicalize_path(new);
695 
696  return new;
697 }
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:575
#define malloc(a)
Definition: header.h:50
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:66
#define is_absolute_path(filename)
Definition: port.h:77
#define ereport(elevel, rest)
Definition: elog.h:122
#define free(a)
Definition: header.h:65
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * strerror(int errnum)
Definition: strerror.c:19
#define elog
Definition: elog.h:219
#define _(x)
Definition: elog.c:84
void make_native_path ( char *  path)

Definition at line 166 of file path.c.

Referenced by pgarch_archiveXlog(), and RestoreArchivedFile().

167 {
168 #ifdef WIN32
169  char *p;
170 
171  for (p = filename; *p; p++)
172  if (*p == '/')
173  *p = '\\';
174 #endif
175 }
static char * filename
Definition: pg_dumpall.c:89
char* mkdtemp ( char *  path)

Definition at line 286 of file mkdtemp.c.

References _DIAGASSERT, GETTEMP(), and NULL.

287 {
288  _DIAGASSERT(path != NULL);
289 
290  return GETTEMP(path, NULL, 1) ? path : NULL;
291 }
#define _DIAGASSERT(x)
Definition: mkdtemp.c:21
#define NULL
Definition: c.h:229
static int GETTEMP(char *path, int *doopen, int domkdir)
Definition: mkdtemp.c:94
bool path_contains_parent_reference ( const char *  path)

Definition at line 376 of file path.c.

References NULL, and skip_drive.

Referenced by convert_and_check_filename(), and path_is_relative_and_below_cwd().

377 {
378  int path_len;
379 
380  path = skip_drive(path); /* C: shouldn't affect our conclusion */
381 
382  path_len = strlen(path);
383 
384  /*
385  * ".." could be the whole path; otherwise, if it's present it must be at
386  * the beginning, in the middle, or at the end.
387  */
388  if (strcmp(path, "..") == 0 ||
389  strncmp(path, "../", 3) == 0 ||
390  strstr(path, "/../") != NULL ||
391  (path_len >= 3 && strcmp(path + path_len - 3, "/..") == 0))
392  return true;
393 
394  return false;
395 }
#define skip_drive(path)
Definition: path.c:78
#define NULL
Definition: c.h:229
bool path_is_prefix_of_path ( const char *  path1,
const char *  path2 
)

Definition at line 438 of file path.c.

References IS_DIR_SEP.

Referenced by convert_and_check_filename(), create_script_for_old_cluster_deletion(), CreateTableSpace(), and parseCommandLine().

439 {
440  int path1_len = strlen(path1);
441 
442  if (strncmp(path1, path2, path1_len) == 0 &&
443  (IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
444  return true;
445  return false;
446 }
#define IS_DIR_SEP(ch)
Definition: port.h:75
bool path_is_relative_and_below_cwd ( const char *  path)

Definition at line 405 of file path.c.

References is_absolute_path, IS_DIR_SEP, and path_contains_parent_reference().

Referenced by convert_and_check_filename().

406 {
407  if (is_absolute_path(path))
408  return false;
409  /* don't allow anything above the cwd */
410  else if (path_contains_parent_reference(path))
411  return false;
412 #ifdef WIN32
413 
414  /*
415  * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
416  * relative to the cwd on that drive, or the drive's root directory if
417  * that drive has no cwd. Because the path itself cannot tell us which is
418  * the case, we have to assume the worst, i.e. that it is not below the
419  * cwd. We could use GetFullPathName() to find the full path but that
420  * could change if the current directory for the drive changes underneath
421  * us, so we just disallow it.
422  */
423  else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
424  !IS_DIR_SEP(path[2]))
425  return false;
426 #endif
427  else
428  return true;
429 }
#define IS_DIR_SEP(ch)
Definition: port.h:75
bool path_contains_parent_reference(const char *path)
Definition: path.c:376
#define is_absolute_path(filename)
Definition: port.h:77
int pclose_check ( FILE *  stream)

Definition at line 510 of file exec.c.

References _, free, log_error, pfree(), strerror(), and wait_result_to_str().

Referenced by pipe_read_line().

511 {
512  int exitstatus;
513  char *reason;
514 
515  exitstatus = pclose(stream);
516 
517  if (exitstatus == 0)
518  return 0; /* all is well */
519 
520  if (exitstatus == -1)
521  {
522  /* pclose() itself failed, and hopefully set errno */
523  log_error(_("pclose failed: %s"), strerror(errno));
524  }
525  else
526  {
527  reason = wait_result_to_str(exitstatus);
528  log_error("%s", reason);
529 #ifdef FRONTEND
530  free(reason);
531 #else
532  pfree(reason);
533 #endif
534  }
535  return exitstatus;
536 }
#define log_error(str, param)
Definition: exec.c:31
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
void pfree(void *pointer)
Definition: mcxt.c:950
#define free(a)
Definition: header.h:65
const char * strerror(int errnum)
Definition: strerror.c:19
#define _(x)
Definition: elog.c:84
unsigned char pg_ascii_tolower ( unsigned char  ch)

Definition at line 146 of file pgstrcasecmp.c.

Referenced by asc_initcap(), asc_tolower(), pg_wc_tolower(), and SB_lower_char().

147 {
148  if (ch >= 'A' && ch <= 'Z')
149  ch += 'a' - 'A';
150  return ch;
151 }
unsigned char pg_ascii_toupper ( unsigned char  ch)

Definition at line 135 of file pgstrcasecmp.c.

Referenced by asc_initcap(), asc_toupper(), filter_list_to_array(), and pg_wc_toupper().

136 {
137  if (ch >= 'a' && ch <= 'z')
138  ch += 'A' - 'a';
139  return ch;
140 }
int pg_check_dir ( const char *  dir)

Definition at line 31 of file pgcheckdir.c.

References closedir(), dirent::d_name, NULL, opendir(), readdir(), and result.

Referenced by create_data_directory(), create_xlog_or_symlink(), main(), and verify_dir_is_empty_or_create().

32 {
33  int result = 1;
34  DIR *chkdir;
35  struct dirent *file;
36  bool dot_found = false;
37  bool mount_found = false;
38  int readdir_errno;
39 
40  chkdir = opendir(dir);
41  if (chkdir == NULL)
42  return (errno == ENOENT) ? 0 : -1;
43 
44  while (errno = 0, (file = readdir(chkdir)) != NULL)
45  {
46  if (strcmp(".", file->d_name) == 0 ||
47  strcmp("..", file->d_name) == 0)
48  {
49  /* skip this and parent directory */
50  continue;
51  }
52 #ifndef WIN32
53  /* file starts with "." */
54  else if (file->d_name[0] == '.')
55  {
56  dot_found = true;
57  }
58  /* lost+found directory */
59  else if (strcmp("lost+found", file->d_name) == 0)
60  {
61  mount_found = true;
62  }
63 #endif
64  else
65  {
66  result = 4; /* not empty */
67  break;
68  }
69  }
70 
71  if (errno)
72  result = -1; /* some kind of I/O error? */
73 
74  /* Close chkdir and avoid overwriting the readdir errno on success */
75  readdir_errno = errno;
76  if (closedir(chkdir))
77  result = -1; /* error executing closedir */
78  else
79  errno = readdir_errno;
80 
81  /* We report on mount point if we find a lost+found directory */
82  if (result == 1 && mount_found)
83  result = 3;
84 
85  /* We report on dot-files if we _only_ find dot files */
86  if (result == 1 && dot_found)
87  result = 2;
88 
89  return result;
90 }
int closedir(DIR *)
Definition: dirent.c:113
return result
Definition: formatting.c:1632
Definition: dirent.h:9
Definition: dirent.c:25
DIR * opendir(const char *)
Definition: dirent.c:33
#define NULL
Definition: c.h:229
struct dirent * readdir(DIR *)
Definition: dirent.c:78
char d_name[MAX_PATH]
Definition: dirent.h:14
double pg_erand48 ( unsigned short  xseed[3])

Definition at line 79 of file erand48.c.

References _dorand48().

Referenced by doLog(), geqo_rand(), getExponentialRand(), getGaussianRand(), getPoissonRand(), getrand(), and sampler_random_fract().

80 {
81  _dorand48(xseed);
82  return ldexp((double) xseed[0], -48) +
83  ldexp((double) xseed[1], -32) +
84  ldexp((double) xseed[2], -16);
85 }
static void _dorand48(unsigned short xseed[3])
Definition: erand48.c:58
int pg_get_encoding_from_locale ( const char *  ctype,
bool  write_message 
)
long pg_jrand48 ( unsigned short  xseed[3])

Definition at line 95 of file erand48.c.

References _dorand48().

Referenced by pg_backend_random(), pg_frontend_random(), and RandomCancelKey().

96 {
97  _dorand48(xseed);
98  return ((long) xseed[2] << 16) + ((long) xseed[1]);
99 }
static void _dorand48(unsigned short xseed[3])
Definition: erand48.c:58
long pg_lrand48 ( void  )

Definition at line 88 of file erand48.c.

References _dorand48(), and _rand48_seed.

Referenced by random().

89 {
91  return ((long) _rand48_seed[2] << 15) + ((long) _rand48_seed[1] >> 1);
92 }
static unsigned short _rand48_seed[3]
Definition: erand48.c:44
static void _dorand48(unsigned short xseed[3])
Definition: erand48.c:58
int pg_mkdir_p ( char *  path,
int  omode 
)

Definition at line 57 of file pgmkdirp.c.

References mkdir, NULL, S_IRWXG, and S_IRWXO.

Referenced by create_data_directory(), create_xlog_or_symlink(), StartLogStreamer(), and verify_dir_is_empty_or_create().

58 {
59  struct stat sb;
60  mode_t numask,
61  oumask;
62  int last,
63  retval;
64  char *p;
65 
66  retval = 0;
67  p = path;
68 
69 #ifdef WIN32
70  /* skip network and drive specifiers for win32 */
71  if (strlen(p) >= 2)
72  {
73  if (p[0] == '/' && p[1] == '/')
74  {
75  /* network drive */
76  p = strstr(p + 2, "/");
77  if (p == NULL)
78  {
79  errno = EINVAL;
80  return -1;
81  }
82  }
83  else if (p[1] == ':' &&
84  ((p[0] >= 'a' && p[0] <= 'z') ||
85  (p[0] >= 'A' && p[0] <= 'Z')))
86  {
87  /* local drive */
88  p += 2;
89  }
90  }
91 #endif
92 
93  /*
94  * POSIX 1003.2: For each dir operand that does not name an existing
95  * directory, effects equivalent to those caused by the following command
96  * shall occur:
97  *
98  * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode] dir
99  *
100  * We change the user's umask and then restore it, instead of doing
101  * chmod's. Note we assume umask() can't change errno.
102  */
103  oumask = umask(0);
104  numask = oumask & ~(S_IWUSR | S_IXUSR);
105  (void) umask(numask);
106 
107  if (p[0] == '/') /* Skip leading '/'. */
108  ++p;
109  for (last = 0; !last; ++p)
110  {
111  if (p[0] == '\0')
112  last = 1;
113  else if (p[0] != '/')
114  continue;
115  *p = '\0';
116  if (!last && p[1] == '\0')
117  last = 1;
118 
119  if (last)
120  (void) umask(oumask);
121 
122  /* check for pre-existing directory */
123  if (stat(path, &sb) == 0)
124  {
125  if (!S_ISDIR(sb.st_mode))
126  {
127  if (last)
128  errno = EEXIST;
129  else
130  errno = ENOTDIR;
131  retval = -1;
132  break;
133  }
134  }
135  else if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
136  {
137  retval = -1;
138  break;
139  }
140  if (!last)
141  *p = '/';
142  }
143 
144  /* ensure we restored umask */
145  (void) umask(oumask);
146 
147  return retval;
148 }
#define mkdir(a, b)
Definition: win32.h:57
#define S_IRWXO
Definition: win32.h:455
#define NULL
Definition: c.h:229
#define S_IRWXG
Definition: win32.h:451
void pg_qsort ( void *  base,
size_t  nel,
size_t  elsize,
int(*)(const void *, const void *)  cmp 
)

Definition at line 113 of file qsort.c.

References cmp(), med3(), Min, swap, SWAPINIT, and vecswap.

Referenced by DropRelFileNodesAllBuffers(), and InitCatalogCache().

114 {
115  char *pa,
116  *pb,
117  *pc,
118  *pd,
119  *pl,
120  *pm,
121  *pn;
122  size_t d1,
123  d2;
124  int r,
125  swaptype,
126  presorted;
127 
128 loop:SWAPINIT(a, es);
129  if (n < 7)
130  {
131  for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
132  for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
133  pl -= es)
134  swap(pl, pl - es);
135  return;
136  }
137  presorted = 1;
138  for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
139  {
140  if (cmp(pm - es, pm) > 0)
141  {
142  presorted = 0;
143  break;
144  }
145  }
146  if (presorted)
147  return;
148  pm = (char *) a + (n / 2) * es;
149  if (n > 7)
150  {
151  pl = (char *) a;
152  pn = (char *) a + (n - 1) * es;
153  if (n > 40)
154  {
155  size_t d = (n / 8) * es;
156 
157  pl = med3(pl, pl + d, pl + 2 * d, cmp);
158  pm = med3(pm - d, pm, pm + d, cmp);
159  pn = med3(pn - 2 * d, pn - d, pn, cmp);
160  }
161  pm = med3(pl, pm, pn, cmp);
162  }
163  swap(a, pm);
164  pa = pb = (char *) a + es;
165  pc = pd = (char *) a + (n - 1) * es;
166  for (;;)
167  {
168  while (pb <= pc && (r = cmp(pb, a)) <= 0)
169  {
170  if (r == 0)
171  {
172  swap(pa, pb);
173  pa += es;
174  }
175  pb += es;
176  }
177  while (pb <= pc && (r = cmp(pc, a)) >= 0)
178  {
179  if (r == 0)
180  {
181  swap(pc, pd);
182  pd -= es;
183  }
184  pc -= es;
185  }
186  if (pb > pc)
187  break;
188  swap(pb, pc);
189  pb += es;
190  pc -= es;
191  }
192  pn = (char *) a + n * es;
193  d1 = Min(pa - (char *) a, pb - pa);
194  vecswap(a, pb - d1, d1);
195  d1 = Min(pd - pc, pn - pd - es);
196  vecswap(pb, pn - d1, d1);
197  d1 = pb - pa;
198  d2 = pd - pc;
199  if (d1 <= d2)
200  {
201  /* Recurse on left partition, then iterate on right partition */
202  if (d1 > es)
203  pg_qsort(a, d1 / es, es, cmp);
204  if (d2 > es)
205  {
206  /* Iterate rather than recurse to save stack space */
207  /* pg_qsort(pn - d2, d2 / es, es, cmp); */
208  a = pn - d2;
209  n = d2 / es;
210  goto loop;
211  }
212  }
213  else
214  {
215  /* Recurse on right partition, then iterate on left partition */
216  if (d2 > es)
217  pg_qsort(pn - d2, d2 / es, es, cmp);
218  if (d1 > es)
219  {
220  /* Iterate rather than recurse to save stack space */
221  /* pg_qsort(a, d1 / es, es, cmp); */
222  n = d1 / es;
223  goto loop;
224  }
225  }
226 }
#define swap(a, b)
Definition: qsort.c:94
void pg_qsort(void *a, size_t n, size_t es, int(*cmp)(const void *, const void *))
Definition: qsort.c:113
#define Min(x, y)
Definition: c.h:806
static char * med3(char *a, char *b, char *c, int(*cmp)(const void *, const void *))
Definition: qsort.c:105
#define SWAPINIT(a, es)
Definition: qsort.c:82
#define vecswap(a, b, n)
Definition: qsort.c:102
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:742
int pg_qsort_strcmp ( const void *  a,
const void *  b 
)

Definition at line 232 of file qsort.c.

Referenced by BuildEventTriggerCache(), filter_event_trigger(), readstoplist(), and searchstoplist().

233 {
234  return strcmp(*(const char *const *) a, *(const char *const *) b);
235 }
bool pg_set_block ( pgsocket  sock)

Definition at line 49 of file noblock.c.

50 {
51 #if !defined(WIN32)
52  int flags;
53 
54  flags = fcntl(sock, F_GETFL);
55  if (flags < 0)
56  return false;
57  if (fcntl(sock, F_SETFL, (flags & ~O_NONBLOCK)) == -1)
58  return false;
59  return true;
60 #else
61  unsigned long ioctlsocket_ret = 0;
62 
63  /* Returns non-0 on failure, while fcntl() returns -1 on failure */
64  return (ioctlsocket(sock, FIONBIO, &ioctlsocket_ret) == 0);
65 #endif
66 }
bool pg_set_noblock ( pgsocket  sock)

Definition at line 25 of file noblock.c.

Referenced by pgstat_init(), pq_init(), PQconnectPoll(), and report_fork_failure_to_client().

26 {
27 #if !defined(WIN32)
28  int flags;
29 
30  flags = fcntl(sock, F_GETFL);
31  if (flags < 0)
32  return false;
33  if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) == -1)
34  return false;
35  return true;
36 #else
37  unsigned long ioctlsocket_ret = 1;
38 
39  /* Returns non-0 on failure, while fcntl() returns -1 on failure */
40  return (ioctlsocket(sock, FIONBIO, &ioctlsocket_ret) == 0);
41 #endif
42 }
void pg_srand48 ( long  seed)

Definition at line 102 of file erand48.c.

References _rand48_add, _rand48_mult, _rand48_seed, RAND48_ADD, RAND48_MULT_0, RAND48_MULT_1, RAND48_MULT_2, and RAND48_SEED_0.

Referenced by srandom().

103 {
105  _rand48_seed[1] = (unsigned short) seed;
106  _rand48_seed[2] = (unsigned short) (seed >> 16);
111 }
static unsigned short _rand48_seed[3]
Definition: erand48.c:44
#define RAND48_SEED_0
Definition: erand48.c:36
#define RAND48_ADD
Definition: erand48.c:42
static unsigned short _rand48_mult[3]
Definition: erand48.c:49
static unsigned short _rand48_add
Definition: erand48.c:54
#define RAND48_MULT_1
Definition: erand48.c:40
#define RAND48_MULT_2
Definition: erand48.c:41
#define RAND48_MULT_0
Definition: erand48.c:39
int pg_strcasecmp ( const char *  s1,
const char *  s2 
)

Definition at line 36 of file pgstrcasecmp.c.

References IS_HIGHBIT_SET.

Referenced by AlterOperator(), AlterTSDictionary(), array_out(), ATExecSetRelOptions(), ATExecSetStorage(), build_startup_packet(), check_datestyle(), check_ddl_tag(), check_ident_usermap(), check_log_destination(), check_table_rewrite_ddl_tag(), check_usermap(), check_wal_consistency_checking(), comp_keyword_case_hook(), compute_attributes_with_style(), config_enum_lookup_by_name(), convert_any_priv_string(), convert_priv_string(), defGetBoolean(), defGetTypeLength(), DefineAggregate(), DefineCollation(), DefineOperator(), DefineRange(), DefineTSConfiguration(), DefineTSDictionary(), DefineTSParser(), DefineTSTemplate(), DefineType(), DefineView(), dintdict_init(), dispell_init(), do_pset(), doCustom(), dsimple_init(), dsnowball_init(), dsynonym_init(), dumpFunc(), dxsyn_init(), echo_hidden_hook(), echo_hook(), equivalent_locale(), evaluateSleep(), exec_command(), fillRelOptions(), find_matching_ts_config(), findTTStatus(), get_progname(), helpSQL(), histcontrol_hook(), hostname_match(), interpretOidsOption(), locate_stem_module(), lookup_prop_name(), main(), makeAlterConfigCommand(), on_error_rollback_hook(), parse_hstore(), parse_slash_copy(), parseArchiveFormat(), parseNameAndArgTypes(), ParseVariableBool(), pg_fe_sendauth(), pg_find_encoding(), pg_get_functiondef(), pg_size_bytes(), pg_stat_get_progress_info(), pgp_get_cipher_code(), pgp_get_digest_code(), PGTYPEStimestamp_defmt_scan(), plperl_trigger_handler(), plpgsql_extra_checks_check_hook(), PLy_exec_trigger(), pqSetenvPoll(), process_backslash_command(), prsd_headline(), px_find_digest(), px_gen_salt(), px_resolve_alias(), ReadArrayStr(), show_context_hook(), splitTzLine(), SyncRepGetStandbyPriority(), thesaurus_init(), transformCreateStmt(), transformPartitionSpec(), transformRelOptions(), unaccent_init(), validate_exec(), validateWithCheckOption(), verbosity_hook(), verify_peer_name_matches_certificate_name(), wildcard_certificate_match(), and xmlpi().

37 {
38  for (;;)
39  {
40  unsigned char ch1 = (unsigned char) *s1++;
41  unsigned char ch2 = (unsigned char) *s2++;
42 
43  if (ch1 != ch2)
44  {
45  if (ch1 >= 'A' && ch1 <= 'Z')
46  ch1 += 'a' - 'A';
47  else if (IS_HIGHBIT_SET(ch1) && isupper(ch1))
48  ch1 = tolower(ch1);
49 
50  if (ch2 >= 'A' && ch2 <= 'Z')
51  ch2 += 'a' - 'A';
52  else if (IS_HIGHBIT_SET(ch2) && isupper(ch2))
53  ch2 = tolower(ch2);
54 
55  if (ch1 != ch2)
56  return (int) ch1 - (int) ch2;
57  }
58  if (ch1 == 0)
59  break;
60  }
61  return 0;
62 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
char * s1
char * s2
int pg_strncasecmp ( const char *  s1,
const char *  s2,
size_t  n 
)

Definition at line 69 of file pgstrcasecmp.c.

References IS_HIGHBIT_SET.

Referenced by AlterTableGetRelOptionsLockLevel(), check_datestyle(), check_ddl_tag(), check_special_value(), check_timezone(), command_no_begin(), do_pset(), equivalent_locale(), float4in(), float8in_internal(), helpSQL(), is_select_command(), MainLoop(), map_sql_identifier_to_xml_name(), numeric_in(), parse_bool_with_len(), parseRelOptions(), ParseTzFile(), ParseVariableBool(), range_parse(), scan_directory_ci(), set_unicode_line_style(), set_var_from_str(), SpecialTags(), and transformRelOptions().

70 {
71  while (n-- > 0)
72  {
73  unsigned char ch1 = (unsigned char) *s1++;
74  unsigned char ch2 = (unsigned char) *s2++;
75 
76  if (ch1 != ch2)
77  {
78  if (ch1 >= 'A' && ch1 <= 'Z')
79  ch1 += 'a' - 'A';
80  else if (IS_HIGHBIT_SET(ch1) && isupper(ch1))
81  ch1 = tolower(ch1);
82 
83  if (ch2 >= 'A' && ch2 <= 'Z')
84  ch2 += 'a' - 'A';
85  else if (IS_HIGHBIT_SET(ch2) && isupper(ch2))
86  ch2 = tolower(ch2);
87 
88  if (ch1 != ch2)
89  return (int) ch1 - (int) ch2;
90  }
91  if (ch1 == 0)
92  break;
93  }
94  return 0;
95 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
char * s1
char * s2
unsigned char pg_tolower ( unsigned char  ch)

Definition at line 122 of file pgstrcasecmp.c.

References IS_HIGHBIT_SET.

Referenced by dir_strcmp(), ParseDateTime(), PGTYPESdate_defmt_asc(), PQfnumber(), processSQLNamePattern(), SB_lower_char(), seq_search(), str_initcap(), str_tolower(), and validateTzEntry().

123 {
124  if (ch >= 'A' && ch <= 'Z')
125  ch += 'a' - 'A';
126  else if (IS_HIGHBIT_SET(ch) && isupper(ch))
127  ch = tolower(ch);
128  return ch;
129 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
unsigned char pg_toupper ( unsigned char  ch)

Definition at line 105 of file pgstrcasecmp.c.

References IS_HIGHBIT_SET.

Referenced by cash_words(), DetermineTimeZoneAbbrevOffsetInternal(), pg_timezone_abbrevs(), pg_tzset(), seq_search(), str_initcap(), and str_toupper().

106 {
107  if (ch >= 'a' && ch <= 'z')
108  ch += 'A' - 'a';
109  else if (IS_HIGHBIT_SET(ch) && islower(ch))
110  ch = toupper(ch);
111  return ch;
112 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:973
void pg_usleep ( long  microsec)

Definition at line 53 of file signal.c.

References EINTR, FALSE, NULL, pgwin32_dispatch_queued_signals(), pgwin32_signal_event, and select.

Referenced by auth_delay_checks(), AutoVacLauncherMain(), AutoVacWorkerMain(), backend_read_statsfile(), BackendInitialize(), BackgroundWriterMain(), CheckpointerMain(), CheckpointWriteDelay(), CountOtherDBBackends(), CreateCheckPoint(), CustomizableNextWALFileReady(), do_pg_stop_backup(), do_promote(), do_restart(), do_stop(), do_watch(), exec_prog(), FileRead(), FileWrite(), ForgetDatabaseFsyncRequests(), ForgetRelationFsyncRequests(), GetMultiXactIdMembers(), InitPostgres(), lazy_truncate_heap(), main(), perform_spin_delay(), pgarch_ArchiverCopyLoop(), pgwin32_recv(), read_local_xlog_page(), recoveryPausesHere(), register_unlink(), regression_main(), RequestCheckpoint(), ResolveRecoveryConflictWithDatabase(), ResolveRecoveryConflictWithVirtualXIDs(), RestoreWALFileForRecovery(), ServerLoop(), ShutdownWalRcv(), StartBackgroundWorker(), StartupXLOG(), StreamConnection(), test_postmaster_connection(), vacuum_delay_point(), wait_pid(), WaitExceedsMaxStandbyDelay(), WalSndWaitStopping(), WalWriterMain(), XLogDumpXLogRead(), and XLogFlush().

54 {
55  if (WaitForSingleObject(pgwin32_signal_event,
56  (microsec < 500 ? 1 : (microsec + 500) / 1000))
57  == WAIT_OBJECT_0)
58  {
60  errno = EINTR;
61  return;
62  }
63 }
HANDLE pgwin32_signal_event
Definition: signal.c:27
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:107
#define EINTR
Definition: win32.h:285
char** pgfnames ( const char *  path)

Definition at line 31 of file pgfnames.c.

References _, closedir(), dirent::d_name, elog, NULL, opendir(), palloc(), pstrdup(), readdir(), repalloc(), strerror(), and WARNING.

Referenced by convert_sourcefiles_in(), rmtree(), and scan_available_timezones().

32 {
33  DIR *dir;
34  struct dirent *file;
35  char **filenames;
36  int numnames = 0;
37  int fnsize = 200; /* enough for many small dbs */
38 
39  dir = opendir(path);
40  if (dir == NULL)
41  {
42 #ifndef FRONTEND
43  elog(WARNING, "could not open directory \"%s\": %m", path);
44 #else
45  fprintf(stderr, _("could not open directory \"%s\": %s\n"),
46  path, strerror(errno));
47 #endif
48  return NULL;
49  }
50 
51  filenames = (char **) palloc(fnsize * sizeof(char *));
52 
53  while (errno = 0, (file = readdir(dir)) != NULL)
54  {
55  if (strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
56  {
57  if (numnames + 1 >= fnsize)
58  {
59  fnsize *= 2;
60  filenames = (char **) repalloc(filenames,
61  fnsize * sizeof(char *));
62  }
63  filenames[numnames++] = pstrdup(file->d_name);
64  }
65  }
66 
67  if (errno)
68  {
69 #ifndef FRONTEND
70  elog(WARNING, "could not read directory \"%s\": %m", path);
71 #else
72  fprintf(stderr, _("could not read directory \"%s\": %s\n"),
73  path, strerror(errno));
74 #endif
75  }
76 
77  filenames[numnames] = NULL;
78 
79  if (closedir(dir))
80  {
81 #ifndef FRONTEND
82  elog(WARNING, "could not close directory \"%s\": %m", path);
83 #else
84  fprintf(stderr, _("could not close directory \"%s\": %s\n"),
85  path, strerror(errno));
86 #endif
87  }
88 
89  return filenames;
90 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
int closedir(DIR *)
Definition: dirent.c:113
Definition: dirent.h:9
Definition: dirent.c:25
DIR * opendir(const char *)
Definition: dirent.c:33
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
struct dirent * readdir(DIR *)
Definition: dirent.c:78
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
void * palloc(Size size)
Definition: mcxt.c:849
const char * strerror(int errnum)
Definition: strerror.c:19
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:219
#define _(x)
Definition: elog.c:84
void pgfnames_cleanup ( char **  filenames)

Definition at line 99 of file pgfnames.c.

References fn(), and pfree().

Referenced by convert_sourcefiles_in(), rmtree(), and scan_available_timezones().

100 {
101  char **fn;
102 
103  for (fn = filenames; *fn; fn++)
104  pfree(*fn);
105 
106  pfree(filenames);
107 }
void pfree(void *pointer)
Definition: mcxt.c:950
static void * fn(void *arg)
int pqGethostbyname ( const char *  name,
struct hostent *  resultbuf,
char *  buffer,
size_t  buflen,
struct hostent **  result,
int *  herrno 
)

Definition at line 117 of file thread.c.

References NULL.

Referenced by getaddrinfo().

122 {
123 #if defined(FRONTEND) && defined(ENABLE_THREAD_SAFETY) && defined(HAVE_GETHOSTBYNAME_R)
124 
125  /*
126  * broken (well early POSIX draft) gethostbyname_r() which returns 'struct
127  * hostent *'
128  */
129  *result = gethostbyname_r(name, resultbuf, buffer, buflen, herrno);
130  return (*result == NULL) ? -1 : 0;
131 #else
132 
133  /* no gethostbyname_r(), just use gethostbyname() */
134  *result = gethostbyname(name);
135 
136  if (*result != NULL)
137  *herrno = h_errno;
138 
139  if (*result != NULL)
140  return 0;
141  else
142  return -1;
143 #endif
144 }
return result
Definition: formatting.c:1632
#define NULL
Definition: c.h:229
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
const char * name
Definition: encode.c:521
int pqGetpwuid ( uid_t  uid,
struct passwd *  resultbuf,
char *  buffer,
size_t  buflen,
struct passwd **  result 
)

Definition at line 95 of file thread.c.

References NULL.

Referenced by get_home_path(), pg_fe_getauthname(), PQconnectPoll(), and pqGetHomeDirectory().

97 {
98 #if defined(FRONTEND) && defined(ENABLE_THREAD_SAFETY) && defined(HAVE_GETPWUID_R)
99  return getpwuid_r(uid, resultbuf, buffer, buflen, result);
100 #else
101  /* no getpwuid_r() available, just use getpwuid() */
102  errno = 0;
103  *result = getpwuid(uid);
104  /* paranoia: ensure we return zero on success */
105  return (*result == NULL) ? errno : 0;
106 #endif
107 }
return result
Definition: formatting.c:1632
#define NULL
Definition: c.h:229
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:211
pqsigfunc pqsignal_no_restart ( int  signo,
pqsigfunc  func 
)

Definition at line 71 of file pqsignal.c.

References SIG_ERR, and SIGCHLD.

Referenced by PostmasterMain().

72 {
73  struct sigaction act,
74  oact;
75 
76  act.sa_handler = func;
77  sigemptyset(&act.sa_mask);
78  act.sa_flags = 0;
79 #ifdef SA_NOCLDSTOP
80  if (signo == SIGCHLD)
81  act.sa_flags |= SA_NOCLDSTOP;
82 #endif
83  if (sigaction(signo, &act, &oact) < 0)
84  return SIG_ERR;
85  return oact.sa_handler;
86 }
#define SIG_ERR
Definition: win32.h:184
#define SIGCHLD
Definition: win32.h:198
char* pqStrerror ( int  errnum,
char *  strerrbuf,
size_t  buflen 
)

Definition at line 61 of file thread.c.

References strerror(), and strlcpy().

Referenced by initialize_SSL(), lo_export(), lo_import_internal(), pg_fe_getauthname(), pg_local_sendauth(), and PQconnectPoll().

62 {
63 #if defined(FRONTEND) && defined(ENABLE_THREAD_SAFETY) && defined(HAVE_STRERROR_R)
64  /* reentrant strerror_r is available */
65 #ifdef STRERROR_R_INT
66  /* SUSv3 version */
67  if (strerror_r(errnum, strerrbuf, buflen) == 0)
68  return strerrbuf;
69  else
70  return "Unknown error";
71 #else
72  /* GNU libc */
73  return strerror_r(errnum, strerrbuf, buflen);
74 #endif
75 #else
76  /* no strerror_r() available, just use strerror */
77  strlcpy(strerrbuf, strerror(errnum), buflen);
78 
79  return strerrbuf;
80 #endif
81 }
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * strerror(int errnum)
Definition: strerror.c:19
void qsort_arg ( void *  base,
size_t  nel,
size_t  elsize,
qsort_arg_comparator  cmp,
void *  arg 
)

Definition at line 113 of file qsort_arg.c.

References cmp(), med3(), Min, swap, SWAPINIT, and vecswap.

Referenced by _bt_sort_array_elements(), compute_range_stats(), compute_scalar_stats(), dependency_degree(), gbt_num_picksplit(), gbt_var_picksplit(), ginExtractEntries(), isort(), mcelem_array_selec(), ndistinct_for_combination(), range_gist_double_sorting_split(), range_gist_single_sorting_split(), RelationBuildPartitionDesc(), SortAndUniqItems(), spg_range_quad_picksplit(), startScanKey(), tbm_prepare_shared_iterate(), tsvectorrecv(), uniqueentry(), and uniqueifyJsonbObject().

114 {
115  char *pa,
116  *pb,
117  *pc,
118  *pd,
119  *pl,
120  *pm,
121  *pn;
122  size_t d1,
123  d2;
124  int r,
125  swaptype,
126  presorted;
127 
128 loop:SWAPINIT(a, es);
129  if (n < 7)
130  {
131  for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
132  for (pl = pm; pl > (char *) a && cmp(pl - es, pl, arg) > 0;
133  pl -= es)
134  swap(pl, pl - es);
135  return;
136  }
137  presorted = 1;
138  for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
139  {
140  if (cmp(pm - es, pm, arg) > 0)
141  {
142  presorted = 0;
143  break;
144  }
145  }
146  if (presorted)
147  return;
148  pm = (char *) a + (n / 2) * es;
149  if (n > 7)
150  {
151  pl = (char *) a;
152  pn = (char *) a + (n - 1) * es;
153  if (n > 40)
154  {
155  size_t d = (n / 8) * es;
156 
157  pl = med3(pl, pl + d, pl + 2 * d, cmp, arg);
158  pm = med3(pm - d, pm, pm + d, cmp, arg);
159  pn = med3(pn - 2 * d, pn - d, pn, cmp, arg);
160  }
161  pm = med3(pl, pm, pn, cmp, arg);
162  }
163  swap(a, pm);
164  pa = pb = (char *) a + es;
165  pc = pd = (char *) a + (n - 1) * es;
166  for (;;)
167  {
168  while (pb <= pc && (r = cmp(pb, a, arg)) <= 0)
169  {
170  if (r == 0)
171  {
172  swap(pa, pb);
173  pa += es;
174  }
175  pb += es;
176  }
177  while (pb <= pc && (r = cmp(pc, a, arg)) >= 0)
178  {
179  if (r == 0)
180  {
181  swap(pc, pd);
182  pd -= es;
183  }
184  pc -= es;
185  }
186  if (pb > pc)
187  break;
188  swap(pb, pc);
189  pb += es;
190  pc -= es;
191  }
192  pn = (char *) a + n * es;
193  d1 = Min(pa - (char *) a, pb - pa);
194  vecswap(a, pb - d1, d1);
195  d1 = Min(pd - pc, pn - pd - es);
196  vecswap(pb, pn - d1, d1);
197  d1 = pb - pa;
198  d2 = pd - pc;
199  if (d1 <= d2)
200  {
201  /* Recurse on left partition, then iterate on right partition */
202  if (d1 > es)
203  qsort_arg(a, d1 / es, es, cmp, arg);
204  if (d2 > es)
205  {
206  /* Iterate rather than recurse to save stack space */
207  /* qsort_arg(pn - d2, d2 / es, es, cmp, arg); */
208  a = pn - d2;
209  n = d2 / es;
210  goto loop;
211  }
212  }
213  else
214  {
215  /* Recurse on right partition, then iterate on left partition */
216  if (d2 > es)
217  qsort_arg(pn - d2, d2 / es, es, cmp, arg);
218  if (d1 > es)
219  {
220  /* Iterate rather than recurse to save stack space */
221  /* qsort_arg(a, d1 / es, es, cmp, arg); */
222  n = d1 / es;
223  goto loop;
224  }
225  }
226 }
#define Min(x, y)
Definition: c.h:806
void qsort_arg(void *a, size_t n, size_t es, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
#define SWAPINIT(a, es)
Definition: qsort_arg.c:82
static char * med3(char *a, char *b, char *c, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:105
#define vecswap(a, b, n)
Definition: qsort_arg.c:102
#define swap(a, b)
Definition: qsort_arg.c:94
void * arg
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:742
double rint ( double  x)

Definition at line 22 of file rint.c.

Referenced by acquire_inherited_sample_rows(), AdjustFractSeconds(), bernoulli_beginsamplescan(), btcostestimate(), calculatePagesPerBuffer(), cash_div_flt4(), cash_div_flt8(), cash_mul_flt4(), cash_mul_flt8(), check_effective_io_concurrency(), clamp_row_est(), create_modifytable_path(), DecodeInterval(), DecodeNumberField(), dround(), dtoi2(), dtoi4(), dtoi8(), estimate_rel_size(), ExecInitBitmapHeapScan(), final_cost_hashjoin(), final_cost_nestloop(), float4_to_char(), float8_timestamptz(), float8_to_char(), flt4_mul_cash(), flt8_mul_cash(), ftoi2(), ftoi4(), ftoi8(), genericcostestimate(), gincostestimate(), initial_cost_mergejoin(), interval_div(), interval_mul(), make_interval(), make_time(), make_timestamp_internal(), ParseFractionalSecond(), set_append_rel_size(), and system_beginsamplescan().

23 {
24  double x_orig;
25  double r;
26 
27  /* Per POSIX, NaNs must be returned unchanged. */
28  if (isnan(x))
29  return x;
30 
31  if (x <= 0.0)
32  {
33  /* Both positive and negative zero should be returned unchanged. */
34  if (x == 0.0)
35  return x;
36 
37  /*
38  * Subtracting 0.5 from a number very close to -0.5 can round to
39  * exactly -1.0, producing incorrect results, so we take the opposite
40  * approach: add 0.5 to the negative number, so that it goes closer to
41  * zero (or at most to +0.5, which is dealt with next), avoiding the
42  * precision issue.
43  */
44  x_orig = x;
45  x += 0.5;
46 
47  /*
48  * Be careful to return minus zero when input+0.5 >= 0, as that's what
49  * rint() should return with negative input.
50  */
51  if (x >= 0.0)
52  return -0.0;
53 
54  /*
55  * For very big numbers the input may have no decimals. That case is
56  * detected by testing x+0.5 == x+1.0; if that happens, the input is
57  * returned unchanged. This also covers the case of minus infinity.
58  */
59  if (x == x_orig + 1.0)
60  return x_orig;
61 
62  /* Otherwise produce a rounded estimate. */
63  r = floor(x);
64 
65  /*
66  * If the rounding did not produce exactly input+0.5 then we're done.
67  */
68  if (r != x)
69  return r;
70 
71  /*
72  * The original fractional part was exactly 0.5 (since
73  * floor(input+0.5) == input+0.5). We need to round to nearest even.
74  * Dividing input+0.5 by 2, taking the floor and multiplying by 2
75  * yields the closest even number. This part assumes that division by
76  * 2 is exact, which should be OK because underflow is impossible
77  * here: x is an integer.
78  */
79  return floor(x * 0.5) * 2.0;
80  }
81  else
82  {
83  /*
84  * The positive case is similar but with signs inverted and using
85  * ceil() instead of floor().
86  */
87  x_orig = x;
88  x -= 0.5;
89  if (x <= 0.0)
90  return 0.0;
91  if (x == x_orig - 1.0)
92  return x_orig;
93  r = ceil(x);
94  if (r != x)
95  return r;
96  return ceil(x * 0.5) * 2.0;
97  }
98 }
bool rmtree ( const char *  path,
bool  rmtopdir 
)

Definition at line 36 of file rmtree.c.

References _, elog, filename, lstat, MAXPGPATH, NULL, pgfnames(), pgfnames_cleanup(), result, rmtree(), snprintf(), strerror(), unlink(), and WARNING.

Referenced by cleanup_directories_atexit(), convert_sourcefiles_in(), create_tablespace_directories(), CreateSlotOnDisk(), dbase_redo(), exit_nicely(), movedb(), movedb_failure_callback(), regression_main(), remove_dbtablespaces(), remove_new_subdir(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), rmtree(), and StartupReplicationSlots().

37 {
38  bool result = true;
39  char pathbuf[MAXPGPATH];
40  char **filenames;
41  char **filename;
42  struct stat statbuf;
43 
44  /*
45  * we copy all the names out of the directory before we start modifying
46  * it.
47  */
48  filenames = pgfnames(path);
49 
50  if (filenames == NULL)
51  return false;
52 
53  /* now we have the names we can start removing things */
54  for (filename = filenames; *filename; filename++)
55  {
56  snprintf(pathbuf, MAXPGPATH, "%s/%s", path, *filename);
57 
58  /*
59  * It's ok if the file is not there anymore; we were just about to
60  * delete it anyway.
61  *
62  * This is not an academic possibility. One scenario where this
63  * happens is when bgwriter has a pending unlink request for a file in
64  * a database that's being dropped. In dropdb(), we call
65  * ForgetDatabaseFsyncRequests() to flush out any such pending unlink
66  * requests, but because that's asynchronous, it's not guaranteed that
67  * the bgwriter receives the message in time.
68  */
69  if (lstat(pathbuf, &statbuf) != 0)
70  {
71  if (errno != ENOENT)
72  {
73 #ifndef FRONTEND
74  elog(WARNING, "could not stat file or directory \"%s\": %m",
75  pathbuf);
76 #else
77  fprintf(stderr, _("could not stat file or directory \"%s\": %s\n"),
78  pathbuf, strerror(errno));
79 #endif
80  result = false;
81  }
82  continue;
83  }
84 
85  if (S_ISDIR(statbuf.st_mode))
86  {
87  /* call ourselves recursively for a directory */
88  if (!rmtree(pathbuf, true))
89  {
90  /* we already reported the error */
91  result = false;
92  }
93  }
94  else
95  {
96  if (unlink(pathbuf) != 0)
97  {
98  if (errno != ENOENT)
99  {
100 #ifndef FRONTEND
101  elog(WARNING, "could not remove file or directory \"%s\": %m",
102  pathbuf);
103 #else
104  fprintf(stderr, _("could not remove file or directory \"%s\": %s\n"),
105  pathbuf, strerror(errno));
106 #endif
107  result = false;
108  }
109  }
110  }
111  }
112 
113  if (rmtopdir)
114  {
115  if (rmdir(path) != 0)
116  {
117 #ifndef FRONTEND
118  elog(WARNING, "could not remove file or directory \"%s\": %m",
119  path);
120 #else
121  fprintf(stderr, _("could not remove file or directory \"%s\": %s\n"),
122  path, strerror(errno));
123 #endif
124  result = false;
125  }
126  }
127 
128  pgfnames_cleanup(filenames);
129 
130  return result;
131 }
char ** pgfnames(const char *path)
Definition: pgfnames.c:31
return result
Definition: formatting.c:1632
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define MAXPGPATH
int unlink(const char *filename)
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
#define NULL
Definition: c.h:229
void pgfnames_cleanup(char **filenames)
Definition: pgfnames.c:99
static char * filename
Definition: pg_dumpall.c:89
const char * strerror(int errnum)
Definition: strerror.c:19
#define elog
Definition: elog.h:219
#define lstat(path, sb)
Definition: win32.h:262
#define _(x)
Definition: elog.c:84
void set_pglocale_pgservice ( const char *  argv0,
const char *  app 
)

Definition at line 550 of file exec.c.

References canonicalize_path(), find_my_exec(), get_etc_path(), get_locale_path(), MAXPGPATH, my_exec_path, NULL, PG_TEXTDOMAIN, putenv, and snprintf().

Referenced by main(), and regression_main().

551 {
552  char path[MAXPGPATH];
553  char my_exec_path[MAXPGPATH];
554  char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
555  * PGLOCALEDIR */
556  char *dup_path;
557 
558  /* don't set LC_ALL in the backend */
559  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
560  {
561  setlocale(LC_ALL, "");
562 
563  /*
564  * One could make a case for reproducing here PostmasterMain()'s test
565  * for whether the process is multithreaded. Unlike the postmaster,
566  * no frontend program calls sigprocmask() or otherwise provides for
567  * mutual exclusion between signal handlers. While frontends using
568  * fork(), if multithreaded, are formally exposed to undefined
569  * behavior, we have not witnessed a concrete bug. Therefore,
570  * complaining about multithreading here may be mere pedantry.
571  */
572  }
573 
574  if (find_my_exec(argv0, my_exec_path) < 0)
575  return;
576 
577 #ifdef ENABLE_NLS
578  get_locale_path(my_exec_path, path);
579  bindtextdomain(app, path);
580  textdomain(app);
581 
582  if (getenv("PGLOCALEDIR") == NULL)
583  {
584  /* set for libpq to use */
585  snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
586  canonicalize_path(env_path + 12);
587  dup_path = strdup(env_path);
588  if (dup_path)
589  putenv(dup_path);
590  }
591 #endif
592 
593  if (getenv("PGSYSCONFDIR") == NULL)
594  {
595  get_etc_path(my_exec_path, path);
596 
597  /* set for libpq to use */
598  snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
599  canonicalize_path(env_path + 13);
600  dup_path = strdup(env_path);
601  if (dup_path)
602  putenv(dup_path);
603  }
604 }
static char * argv0
Definition: pg_ctl.c:89
void canonicalize_path(char *path)
Definition: path.c:254
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define putenv(x)
Definition: win32.h:411
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1012
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:713
#define NULL
Definition: c.h:229
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
void simple_prompt ( const char *  prompt,
char *  destination,
size_t  destlen,
bool  echo 
)

Definition at line 37 of file sprompt.c.

References _, buf, length(), and NULL.

Referenced by _connectDB(), connectDatabase(), ConnectDatabase(), doConnect(), exec_command_password(), exec_command_prompt(), get_su_pwd(), GetConnection(), main(), prompt_for_password(), sql_conn(), vacuumlo(), and yesno_prompt().

38 {
39  int length;
40  FILE *termin,
41  *termout;
42 
43 #ifdef HAVE_TERMIOS_H
44  struct termios t_orig,
45  t;
46 #else
47 #ifdef WIN32
48  HANDLE t = NULL;
49  DWORD t_orig = 0;
50 #endif
51 #endif
52 
53 #ifdef WIN32
54 
55  /*
56  * A Windows console has an "input code page" and an "output code page";
57  * these usually match each other, but they rarely match the "Windows ANSI
58  * code page" defined at system boot and expected of "char *" arguments to
59  * Windows API functions. The Microsoft CRT write() implementation
60  * automatically converts text between these code pages when writing to a
61  * console. To identify such file descriptors, it calls GetConsoleMode()
62  * on the underlying HANDLE, which in turn requires GENERIC_READ access on
63  * the HANDLE. Opening termout in mode "w+" allows that detection to
64  * succeed. Otherwise, write() would not recognize the descriptor as a
65  * console, and non-ASCII characters would display incorrectly.
66  *
67  * XXX fgets() still receives text in the console's input code page. This
68  * makes non-ASCII credentials unportable.
69  */
70  termin = fopen("CONIN$", "r");
71  termout = fopen("CONOUT$", "w+");
72 #else
73 
74  /*
75  * Do not try to collapse these into one "w+" mode file. Doesn't work on
76  * some platforms (eg, HPUX 10.20).
77  */
78  termin = fopen("/dev/tty", "r");
79  termout = fopen("/dev/tty", "w");
80 #endif
81  if (!termin || !termout
82 #ifdef WIN32
83 
84  /*
85  * Direct console I/O does not work from the MSYS 1.0.10 console. Writes
86  * reach nowhere user-visible; reads block indefinitely. XXX This affects
87  * most Windows terminal environments, including rxvt, mintty, Cygwin
88  * xterm, Cygwin sshd, and PowerShell ISE. Switch to a more-generic test.
89  */
90  || (getenv("OSTYPE") && strcmp(getenv("OSTYPE"), "msys") == 0)
91 #endif
92  )
93  {
94  if (termin)
95  fclose(termin);
96  if (termout)
97  fclose(termout);
98  termin = stdin;
99  termout = stderr;
100  }
101 
102 #ifdef HAVE_TERMIOS_H
103  if (!echo)
104  {
105  tcgetattr(fileno(termin), &t);
106  t_orig = t;
107  t.c_lflag &= ~ECHO;
108  tcsetattr(fileno(termin), TCSAFLUSH, &t);
109  }
110 #else
111 #ifdef WIN32
112  if (!echo)
113  {
114  /* get a new handle to turn echo off */
115  t = GetStdHandle(STD_INPUT_HANDLE);
116 
117  /* save the old configuration first */
118  GetConsoleMode(t, &t_orig);
119 
120  /* set to the new mode */
121  SetConsoleMode(t, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT);
122  }
123 #endif
124 #endif
125 
126  if (prompt)
127  {
128  fputs(_(prompt), termout);
129  fflush(termout);
130  }
131 
132  if (fgets(destination, destlen, termin) == NULL)
133  destination[0] = '\0';
134 
135  length = strlen(destination);
136  if (length > 0 && destination[length - 1] != '\n')
137  {
138  /* eat rest of the line */
139  char buf[128];
140  int buflen;
141 
142  do
143  {
144  if (fgets(buf, sizeof(buf), termin) == NULL)
145  break;
146  buflen = strlen(buf);
147  } while (buflen > 0 && buf[buflen - 1] != '\n');
148  }
149 
150  if (length > 0 && destination[length - 1] == '\n')
151  /* remove trailing newline */
152  destination[length - 1] = '\0';
153 
154 #ifdef HAVE_TERMIOS_H
155  if (!echo)
156  {
157  tcsetattr(fileno(termin), TCSAFLUSH, &t_orig);
158  fputs("\n", termout);
159  fflush(termout);
160  }
161 #else
162 #ifdef WIN32
163  if (!echo)
164  {
165  /* reset to the original console mode */
166  SetConsoleMode(t, t_orig);
167  fputs("\n", termout);
168  fflush(termout);
169  }
170 #endif
171 #endif
172 
173  if (termin != stdin)
174  {
175  fclose(termin);
176  fclose(termout);
177  }
178 }
int length(const List *list)
Definition: list.c:1271
static char * buf
Definition: pg_test_fsync.c:66
#define NULL
Definition: c.h:229
#define _(x)
Definition: elog.c:84
void srandom ( unsigned int  seed)

Definition at line 22 of file srandom.c.

References pg_srand48().

Referenced by BackendRun(), main(), PostmasterMain(), and setseed().

23 {
24  pg_srand48((long int) seed);
25 }
void pg_srand48(long seed)
Definition: erand48.c:102
size_t strlcat ( char *  dst,
const char *  src,
size_t  siz 
)

Definition at line 33 of file strlcat.c.

Referenced by CreateLockFile(), get_configdata(), get_prompt(), and validate_exec().

34 {
35  char *d = dst;
36  const char *s = src;
37  size_t n = siz;
38  size_t dlen;
39 
40  /* Find the end of dst and adjust bytes left but don't go past end */
41  while (n-- != 0 && *d != '\0')
42  d++;
43  dlen = d - dst;
44  n = siz - dlen;
45 
46  if (n == 0)
47  return (dlen + strlen(s));
48  while (*s != '\0')
49  {
50  if (n != 1)
51  {
52  *d++ = *s;
53  n--;
54  }
55  s++;
56  }
57  *d = '\0';
58 
59  return (dlen + (s - src)); /* count does not include NUL */
60 }
size_t strlcpy ( char *  dst,
const char *  src,
size_t  siz 
)

Definition at line 45 of file strlcpy.c.

Referenced by _tarGetHeader(), AuxiliaryProcessMain(), BaseBackup(), be_tls_get_cipher(), be_tls_get_peerdn_name(), be_tls_get_version(), chkpass_in(), chkpass_out(), ChooseIndexNameAddition(), CleanupPriorWALFiles(), connectFailureMessage(), ConvertTimeZoneAbbrevs(), create_script_for_old_cluster_deletion(), createNewConnection(), descriptor_variable(), DetermineTimeZoneAbbrevOffsetInternal(), expand_tilde(), fetch_fp_info(), find_in_dynamic_libpath(), find_other_exec_or_die(), from_char_parse_int_len(), from_char_seq_search(), fsync_parent_path(), get_configdata(), get_control_data(), get_home_path(), get_prompt(), hash_create(), identify_system_timezone(), init(), initialize_SSL(), InitPostgres(), internal_cancel(), isolation_init(), join_path_components(), KeepFileRestoredFromArchive(), logfile_getname(), main(), make_oper_cache_key(), make_relative_path(), parseCommandLine(), ParseLongOption(), parseServiceInfo(), pg_getnameinfo_all(), pg_open_tzfile(), pg_perm_setlocale(), pg_timezone_abbrevs(), pg_TZDIR(), pg_tzenumerate_next(), pgarch_archiveXlog(), pgstat_bestart(), PQcancel(), pqGetErrorNotice3(), pqGetHomeDirectory(), pqParseInput2(), pqParseInput3(), PQrequestCancel(), pqStrerror(), process_file(), process_postgres_switches(), ReceiveAndUnpackTarFile(), recoveryStopsAfter(), replace_string(), RequestXLogStreaming(), resolve_symlinks(), results_differ(), scan_available_timezones(), scan_directory_ci(), SerializeLibraryState(), set_ps_display(), setup_bin_paths(), SetWALFileNameForCleanup(), SimpleLruInit(), SSLerrmessage(), StartupXLOG(), syncTargetDirectory(), tar_close(), tarCreateHeader(), test_postmaster_connection(), timestamptz_to_str(), uuid_generate_internal(), validate_exec(), WalReceiverMain(), and XLogRestorePoint().

46 {
47  char *d = dst;
48  const char *s = src;
49  size_t n = siz;
50 
51  /* Copy as many bytes as will fit */
52  if (n != 0)
53  {
54  while (--n != 0)
55  {
56  if ((*d++ = *s++) == '\0')
57  break;
58  }
59  }
60 
61  /* Not enough room in dst, add NUL and traverse rest of src */
62  if (n == 0)
63  {
64  if (siz != 0)
65  *d = '\0'; /* NUL-terminate dst */
66  while (*s++)
67  ;
68  }
69 
70  return (s - src - 1); /* count does not include NUL */
71 }
void unsetenv ( const char *  name)

Definition at line 20 of file unsetenv.c.

References malloc, NULL, and putenv.

21 {
22  char *envstr;
23 
24  if (getenv(name) == NULL)
25  return; /* no work */
26 
27  /*
28  * The technique embodied here works if libc follows the Single Unix Spec
29  * and actually uses the storage passed to putenv() to hold the environ
30  * entry. When we clobber the entry in the second step we are ensuring
31  * that we zap the actual environ member. However, there are some libc
32  * implementations (notably recent BSDs) that do not obey SUS but copy the
33  * presented string. This method fails on such platforms. Hopefully all
34  * such platforms have unsetenv() and thus won't be using this hack. See:
35  * http://www.greenend.org.uk/rjk/2008/putenv.html
36  *
37  * Note that repeatedly setting and unsetting a var using this code will
38  * leak memory.
39  */
40 
41  envstr = (char *) malloc(strlen(name) + 2);
42  if (!envstr) /* not much we can do if no memory */
43  return;
44 
45  /* Override the existing setting by forcibly defining the var */
46  sprintf(envstr, "%s=", name);
47  putenv(envstr);
48 
49  /* Now we can clobber the variable definition this way: */
50  strcpy(envstr, "=");
51 
52  /*
53  * This last putenv cleans up if we have multiple zero-length names as a
54  * result of unsetting multiple things.
55  */
56  putenv(envstr);
57 }
#define putenv(x)
Definition: win32.h:411
#define malloc(a)
Definition: header.h:50
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
char* wait_result_to_str ( int  exit_status)

Definition at line 32 of file wait_error.c.

References _, pstrdup(), snprintf(), WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by ClosePipeToProgram(), do_copy(), ExecuteRecoveryCommand(), pclose_check(), and RestoreArchivedFile().

33 {
34  char str[512];
35 
36  if (WIFEXITED(exitstatus))
37  {
38  /*
39  * Give more specific error message for some common exit codes that
40  * have a special meaning in shells.
41  */
42  switch (WEXITSTATUS(exitstatus))
43  {
44  case 126:
45  snprintf(str, sizeof(str), _("command not executable"));
46  break;
47 
48  case 127:
49  snprintf(str, sizeof(str), _("command not found"));
50  break;
51 
52  default:
53  snprintf(str, sizeof(str),
54  _("child process exited with exit code %d"),
55  WEXITSTATUS(exitstatus));
56  }
57  }
58  else if (WIFSIGNALED(exitstatus))
59 #if defined(WIN32)
60  snprintf(str, sizeof(str),
61  _("child process was terminated by exception 0x%X"),
62  WTERMSIG(exitstatus));
63 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
64  {
65  char str2[256];
66 
67  snprintf(str2, sizeof(str2), "%d: %s", WTERMSIG(exitstatus),
68  WTERMSIG(exitstatus) < NSIG ?
69  sys_siglist[WTERMSIG(exitstatus)] : "(unknown)");
70  snprintf(str, sizeof(str),
71  _("child process was terminated by signal %s"), str2);
72  }
73 #else
74  snprintf(str, sizeof(str),
75  _("child process was terminated by signal %d"),
76  WTERMSIG(exitstatus));
77 #endif
78  else
79  snprintf(str, sizeof(str),
80  _("child process exited with unrecognized status %d"),
81  exitstatus);
82 
83  return pstrdup(str);
84 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define WIFEXITED(w)
Definition: win32.h:172
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define WIFSIGNALED(w)
Definition: win32.h:173
#define WEXITSTATUS(w)
Definition: win32.h:174
#define WTERMSIG(w)
Definition: win32.h:175
#define _(x)
Definition: elog.c:84