PostgreSQL Source Code  git master
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 PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"
 
#define EXE   ""
 
#define DEVNULL   "/dev/null"
 
#define USE_REPL_SNPRINTF   1
 
#define vsnprintf   pg_vsnprintf
 
#define snprintf   pg_snprintf
 
#define vsprintf   pg_vsprintf
 
#define sprintf   pg_sprintf
 
#define vfprintf   pg_vfprintf
 
#define fprintf   pg_fprintf
 
#define vprintf   pg_vprintf
 
#define printf(...)   pg_printf(__VA_ARGS__)
 
#define strerror   pg_strerror
 
#define strerror_r   pg_strerror_r
 
#define PG_STRERROR_R_BUFLEN   256 /* Recommended buffer size for strerror_r */
 
#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 RTLD_NOW   1
 
#define RTLD_GLOBAL   0
 
#define qsort(a, b, c, d)   pg_qsort(a,b,c,d)
 
#define pg_backend_random   pg_strong_random
 

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)
 
int pg_vsnprintf (char *str, size_t count, const char *fmt, va_list args)
 
int pg_snprintf (char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
 
int int pg_vsprintf (char *str, const char *fmt, va_list args)
 
int pg_sprintf (char *str, const char *fmt,...) pg_attribute_printf(2
 
int int pg_vfprintf (FILE *stream, const char *fmt, va_list args)
 
int pg_fprintf (FILE *stream, const char *fmt,...) pg_attribute_printf(2
 
int int pg_vprintf (const char *fmt, va_list args)
 
int pg_printf (const char *fmt,...) pg_attribute_printf(1
 
int pg_strfromd (char *str, size_t count, int precision, double value)
 
char * pg_strerror (int errnum)
 
char * pg_strerror_r (int errnum, char *buf, size_t buflen)
 
const char * pg_strsignal (int signum)
 
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)
 
float strtof (const char *nptr, char **endptr)
 
char * mkdtemp (char *path)
 
double rint (double x)
 
int inet_aton (const char *cp, struct in_addr *addr)
 
ssize_t pg_pread (int fd, void *buf, size_t nbyte, off_t offset)
 
ssize_t pg_pwrite (int fd, const void *buf, size_t nbyte, off_t offset)
 
size_t strlcat (char *dst, const char *src, size_t siz)
 
size_t strlcpy (char *dst, const char *src, size_t siz)
 
size_t strnlen (const char *str, size_t maxlen)
 
long random (void)
 
void unsetenv (const char *name)
 
void srandom (unsigned int seed)
 
void * dlopen (const char *file, int mode)
 
void * dlsym (void *handle, const char *symbol)
 
int dlclose (void *handle)
 
char * dlerror (void)
 
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)
 
bool pg_strong_random (void *buf, size_t len)
 
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)
 
bool wait_result_is_signal (int exit_status, int signum)
 
bool wait_result_is_any_signal (int exit_status, bool include_command_not_found)
 

Macro Definition Documentation

◆ closesocket

◆ DEVNULL

#define DEVNULL   "/dev/null"

◆ EXE

#define EXE   ""

Definition at line 117 of file port.h.

Referenced by find_other_exec(), and get_progname().

◆ fprintf

#define fprintf   pg_fprintf

Definition at line 196 of file port.h.

Referenced by _connectDB(), _dosmaperr(), _print_horizontal_line(), _ShowOption(), add_socket_to_set(), addScript(), advanceConnectionState(), advice(), appendPsqlMetaConnect(), appendShellString(), apw_dump_now(), BaseBackup(), bootstrap_template1(), change_directory(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_input(), check_loadable_libraries(), check_locale_encoding(), check_prepare_conn(), check_system_link_file(), CheckConnection(), CheckForExternalTrigger(), checkInitSteps(), close_file(), ClosePager(), coerceToBool(), coerceToDouble(), coerceToInt(), colorcomplement(), commandFailed(), ConditionError(), convert_sourcefiles_in(), create_data_directory(), create_script_for_cluster_analyze(), create_script_for_old_cluster_deletion(), create_xlog_or_symlink(), CreateOptsFile(), CustomizableCleanupPriorWALFiles(), CustomizableInitialize(), CustomizableNextWALFileReady(), defaultNoticeProcessor(), DescribeQuery(), do_field(), do_header(), do_pg_stop_backup(), doConnect(), dolink(), doLog(), dropDBs(), dropRoles(), dropTablespaces(), dsa_dump(), dshash_dump(), dumpDatabases(), dumpGroups(), dumpnfa(), dumpRoleMembership(), dumpRoles(), dumpTablespaces(), dumpTimestamp(), dumpUserConfig(), echo_hidden_command(), ecpg_filter(), ecpg_log(), ecpg_start_test(), ECPGdump_a_simple(), evalStandardFunc(), evaluateExpr(), evaluateSleep(), exec_command_write(), exec_prog(), executeMetaCommand(), ExecuteSqlCommand(), executeStatement(), exportFile(), file_line_count(), file_size(), findBuiltin(), get_id(), get_opts(), get_progname(), get_su_pwd(), get_user_name_or_exit(), getopt(), getopt_long(), gseg_internal_consistent(), gseg_leaf_consistent(), gseg_penalty(), gseg_picksplit(), gseg_same(), gseg_union(), handle_args(), handle_sigint(), hash_stats(), header(), helpSQL(), helpVariables(), identify_system_timezone(), importFile(), infile(), init_htab(), initCreateFKeys(), initCreatePKeys(), initCreateTables(), initDropTables(), initGenerateData(), initialize_environment(), initVacuum(), isolation_init(), isolation_start_test(), isotesterNoticeProcessor(), listAvailableScripts(), load_resultmap(), LocalBufferAlloc(), lookupCreateVariable(), main(), make_absolute_path(), make_directory(), makeVariableValue(), MarkLocalBufferDirty(), memory_exhausted(), MemoryContextStatsDetail(), MemoryContextStatsInternal(), MemoryContextStatsPrint(), my_truncate(), new_9_0_populate_pg_largeobject_metadata(), nfanode(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), open_result_files(), optimize(), output_cursor_statement(), output_deallocate_prepare_statement(), output_declare_statement(), output_get_descr(), output_get_descr_header(), output_line_number(), output_prepare_statement(), output_row(), output_set_descr(), output_set_descr_header(), output_statement(), overwrite(), packArcInfoCmp(), parse_psql_options(), parseCommandLine(), parseQuery(), parseScriptWeight(), passwordFromFile(), perform_spin_delay(), pg_attribute_printf(), pg_char_to_encoding(), pg_log_generic_v(), pg_log_v(), pg_malloc_internal(), pg_realloc(), pg_regcomp(), pg_strdup(), pgwin32_is_service(), pickout(), pipe_read_line(), PostmasterMain(), PQdisplayTuples(), pqGetc(), pqGetInt(), pqGetnchar(), pqGets_internal(), PQprint(), PQprintTuples(), pqPutc(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), pqSaveParameterStatus(), pqSetenvPoll(), pqSkipnchar(), print(), print2(), print_action(), print_aligned_text(), print_aligned_vertical(), print_aligned_vertical_line(), print_asciidoc_text(), print_asciidoc_vertical(), print_html_text(), print_html_vertical(), print_latex_vertical(), print_troff_ms_vertical(), print_with_linenumbers(), printHistory(), PrintNotifications(), printProgressReport(), PrintQueryStatus(), printTable(), printTableAddCell(), printTableAddHeader(), process_file(), progress_report(), psql_command(), psql_start_test(), PSQLexec(), PSQLexecWatch(), pvsnprintf(), readCommandResponse(), regression_main(), report_error_message(), report_multiple_error_messages(), RestoreWALFileForRecovery(), results_differ(), rstacktoodeep(), rulesub(), run_diff(), run_named_permutations(), run_permutation(), run_schedule(), runInitSteps(), runShellCommand(), s_lock_stuck(), scan_available_timezones(), score_timezone(), selectColorTrigrams(), sendCommand(), SendQuery(), set_dump_section(), set_random_seed(), setalarm(), setup_cancel_handler(), setup_data_file_paths(), setup_locale_encoding(), setup_pgdata(), SetWALFileNameForCleanup(), SetWALSegSize(), slashUsage(), slice_check(), spawn_process(), sql_check(), sql_conn(), sql_exec(), sqlprint(), status_end(), stop_postmaster(), strtodouble(), strtoint64(), syntax_error(), test_pattern(), test_timing(), threadRun(), TParserClose(), TParserCopyClose(), TParserCopyInit(), TParserGet(), TParserInit(), try_complete_step(), tryExecuteStatement(), update_metainfo_datafile(), usage(), vacuumlo(), verror(), wait_for_tests(), warn(), warn_on_mount_point(), warning(), whenever_action(), write_version_file(), writezone(), XidCacheRemoveRunningXids(), and yearistype().

◆ fseeko

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

Definition at line 356 of file port.h.

◆ ftello

#define ftello (   a)    ftell(a)

Definition at line 357 of file port.h.

◆ is_absolute_path

◆ IS_DIR_SEP

◆ pg_backend_random

#define pg_backend_random   pg_strong_random

Definition at line 516 of file port.h.

◆ PG_BACKEND_VERSIONSTR

#define PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"

Definition at line 111 of file port.h.

Referenced by adjust_data_dir(), do_kill(), do_start(), getInstallationPaths(), main(), and setup_bin_paths().

◆ PG_IOLBF

#define PG_IOLBF   _IOLBF

Definition at line 324 of file port.h.

Referenced by logfile_open(), main(), SysLogger_Start(), and update_metainfo_datafile().

◆ PG_STRERROR_R_BUFLEN

◆ PGINVALID_SOCKET

◆ pgoff_t

#define pgoff_t   off_t

Definition at line 339 of file port.h.

◆ printf

#define printf (   ...)    pg_printf(__VA_ARGS__)

Definition at line 198 of file port.h.

Referenced by aes_cbc_decrypt(), array_in(), bootstrap_template1(), callback(), cash_in(), check_constant_qual(), check_errno(), check_ok(), check_result_of_insert(), check_return(), CleanupPriorWALFiles(), cluster_all_databases(), connection_warnings(), connectToServer(), create_data_directory(), create_xlog_or_symlink(), date_test_defmt(), date_test_fmt(), date_test_strdate(), debugStartup(), debugtup(), describe_char(), do_connect(), do_help(), do_status(), dosqlprint(), DoubleMetaphone(), dump_assert(), dump_assign(), dump_binary(), dump_block(), dump_call(), dump_case(), dump_close(), dump_commit(), dump_cursor_direction(), dump_dynexecute(), dump_dynfors(), dump_execsql(), dump_exit(), dump_expr(), dump_fetch(), dump_forc(), dump_foreach_a(), dump_fori(), dump_fors(), dump_getdiag(), dump_if(), dump_ind(), dump_loop(), dump_open(), dump_perform(), dump_raise(), dump_return(), dump_return_next(), dump_return_query(), dump_rollback(), dump_set(), dump_sqlda(), dump_stmt(), dump_while(), echo_hidden_command(), ecpg_process_output(), error(), exec_command_conninfo(), exec_command_pset(), exec_command_s(), ExecHashIncreaseNumBatches(), ExecHashIncreaseNumBuckets(), ExecHashTableCreate(), executeCommand(), executeMaintenanceCommand(), executeQuery(), executeQueryOrDie(), fa(), fb(), fc(), fd(), fe(), fmtlong(), generate_partitionwise_join_paths(), get_su_pwd(), handle_args(), handle_help_version_opts(), help(), init_perm(), initialize_data_directory(), initialize_environment(), int2int4_sum(), InteractiveBackend(), len_utf8(), main(), MainLoop(), output(), pg_fatal(), pg_log_v(), plpgsql_dumptree(), PostgresMain(), pprint(), preprocess_expression(), print(), print_addr(), print_double(), print_elapse(), print_expr(), print_pathkeys(), print_rmgr_list(), print_rt(), print_slot(), print_tl(), printatt(), PrintControlValues(), printGSSInfo(), printMixedStruct(), PrintNewControlValues(), printPsetInfo(), printResult(), printResults(), printResultSet(), printSimpleStats(), printSSLInfo(), PrintTiming(), PrintVariables(), PSQLexec(), regression_main(), reindex_all_databases(), run_permutation(), run_schedule(), run_single_test(), run_vacuum_command(), runShellCommand(), SendQuery(), setup_locale_encoding(), setup_text_search(), show_binary_results(), show_item(), sql_check(), sqlnotice(), test(), test_config_settings(), test_file_descriptor_sync(), test_non_sync(), test_null(), test_open_sync(), test_open_syncs(), test_sync(), test_timing(), TopoSort(), try_complete_step(), update_spins_per_delay(), usage(), vacuum_one_database(), XLogDumpDisplayRecord(), XLogDumpDisplayStats(), XLogDumpStatsRow(), and yesno_prompt().

◆ qsort

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

Definition at line 491 of file port.h.

Referenced by _bt_deltasortsplits(), _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(), check_loadable_libraries(), CheckConstraintFetch(), checkSharedDependencies(), choose_bitmap_and(), compactify_tuples(), compileTheLexeme(), compute_array_stats(), compute_range_stats(), compute_scalar_stats(), compute_tsvector_stats(), create_hash_bounds(), CreateStatistics(), dsynonym_init(), eliminate_duplicate_dependencies(), entry_dealloc(), EnumValuesCreate(), ExecInitInterpreter(), expand_grouping_sets(), filemap_finalize(), fill_in_constant_lengths(), find_inheritance_children(), findDependentObjects(), findObjectByCatalogId(), g_int_picksplit(), g_intbig_picksplit(), generate_trgm(), generate_wildcard_trgm(), get_docrep(), ghstore_picksplit(), ginGetBAEntry(), gist_box_picksplit(), gseg_picksplit(), gtrgm_picksplit(), gtsquery_picksplit(), gtsvector_picksplit(), heap_compute_xid_horizon_for_tuples(), hstoreUniquePairs(), IssuePendingWritebacks(), list_qsort(), 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(), pg_import_system_collations(), ProcArrayApplyRecoveryInfo(), process_target_file(), QTNSort(), range_gist_double_sorting_split(), rankSort(), read_dictionary(), readstoplist(), ready_list_sort(), rebuild_database_list(), ReorderBufferCopySnap(), select_active_windows(), selectColorTrigrams(), SerializeTransactionState(), setExtensionMembership(), setup_pct_info(), SnapBuildBuildSnapshot(), sort_object_addresses(), sort_policies_by_name(), sort_pool(), sort_snapshot(), 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(), WriteDataChunks(), and writezone().

◆ RTLD_GLOBAL

#define RTLD_GLOBAL   0

Definition at line 472 of file port.h.

Referenced by internal_load_library().

◆ RTLD_NOW

#define RTLD_NOW   1

Definition at line 464 of file port.h.

Referenced by internal_load_library().

◆ snprintf

#define snprintf   pg_snprintf

Definition at line 192 of file port.h.

Referenced by _ArchiveEntry(), _discoverArchiveFormat(), _EndBlob(), _LoadBlobs(), _PG_init(), _ShowOption(), _StartBlob(), _tarAddFile(), _tarGetHeader(), _tarPositionTo(), addRangeTableEntryForValues(), AddToDataDirLockFile(), adjust_data_dir(), AllocSetStats(), AlterObjectOwner_internal(), AlterSystemSetConfigFile(), anybit_typmodout(), anychar_typmodout(), ApplyLauncherRegister(), ApplyWorkerMain(), apw_dump_now(), autovac_report_activity(), autovac_report_workitem(), BackendInitialize(), BackendRun(), BackgroundWorkerUnblockSignals(), BasicOpenFilePerm(), begin_remote_xact(), bootstrap_template1(), build_pgstattuple_type(), buildWorkerCommand(), buildWorkerResponse(), cache_locale_time(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), cfopen(), check_file_clone(), check_file_excluded(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_foreign_key(), check_hard_link(), check_loadable_libraries(), check_log_duration(), check_primary_key(), check_single_dir(), checkControlFile(), CheckPointLogicalRewriteHeap(), CheckPointSnapBuild(), CheckSCRAMAuth(), choose_dsm_implementation(), ChooseConstraintName(), ChooseExtendedStatisticName(), ChooseRelationName(), cidout(), cleanup(), CleanupBackgroundWorker(), CleanupBackupHistory(), CleanupPriorWALFiles(), close_cursor(), compile_pltcl_function(), connectOptions2(), convert_sourcefiles_in(), convertTSFunction(), copy_subdir_files(), copydir(), CopyFromErrorCallback(), crashDumpHandler(), create_new_objects(), create_target_dir(), create_target_symlink(), create_toast_table(), createBackupLabel(), CreateLockFile(), CreateReplicationSlot(), CreateSocketLockFile(), CreateSubscription(), CreateTrigger(), CustomizableCleanupPriorWALFiles(), CustomizableInitialize(), db_dir_size(), DeleteAllExportedSnapshotFiles(), describeDumpableObject(), dir_close(), dir_existsfile(), dir_get_file_size(), dir_open_for_write(), disable_old_cluster(), do_compile(), do_edit(), do_init(), do_kill(), do_lo_list(), do_logrotate(), do_pg_start_backup(), do_promote(), do_setval(), do_start(), do_watch(), DropSubscription(), dsm_cleanup_for_mmap(), dsm_impl_mmap(), dsm_impl_op(), dsm_impl_pin_segment(), dsm_impl_sysv(), dsm_impl_unpin_segment(), dumpSequence(), ean2isn(), ean2string(), ecpg_build_params(), ecpg_log(), ecpg_raise(), ecpg_raise_backend(), ecpg_start_test(), ECPGget_desc(), ECPGset_desc(), ECPGset_var(), exec_prog(), ExecBuildAuxRowMark(), ExecCreateTableAs(), ExecGrant_Largeobject(), ExecParallelHashJoinSetUpBatches(), ExecQueryUsingCursor(), exitArchiveRecovery(), expand_inherited_rtentry(), ExplainPropertyInteger(), ExportSnapshot(), fetch_file_range(), fetch_more_data(), find_other_exec(), FindStreamingStart(), finish_foreign_modify(), finish_heap_swap(), float4_numeric(), float8_numeric(), footers_with_default(), format_operator_internal(), format_procedure_internal(), formatPGVersionNumber(), fsync_pgdata(), generate_old_dump(), GenerationStats(), get_alternative_expectfile(), get_bin_version(), get_config_unit_name(), get_control_data(), get_controlfile(), get_db_infos(), get_dbstat_filename(), get_errno_symbol(), get_extension_aux_control_filename(), get_extension_control_directory(), get_extension_control_filename(), get_extension_script_directory(), get_extension_script_filename(), get_home_path(), get_major_server_version(), get_prompt(), get_rel_infos(), get_sock_dir(), get_str_from_var_sci(), get_tablespace_paths(), get_tsearch_config_filename(), GetConfigOption(), GetConfigOptionByNum(), GetConfigOptionResetString(), getnameinfo(), getVariable(), heap_xlog_logical_rewrite(), ident_inet(), identify_system_timezone(), identify_target_directory(), IdentifySystem(), ImportSnapshot(), incompatible_module_error(), init_params(), init_ps_display(), initCreatePKeys(), initCreateTables(), initGenerateData(), initialize_data_directory(), initialize_environment(), initialize_SSL(), InitTempTableNamespace(), int44out(), int_to_roman(), intervaltypmodout(), isolation_start_test(), join_path_components(), jsonb_agg_transfn(), jsonb_object_agg_transfn(), KeepFileRestoredFromArchive(), KillExistingArchiveStatus(), KillExistingXLOG(), LaunchParallelWorkers(), libpqrcv_readtimelinehistoryfile(), llvm_create_types(), load_module(), load_relcache_init_file(), load_relmap_file(), load_resultmap(), log_line_prefix(), logfile_getname(), logical_rewrite_log_mapping(), logicalrep_worker_launch(), macaddr8_out(), macaddr_out(), main(), make_new_heap(), make_text_key(), mark_file_as_archived(), nameconcatoid(), network_out(), network_show(), new_9_0_populate_pg_largeobject_metadata(), nextval_internal(), nfalsepos_for_missing_strings(), numerictypmodout(), oidout(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), open_file_in_directory(), open_result_files(), open_target_file(), open_walfile(), OpenTemporaryFileInTablespace(), page_header(), parseServiceInfo(), ParseTzFile(), perform_base_backup(), PerformPortalFetch(), pg_getnameinfo_all(), pg_GSS_load_servicename(), pg_lock_status(), pg_ls_dir_files(), pg_lsn_mi(), pg_lsn_out(), pg_perm_setlocale(), pg_rusage_show(), pg_signal_thread(), pg_size_pretty(), pg_strerror_r(), pg_tablespace_location(), pg_tzenumerate_next(), pg_tzset_offset(), pgarch_ArchiverCopyLoop(), pgarch_archiveXlog(), pgarch_readyXlog(), pgfdw_subxact_callback(), pgrowlocks(), pgstat_reset_remove_files(), pgtypes_fmt_replace(), PGTYPESdate_fmt_asc(), pgwin32_create_signal_listener(), pid_lock_file_exists(), plperl_spi_prepare(), plpgsql_param_ref(), pltcl_init_interp(), pltcl_SPI_prepare(), PLy_procedure_compile(), PLy_procedure_create(), PLy_procedure_munge_source(), populate_with_dummy_strings(), PortalRun(), postgresAcquireSampleRowsFunc(), postgresReScanForeignScan(), PostmasterMain(), PQconnectPoll(), pqGetHomeDirectory(), PQsslAttribute(), prepare_foreign_modify(), preprocess_targetlist(), pretty_wal_size(), print_wchar_str(), printProgressReport(), PrintQueryStatus(), proc_exit(), process_psqlrc(), process_source_file(), process_target_file(), ProcessQuery(), progress_report(), provider_init(), psql_command(), psql_start_test(), read_client_final_message(), ReadControlFile(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), ReceiveXlogStream(), recurse_dir(), regclassout(), regconfigout(), regdictionaryout(), regnamespaceout(), regoperout(), regprocout(), regression_main(), regroleout(), regtypeout(), RelationCacheInitFilePreInvalidate(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), remove_new_subdir(), remove_target_dir(), remove_target_file(), remove_target_symlink(), RemoveAttributeById(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), RemoveTempXlogFiles(), RemoveXlogFile(), ReorderBufferCleanupSerializedTXNs(), ReorderBufferSerializedPath(), replace_variables(), report_fork_failure_to_client(), report_unmatched_relation(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), ResetUnloggedRelationsInTablespaceDir(), RestoreArchive(), RestoreArchivedFile(), results_differ(), rewind_copy_file_range(), RI_Initial_Check(), RI_PartitionRemove_Check(), rmtree(), sanitize_char(), scan_available_timezones(), scan_directory(), select_default_timezone(), send_message_to_frontend(), SendBaseBackup(), sendDir(), sendTablespace(), SendXlogRecPtrResult(), set_info_version(), set_pglocale_pgservice(), setup_background_workers(), setup_config(), SharedFilePath(), SharedFileSetPath(), SharedSegmentName(), show_data_directory_mode(), show_eval_params(), show_log_file_mode(), show_tcp_keepalives_count(), show_tcp_keepalives_idle(), show_tcp_keepalives_interval(), show_tcp_user_timeout(), show_trgm(), show_unix_socket_permissions(), SimpleXLogPageRead(), SlabStats(), SlruDeleteSegment(), SlruInternalDeleteSegment(), slurpFile(), sql_exec_dumpalldbs(), sql_exec_dumpalltables(), sql_exec_dumpalltbspc(), SSLerrmessage(), standard_ProcessUtility(), start_postmaster(), StartChildProcess(), StartLogStreamer(), StartReplication(), StartupReplicationSlots(), StartupXLOG(), stop_postmaster(), StreamServerPort(), sts_filename(), SyncVariables(), SysLogger_Start(), tar_open_for_write(), TempTablespacePath(), test_config_settings(), threadRun(), tidout(), timeofday(), timestamptz_to_str(), transfer_relfile(), transformRowExpr(), transformSetOperationTree(), truncate_target_file(), update_controlfile(), uuid_generate_internal(), uuid_generate_v1mc(), vacuumlo(), validate_exec(), ValidatePgVersion(), ValidateXLOGDirectoryStructure(), VXIDGetDatum(), wait_result_to_str(), walkdir(), WalRcvWaitForStartPosition(), WalReceiverMain(), worker_spi_launch(), write_relcache_init_file(), write_relmap_file(), WriteRecoveryConf(), writeTimeLineHistory(), writeTimeLineHistoryFile(), xidout(), XLogArchiveIsBusy(), XLogFileCopy(), XLogFileInit(), XLogFileRead(), XLogSendPhysical(), XLOGShmemSize(), XLogWalRcvFlush(), and yesno_prompt().

◆ sprintf

#define sprintf   pg_sprintf

Definition at line 194 of file port.h.

Referenced by _ArchiveEntry(), _conv(), _PG_init(), _StartBlob(), _StartBlobs(), aclitemout(), AddISO8601IntPart(), AddPostgresIntPart(), AddVerboseIntPart(), AppendSeconds(), ApplyLogicalMappingFile(), array_dims(), array_out(), assign_pgstat_temp_directory(), BackendRun(), bootstrap_template1(), bt_page_print_tuples(), build_subplan(), build_tuplestore_recursively(), CheckPointReplicationSlots(), ChooseIndexColumnNames(), CreateFakeRelcacheEntry(), CreateNewPortal(), CreateSlotOnDisk(), CreateWalTarMethod(), DCH_to_char(), deallocate_one(), do_kill(), do_lo_import(), doabbr(), ecpg_auto_prepare(), ecpg_build_native_sqlda(), ecpg_build_params(), ecpg_is_type_an_array(), ecpg_store_input(), ECPGdump_a_simple(), ECPGdump_a_struct(), EncodeDateOnly(), EncodeDateTime(), EncodeInterval(), encodingid_to_string(), find_in_dynamic_libpath(), fmtfloat(), fmtptr(), generate_normalized_query(), get_comma_elts(), get_str_from_var(), getNextFlagFromString(), gtsvectorout(), hashline_number(), infix(), initialize_environment(), initialize_worker_spi(), InitializeGUCOptionsFromEnvironment(), InternalIpcMemoryCreate(), LaunchParallelWorkers(), lquery_out(), main(), make_absolute_path(), make_colname_unique(), mdunlinkfork(), MergeAffix(), NIAddAffix(), NUM_processor(), num_word(), oidvectorout(), optionListToArray(), parseQuery(), pg_get_userbyid(), pg_regerror(), pg_strfromd(), pg_wcsformat(), PGTYPESnumeric_from_double(), pgwin32_unsetenv(), plperl_create_sub(), PortalRunMulti(), pqInternalNotice(), PQprintTuples(), PQsetClientEncoding(), pqSetenvPoll(), preparedStatementName(), print_double(), prs_process_call(), ReceiveXlogStream(), regoperout(), regression_main(), ReorderBufferCleanupSerializedTXNs(), ReplicationSlotDropPtr(), ReplicationSlotSave(), report_invalid_encoding(), report_untranslatable_char(), restore(), RestoreSlotFromDisk(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_restrict(), ri_set(), rstacktoodeep(), SaveSlotToPath(), scram_build_verifier(), seg_out(), SelectConfigFiles(), send_int8_string(), set_debug_options(), set_ps_display(), set_rtable_names(), SetOutput(), setup_background_workers(), setup_config(), setup_formatted_log_time(), SnapBuildRestore(), SnapBuildSerialize(), SPI_result_code_string(), sprintf_double_value(), sprintf_float_value(), sql_check(), sql_exec_searchtables(), stringoffset(), stringrule(), SyncRepWaitForLSN(), tarOpen(), transformRelOptions(), ts_process_call(), tsvectorout(), tt_process_call(), ttdummy(), unsetenv(), winsock_strerror(), worker_spi_launch(), WriteToc(), and yearistype().

◆ SSL_get_current_compression

#define SSL_get_current_compression (   x)    0

Definition at line 449 of file port.h.

Referenced by be_tls_get_compression(), and PQsslAttribute().

◆ strerror

#define strerror   pg_strerror

Definition at line 205 of file port.h.

Referenced by _tarReadRaw(), adjust_data_dir(), cfgetc(), cfread(), change_directory(), check_bin_dir(), check_errno(), check_file_clone(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_hard_link(), check_loadable_libraries(), check_ok(), check_single_dir(), checkControlFile(), CheckForExternalTrigger(), cloneFile(), close_file(), convert_sourcefiles_in(), copyFile(), create_script_for_cluster_analyze(), create_script_for_old_cluster_deletion(), CustomizableCleanupPriorWALFiles(), dir_getlasterror(), do_edit(), do_kill(), do_logrotate(), do_promote(), do_reload(), do_restart(), do_stop(), dolink(), exec_command_cd(), file_line_count(), file_size(), get_bin_version(), get_cfp_error(), get_control_data(), get_pgpid(), get_sock_dir(), get_tablespace_paths(), get_user_name(), gnuish_strerror_r(), ident_inet(), infile(), initialize_environment(), linkFile(), load_resultmap(), main(), make_absolute_path(), make_directory(), memcheck(), mkdirs(), new_9_0_populate_pg_largeobject_metadata(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), open_file_in_directory(), open_result_files(), parallel_exec_prog(), parallel_transfer_all_new_dbs(), pid_lock_file_exists(), PostmasterMain(), PostmasterMarkPIDForWorkerNotify(), process_file(), pvsnprintf(), reap_child(), regression_main(), report_fork_failure_to_client(), results_differ(), rewriteVisibilityMap(), run_schedule(), scan_available_timezones(), search_directory(), SelectConfigFiles(), SetWALSegSize(), spawn_process(), start_postmaster(), stop_postmaster(), tablespace_list_append(), tar_getlasterror(), threadRun(), tokenize_file(), tokenize_inc_file(), transfer_relfile(), trap_sigint_during_startup(), try_complete_step(), validate_exec(), wait_for_tests(), write_syslogger_file(), writezone(), and XLogDumpXLogRead().

◆ strerror_r

◆ TIMEZONE_GLOBAL

#define TIMEZONE_GLOBAL   timezone

Definition at line 226 of file port.h.

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

◆ TZNAME_GLOBAL

#define TZNAME_GLOBAL   tzname

Definition at line 227 of file port.h.

Referenced by abstime2tm(), and timestamp2tm().

◆ USE_REPL_SNPRINTF

#define USE_REPL_SNPRINTF   1

Definition at line 142 of file port.h.

◆ vfprintf

#define vfprintf   pg_vfprintf

Definition at line 195 of file port.h.

Referenced by ecpg_log(), pg_log_generic_v(), print_lo_result(), status(), verror(), and write_stderr().

◆ vprintf

#define vprintf   pg_vprintf

Definition at line 197 of file port.h.

Referenced by appendStringInfo().

◆ vsnprintf

◆ vsprintf

#define vsprintf   pg_vsprintf

Definition at line 193 of file port.h.

Typedef Documentation

◆ pgsocket

Definition at line 31 of file port.h.

◆ pqsigfunc

typedef void(* pqsigfunc) (int signo)

Definition at line 525 of file port.h.

◆ qsort_arg_comparator

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

Definition at line 493 of file port.h.

Function Documentation

◆ canonicalize_path()

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(), check_required_directory(), 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(), get_tablespace_mapping(), 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

◆ cleanup_path()

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

◆ crypt()

char* crypt ( const char *  key,
const char *  setting 
)

Definition at line 488 of file crypt.c.

References __bcrypt(), __md5crypt(), _PASSWORD_EFMT1, a64toi, C_block::b, cryptresult, des_cipher(), des_setkey(), i, and itoa64.

489 {
490  char *encp;
491  int32_t i;
492  int t;
493  int32_t salt;
494  int num_iter,
495  salt_size;
496  C_block keyblock,
497  rsltblock;
498 
499 #if 0
500  /* Non-DES encryption schemes hook in here. */
501  if (setting[0] == _PASSWORD_NONDES)
502  {
503  switch (setting[1])
504  {
505  case '2':
506  return (__bcrypt(key, setting));
507  case '1':
508  default:
509  return (__md5crypt(key, setting));
510  }
511  }
512 #endif
513 
514  for (i = 0; i < 8; i++)
515  {
516  if ((t = 2 * (unsigned char) (*key)) != 0)
517  key++;
518  keyblock.b[i] = t;
519  }
520  if (des_setkey((char *) keyblock.b)) /* also initializes "a64toi" */
521  return (NULL);
522 
523  encp = &cryptresult[0];
524  switch (*setting)
525  {
526  case _PASSWORD_EFMT1:
527 
528  /*
529  * Involve the rest of the password 8 characters at a time.
530  */
531  while (*key)
532  {
533  if (des_cipher((char *) (void *) &keyblock,
534  (char *) (void *) &keyblock, 0L, 1))
535  return (NULL);
536  for (i = 0; i < 8; i++)
537  {
538  if ((t = 2 * (unsigned char) (*key)) != 0)
539  key++;
540  keyblock.b[i] ^= t;
541  }
542  if (des_setkey((char *) keyblock.b))
543  return (NULL);
544  }
545 
546  *encp++ = *setting++;
547 
548  /* get iteration count */
549  num_iter = 0;
550  for (i = 4; --i >= 0;)
551  {
552  if ((t = (unsigned char) setting[i]) == '\0')
553  t = '.';
554  encp[i] = t;
555  num_iter = (num_iter << 6) | a64toi[t];
556  }
557  setting += 4;
558  encp += 4;
559  salt_size = 4;
560  break;
561  default:
562  num_iter = 25;
563  salt_size = 2;
564  }
565 
566  salt = 0;
567  for (i = salt_size; --i >= 0;)
568  {
569  if ((t = (unsigned char) setting[i]) == '\0')
570  t = '.';
571  encp[i] = t;
572  salt = (salt << 6) | a64toi[t];
573  }
574  encp += salt_size;
575  if (des_cipher((char *) (void *) &constdatablock,
576  (char *) (void *) &rsltblock, salt, num_iter))
577  return (NULL);
578 
579  /*
580  * Encode the 64 cipher bits as 11 ascii characters.
581  */
582  i = ((int32_t) ((rsltblock.b[0] << 8) | rsltblock.b[1]) << 8) |
583  rsltblock.b[2];
584  encp[3] = itoa64[i & 0x3f];
585  i >>= 6;
586  encp[2] = itoa64[i & 0x3f];
587  i >>= 6;
588  encp[1] = itoa64[i & 0x3f];
589  i >>= 6;
590  encp[0] = itoa64[i];
591  encp += 4;
592  i = ((int32_t) ((rsltblock.b[3] << 8) | rsltblock.b[4]) << 8) |
593  rsltblock.b[5];
594  encp[3] = itoa64[i & 0x3f];
595  i >>= 6;
596  encp[2] = itoa64[i & 0x3f];
597  i >>= 6;
598  encp[1] = itoa64[i & 0x3f];
599  i >>= 6;
600  encp[0] = itoa64[i];
601  encp += 4;
602  i = ((int32_t) ((rsltblock.b[6]) << 8) | rsltblock.b[7]) << 2;
603  encp[2] = itoa64[i & 0x3f];
604  i >>= 6;
605  encp[1] = itoa64[i & 0x3f];
606  i >>= 6;
607  encp[0] = itoa64[i];
608 
609  encp[3] = 0;
610 
611  return (cryptresult);
612 }
static unsigned char a64toi[128]
Definition: crypt.c:455
static int des_setkey(const char *key)
Definition: crypt.c:627
static C_block constdatablock
Definition: crypt.c:476
static const unsigned char itoa64[]
Definition: crypt.c:448
#define _PASSWORD_EFMT1
Definition: crypt.c:112
char * __md5crypt(const char *, const char *)
char * __bcrypt(const char *, const char *)
int i
static int des_cipher(const char *in, char *out, long salt, int num_iter)
Definition: crypt.c:659
static char cryptresult[1+4+4+11+1]
Definition: crypt.c:477
int int32_t
Definition: crypt.c:108
unsigned char b[8]
Definition: crypt.c:230
Definition: crypt.c:228

◆ dlclose()

int dlclose ( void *  handle)

◆ dlerror()

char* dlerror ( void  )

Referenced by internal_load_library().

◆ dlopen()

void* dlopen ( const char *  file,
int  mode 
)

Referenced by internal_load_library().

◆ dlsym()

void* dlsym ( void *  handle,
const char *  symbol 
)

◆ escape_single_quotes_ascii()

char* escape_single_quotes_ascii ( const char *  src)

Definition at line 33 of file quotes.c.

References i, malloc, 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 }
#define malloc(a)
Definition: header.h:50
int i
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1069

◆ find_my_exec()

int find_my_exec ( const char *  argv0,
char *  retpath 
)

Definition at line 129 of file exec.c.

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

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

130 {
131  char cwd[MAXPGPATH],
132  test_path[MAXPGPATH];
133  char *path;
134 
135  if (!getcwd(cwd, MAXPGPATH))
136  {
138  _("could not identify current directory: %m"));
139  return -1;
140  }
141 
142  /*
143  * If argv0 contains a separator, then PATH wasn't used.
144  */
145  if (first_dir_separator(argv0) != NULL)
146  {
147  if (is_absolute_path(argv0))
148  StrNCpy(retpath, argv0, MAXPGPATH);
149  else
150  join_path_components(retpath, cwd, argv0);
151  canonicalize_path(retpath);
152 
153  if (validate_exec(retpath) == 0)
154  return resolve_symlinks(retpath);
155 
156  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
157  _("invalid binary \"%s\""), retpath);
158  return -1;
159  }
160 
161 #ifdef WIN32
162  /* Win32 checks the current directory first for names without slashes */
163  join_path_components(retpath, cwd, argv0);
164  if (validate_exec(retpath) == 0)
165  return resolve_symlinks(retpath);
166 #endif
167 
168  /*
169  * Since no explicit path was supplied, the user must have been relying on
170  * PATH. We'll search the same PATH.
171  */
172  if ((path = getenv("PATH")) && *path)
173  {
174  char *startp = NULL,
175  *endp = NULL;
176 
177  do
178  {
179  if (!startp)
180  startp = path;
181  else
182  startp = endp + 1;
183 
184  endp = first_path_var_separator(startp);
185  if (!endp)
186  endp = startp + strlen(startp); /* point to end */
187 
188  StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
189 
190  if (is_absolute_path(test_path))
191  join_path_components(retpath, test_path, argv0);
192  else
193  {
194  join_path_components(retpath, cwd, test_path);
195  join_path_components(retpath, retpath, argv0);
196  }
197  canonicalize_path(retpath);
198 
199  switch (validate_exec(retpath))
200  {
201  case 0: /* found ok */
202  return resolve_symlinks(retpath);
203  case -1: /* wasn't even a candidate, keep looking */
204  break;
205  case -2: /* found but disqualified */
206  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
207  _("could not read binary \"%s\""),
208  retpath);
209  break;
210  }
211  } while (*endp);
212  }
213 
214  log_error(errcode(ERRCODE_UNDEFINED_FILE),
215  _("could not find a \"%s\" to execute"), argv0);
216  return -1;
217 }
static char * argv0
Definition: pg_ctl.c:96
static int resolve_symlinks(char *path)
Definition: exec.c:232
#define Min(x, y)
Definition: c.h:890
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:570
#define log_error(errcodefn,...)
Definition: exec.c:41
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:68
int errcode_for_file_access(void)
Definition: elog.c:593
#define is_absolute_path(filename)
Definition: port.h:86
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define StrNCpy(dst, src, len)
Definition: c.h:914
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
#define _(x)
Definition: elog.c:84
char * first_path_var_separator(const char *pathlist)
Definition: path.c:120

◆ find_other_exec()

int find_other_exec ( const char *  argv0,
const char *  target,
const char *  versionstr,
char *  retpath 
)

Definition at line 324 of file exec.c.

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

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

326 {
327  char cmd[MAXPGPATH];
328  char line[MAXPGPATH];
329 
330  if (find_my_exec(argv0, retpath) < 0)
331  return -1;
332 
333  /* Trim off program name and keep just directory */
334  *last_dir_separator(retpath) = '\0';
335  canonicalize_path(retpath);
336 
337  /* Now append the other program's name */
338  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
339  "/%s%s", target, EXE);
340 
341  if (validate_exec(retpath) != 0)
342  return -1;
343 
344  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
345 
346  if (!pipe_read_line(cmd, line, sizeof(line)))
347  return -1;
348 
349  if (strcmp(line, versionstr) != 0)
350  return -2;
351 
352  return 0;
353 }
static char * argv0
Definition: pg_ctl.c:96
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
static int validate_exec(const char *path)
Definition: exec.c:68
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define EXE
Definition: port.h:117
#define snprintf
Definition: port.h:192
static char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:365

◆ first_dir_separator()

char* first_dir_separator ( const char *  filename)

Definition at line 103 of file path.c.

References IS_DIR_SEP, skip_drive, and unconstify.

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 unconstify(char *, p);
110  return NULL;
111 }
#define skip_drive(path)
Definition: path.c:78
#define IS_DIR_SEP(ch)
Definition: port.h:84
#define unconstify(underlying_type, expr)
Definition: c.h:1149
static char * filename
Definition: pg_dumpall.c:91

◆ first_path_var_separator()

char* first_path_var_separator ( const char *  pathlist)

Definition at line 120 of file path.c.

References IS_PATH_VAR_SEP, and unconstify.

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 unconstify(char *, p);
128  return NULL;
129 }
#define unconstify(underlying_type, expr)
Definition: c.h:1149
#define IS_PATH_VAR_SEP(ch)
Definition: path.c:42

◆ fls()

int fls ( int  mask)

Definition at line 55 of file fls.c.

References bit().

Referenced by _hash_get_oldblock_from_newbucket(), add_paths_to_append_rel(), and generate_union_paths().

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:363

◆ get_doc_path()

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:72

◆ get_etc_path()

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:72

◆ get_home_path()

bool get_home_path ( char *  ret_path)

Definition at line 807 of file path.c.

References MAXPGPATH, 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 }
#define MAXPGPATH
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:68
#define snprintf
Definition: port.h:192

◆ get_html_path()

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:72

◆ get_include_path()

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:72

◆ get_includeserver_path()

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:72

◆ get_lib_path()

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:72

◆ get_locale_path()

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:72

◆ get_man_path()

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:72

◆ get_parent_directory()

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

◆ get_pkginclude_path()

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:72

◆ get_pkglib_path()

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:72

◆ get_progname()

const char* get_progname ( const char *  argv0)

Definition at line 453 of file path.c.

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

Referenced by get_opts(), handle_help_version_opts(), main(), parseCommandLine(), pg_logging_init(), 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:96
#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
#define fprintf
Definition: port.h:196
char * last_dir_separator(const char *filename)
Definition: path.c:138
#define EXE
Definition: port.h:117

◆ get_share_path()

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:72

◆ getpeereid()

int getpeereid ( int  sock,
uid_t uid,
gid_t gid 
)

Definition at line 35 of file getpeereid.c.

Referenced by ident_inet(), and 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 uid_t
Definition: win32_port.h:239
int gid_t
Definition: win32_port.h:240

◆ has_drive_prefix()

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

◆ inet_aton()

int inet_aton ( const char *  cp,
struct in_addr *  addr 
)

Definition at line 56 of file inet_aton.c.

References pg_hton32, and val.

Referenced by getaddrinfo().

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

◆ inet_net_ntop()

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(), PGSQL_AF_INET, and PGSQL_AF_INET6.

Referenced by getHostaddr(), 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_port.h:336
static char * inet_net_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size)

◆ isinf()

◆ join_path_components()

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
#define IS_DIR_SEP(ch)
Definition: port.h:84
#define MAXPGPATH
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define snprintf
Definition: port.h:192

◆ last_dir_separator()

char* last_dir_separator ( const char *  filename)

Definition at line 138 of file path.c.

References IS_DIR_SEP, skip_drive, and unconstify.

Referenced by check_file_excluded(), ECPGconnect(), find_other_exec(), get_progname(), main(), resolve_symlinks(), sendDir(), sendFile(), 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 unconstify(char *, ret);
147 }
#define skip_drive(path)
Definition: path.c:78
#define IS_DIR_SEP(ch)
Definition: port.h:84
#define unconstify(underlying_type, expr)
Definition: c.h:1149
static char * filename
Definition: pg_dumpall.c:91

◆ make_absolute_path()

char* make_absolute_path ( const char *  path)

Definition at line 608 of file path.c.

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

Referenced by do_kill(), 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:570
#define fprintf
Definition: port.h:196
#define malloc(a)
Definition: header.h:50
#define sprintf
Definition: port.h:194
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:68
#define is_absolute_path(filename)
Definition: port.h:86
#define ereport(elevel, rest)
Definition: elog.h:141
#define free(a)
Definition: header.h:65
#define strerror
Definition: port.h:205
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define _(x)
Definition: elog.c:84

◆ make_native_path()

void make_native_path ( char *  path)

Definition at line 166 of file path.c.

Referenced by do_kill(), 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:91

◆ mkdtemp()

char* mkdtemp ( char *  path)

Definition at line 286 of file mkdtemp.c.

References _DIAGASSERT, and GETTEMP().

Referenced by stop_postmaster().

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

◆ path_contains_parent_reference()

bool path_contains_parent_reference ( const char *  path)

Definition at line 376 of file path.c.

References 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

◆ path_is_prefix_of_path()

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:84

◆ path_is_relative_and_below_cwd()

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:84
bool path_contains_parent_reference(const char *path)
Definition: path.c:376
#define is_absolute_path(filename)
Definition: port.h:86

◆ pclose_check()

int pclose_check ( FILE *  stream)

Definition at line 527 of file exec.c.

References _, errcode(), log_error, pfree(), and wait_result_to_str().

Referenced by pipe_read_line().

528 {
529  int exitstatus;
530  char *reason;
531 
532  exitstatus = pclose(stream);
533 
534  if (exitstatus == 0)
535  return 0; /* all is well */
536 
537  if (exitstatus == -1)
538  {
539  /* pclose() itself failed, and hopefully set errno */
540  log_error(errcode(ERRCODE_SYSTEM_ERROR),
541  _("pclose failed: %m"));
542  }
543  else
544  {
545  reason = wait_result_to_str(exitstatus);
546  log_error(errcode(ERRCODE_SYSTEM_ERROR),
547  "%s", reason);
548  pfree(reason);
549  }
550  return exitstatus;
551 }
int errcode(int sqlerrcode)
Definition: elog.c:570
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
void pfree(void *pointer)
Definition: mcxt.c:1031
#define log_error(errcodefn,...)
Definition: exec.c:41
#define _(x)
Definition: elog.c:84

◆ pg_ascii_tolower()

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 }

◆ pg_ascii_toupper()

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 }

◆ pg_check_dir()

int pg_check_dir ( const char *  dir)

Definition at line 31 of file pgcheckdir.c.

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

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
Definition: dirent.h:9
Definition: dirent.c:25
DIR * opendir(const char *)
Definition: dirent.c:33
struct dirent * readdir(DIR *)
Definition: dirent.c:77
char d_name[MAX_PATH]
Definition: dirent.h:14

◆ pg_erand48()

double pg_erand48 ( unsigned short  xseed[3])

Definition at line 88 of file erand48.c.

References _dorand48().

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

89 {
90  uint64 x = _dorand48(xseed);
91 
92  return ldexp((double) (x & UINT64CONST(0xFFFFFFFFFFFF)), -48);
93 }
static uint64 _dorand48(unsigned short xseed[3])
Definition: erand48.c:63

◆ pg_fprintf()

int pg_fprintf ( FILE *  stream,
const char *  fmt,
  ... 
)

◆ pg_get_encoding_from_locale()

int pg_get_encoding_from_locale ( const char *  ctype,
bool  write_message 
)

◆ pg_jrand48()

long pg_jrand48 ( unsigned short  xseed[3])

Definition at line 112 of file erand48.c.

References _dorand48().

Referenced by initRandomState(), and main().

113 {
114  uint64 x = _dorand48(xseed);
115 
116  return (int32) ((x >> 16) & UINT64CONST(0xFFFFFFFF));
117 }
signed int int32
Definition: c.h:346
static uint64 _dorand48(unsigned short xseed[3])
Definition: erand48.c:63

◆ pg_lrand48()

long pg_lrand48 ( void  )

Definition at line 100 of file erand48.c.

References _dorand48(), and _rand48_seed.

Referenced by random(), test_huge_distances(), and test_pattern().

101 {
102  uint64 x = _dorand48(_rand48_seed);
103 
104  return (x >> 17) & UINT64CONST(0x7FFFFFFF);
105 }
static unsigned short _rand48_seed[3]
Definition: erand48.c:49
static uint64 _dorand48(unsigned short xseed[3])
Definition: erand48.c:63

◆ pg_mkdir_p()

int pg_mkdir_p ( char *  path,
int  omode 
)

Definition at line 57 of file pgmkdirp.c.

References mkdir, S_IRWXG, S_IRWXO, S_IRWXU, S_ISDIR, S_IWUSR, S_IXUSR, and stat.

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 S_IXUSR
Definition: win32_port.h:275
#define S_IWUSR
Definition: win32_port.h:272
#define S_IRWXG
Definition: win32_port.h:290
#define stat(a, b)
Definition: win32_port.h:264
#define S_ISDIR(m)
Definition: win32_port.h:305
#define S_IRWXU
Definition: win32_port.h:278
#define mkdir(a, b)
Definition: win32_port.h:58
#define S_IRWXO
Definition: win32_port.h:302

◆ pg_pread()

ssize_t pg_pread ( int  fd,
void *  buf,
size_t  nbyte,
off_t  offset 
)

Definition at line 27 of file pread.c.

References _dosmaperr(), and read.

Referenced by FileRead(), and XLogPageRead().

28 {
29 #ifdef WIN32
30  OVERLAPPED overlapped = {0};
31  HANDLE handle;
32  DWORD result;
33 
34  handle = (HANDLE) _get_osfhandle(fd);
35  if (handle == INVALID_HANDLE_VALUE)
36  {
37  errno = EBADF;
38  return -1;
39  }
40 
41  overlapped.Offset = offset;
42  if (!ReadFile(handle, buf, size, &result, &overlapped))
43  {
44  _dosmaperr(GetLastError());
45  return -1;
46  }
47 
48  return result;
49 #else
50  if (lseek(fd, offset, SEEK_SET) < 0)
51  return -1;
52 
53  return read(fd, buf, size);
54 #endif
55 }
void _dosmaperr(unsigned long)
Definition: win32error.c:171
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static char * buf
Definition: pg_test_fsync.c:68
#define read(a, b, c)
Definition: win32.h:13

◆ pg_printf()

int pg_printf ( const char *  fmt,
  ... 
)

◆ pg_pwrite()

ssize_t pg_pwrite ( int  fd,
const void *  buf,
size_t  nbyte,
off_t  offset 
)

Definition at line 27 of file pwrite.c.

References _dosmaperr(), and write.

Referenced by FileWrite(), XLogFileInit(), and XLogWrite().

28 {
29 #ifdef WIN32
30  OVERLAPPED overlapped = {0};
31  HANDLE handle;
32  DWORD result;
33 
34  handle = (HANDLE) _get_osfhandle(fd);
35  if (handle == INVALID_HANDLE_VALUE)
36  {
37  errno = EBADF;
38  return -1;
39  }
40 
41  overlapped.Offset = offset;
42  if (!WriteFile(handle, buf, size, &result, &overlapped))
43  {
44  _dosmaperr(GetLastError());
45  return -1;
46  }
47 
48  return result;
49 #else
50  if (lseek(fd, offset, SEEK_SET) < 0)
51  return -1;
52 
53  return write(fd, buf, size);
54 #endif
55 }
#define write(a, b, c)
Definition: win32.h:14
void _dosmaperr(unsigned long)
Definition: win32error.c:171
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static char * buf
Definition: pg_test_fsync.c:68

◆ pg_qsort()

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 apw_load_buffers(), build_distinct_groups(), 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:890
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

◆ pg_qsort_strcmp()

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 }

◆ pg_set_block()

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 }

◆ pg_set_noblock()

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 }

◆ pg_snprintf()

int pg_snprintf ( char *  str,
size_t  count,
const char *  fmt,
  ... 
)

◆ pg_sprintf()

int pg_sprintf ( char *  str,
const char *  fmt,
  ... 
)

◆ pg_srand48()

void pg_srand48 ( long  seed)

Definition at line 131 of file erand48.c.

References _rand48_seed, and RAND48_SEED_0.

Referenced by srandom().

132 {
134  _rand48_seed[1] = (unsigned short) seed;
135  _rand48_seed[2] = (unsigned short) (seed >> 16);
136 }
static unsigned short _rand48_seed[3]
Definition: erand48.c:49
#define RAND48_SEED_0
Definition: erand48.c:45

◆ pg_strcasecmp()

int pg_strcasecmp ( const char *  s1,
const char *  s2 
)

Definition at line 36 of file pgstrcasecmp.c.

References IS_HIGHBIT_SET.

Referenced by array_out(), ATExecSetStorage(), build_startup_packet(), cache_locale_time(), check_datestyle(), check_ddl_tag(), check_ident_usermap(), check_log_destination(), check_table_rewrite_ddl_tag(), check_usermap(), check_wal_consistency_checking(), CheckSCRAMAuth(), comp_keyword_case_hook(), config_enum_lookup_by_name(), convert_any_priv_string(), convert_priv_string(), defGetBoolean(), defGetTypeLength(), DefineAggregate(), DefineCollation(), DefineType(), do_kill(), do_pset(), echo_hidden_hook(), echo_hook(), equivalent_locale(), evaluateSleep(), exec_command(), find_matching_ts_config(), get_progname(), getMetaCommand(), helpSQL(), histcontrol_hook(), hostname_match(), locate_stem_module(), lookup_prop_name(), main(), makeVariableValue(), on_error_rollback_hook(), parse_hstore(), parse_slash_copy(), parseArchiveFormat(), parseNameAndArgTypes(), ParseVariableBool(), pg_fe_sendauth(), pg_find_encoding(), 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(), pq_verify_peer_name_matches_certificate_name(), pqPacketSend(), pqSetenvPoll(), process_backslash_command(), prsd_headline(), px_find_digest(), px_gen_salt(), px_resolve_alias(), ReadArrayStr(), SetMessageEncoding(), show_context_hook(), splitTzLine(), SyncRepGetStandbyPriority(), transformPartitionSpec(), validate_exec(), variable_is_guc_list_quote(), verbosity_hook(), 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:1061
char * s1
char * s2

◆ pg_strerror()

char* pg_strerror ( int  errnum)

Definition at line 35 of file strerror.c.

References pg_strerror_r(), and PG_STRERROR_R_BUFLEN.

36 {
37  static char errorstr_buf[PG_STRERROR_R_BUFLEN];
38 
39  return pg_strerror_r(errnum, errorstr_buf, sizeof(errorstr_buf));
40 }
#define PG_STRERROR_R_BUFLEN
Definition: port.h:210
char * pg_strerror_r(int errnum, char *buf, size_t buflen)
Definition: strerror.c:46

◆ pg_strerror_r()

char* pg_strerror_r ( int  errnum,
char *  buf,
size_t  buflen 
)

Definition at line 46 of file strerror.c.

References _, buf, get_errno_symbol(), gnuish_strerror_r(), snprintf, and generate_unaccent_rules::str.

Referenced by pg_strerror().

47 {
48  char *str;
49 
50  /* If it's a Windows Winsock error, that needs special handling */
51 #ifdef WIN32
52  /* Winsock error code range, per WinError.h */
53  if (errnum >= 10000 && errnum <= 11999)
54  return win32_socket_strerror(errnum, buf, buflen);
55 #endif
56 
57  /* Try the platform's strerror_r(), or maybe just strerror() */
58  str = gnuish_strerror_r(errnum, buf, buflen);
59 
60  /*
61  * Some strerror()s return an empty string for out-of-range errno. This
62  * is ANSI C spec compliant, but not exactly useful. Also, we may get
63  * back strings of question marks if libc cannot transcode the message to
64  * the codeset specified by LC_CTYPE. If we get nothing useful, first try
65  * get_errno_symbol(), and if that fails, print the numeric errno.
66  */
67  if (str == NULL || *str == '\0' || *str == '?')
68  str = get_errno_symbol(errnum);
69 
70  if (str == NULL)
71  {
72  snprintf(buf, buflen, _("operating system error %d"), errnum);
73  str = buf;
74  }
75 
76  return str;
77 }
static char * buf
Definition: pg_test_fsync.c:68
static char * get_errno_symbol(int errnum)
Definition: strerror.c:113
static char * gnuish_strerror_r(int errnum, char *buf, size_t buflen)
Definition: strerror.c:85
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:84

◆ pg_strfromd()

int pg_strfromd ( char *  str,
size_t  count,
int  precision,
double  value 
)

Definition at line 1265 of file snprintf.c.

References Assert, PrintfTarget::bufend, PrintfTarget::bufptr, PrintfTarget::bufstart, convert(), dopr_outch(), dostr(), PrintfTarget::failed, isinf(), PrintfTarget::nchars, sprintf, generate_unaccent_rules::str, PrintfTarget::stream, and value.

Referenced by float4out(), and float8out_internal().

1266 {
1267  PrintfTarget target;
1268  int signvalue = 0;
1269  int vallen;
1270  char fmt[8];
1271  char convert[64];
1272 
1273  /* Set up the target like pg_snprintf, but require nonempty buffer */
1274  Assert(count > 0);
1275  target.bufstart = target.bufptr = str;
1276  target.bufend = str + count - 1;
1277  target.stream = NULL;
1278  target.nchars = 0;
1279  target.failed = false;
1280 
1281  /*
1282  * We bound precision to a reasonable range; the combination of this and
1283  * the knowledge that we're using "g" format without padding allows the
1284  * convert[] buffer to be reasonably small.
1285  */
1286  if (precision < 1)
1287  precision = 1;
1288  else if (precision > 32)
1289  precision = 32;
1290 
1291  /*
1292  * The rest is just an inlined version of the fmtfloat() logic above,
1293  * simplified using the knowledge that no padding is wanted.
1294  */
1295  if (isnan(value))
1296  {
1297  strcpy(convert, "NaN");
1298  vallen = 3;
1299  }
1300  else
1301  {
1302  static const double dzero = 0.0;
1303 
1304  if (value < 0.0 ||
1305  (value == 0.0 &&
1306  memcmp(&value, &dzero, sizeof(double)) != 0))
1307  {
1308  signvalue = '-';
1309  value = -value;
1310  }
1311 
1312  if (isinf(value))
1313  {
1314  strcpy(convert, "Infinity");
1315  vallen = 8;
1316  }
1317  else
1318  {
1319  fmt[0] = '%';
1320  fmt[1] = '.';
1321  fmt[2] = '*';
1322  fmt[3] = 'g';
1323  fmt[4] = '\0';
1324  vallen = sprintf(convert, fmt, precision, value);
1325  if (vallen < 0)
1326  {
1327  target.failed = true;
1328  goto fail;
1329  }
1330 
1331 #ifdef WIN32
1332  if (vallen >= 6 &&
1333  convert[vallen - 5] == 'e' &&
1334  convert[vallen - 3] == '0')
1335  {
1336  convert[vallen - 3] = convert[vallen - 2];
1337  convert[vallen - 2] = convert[vallen - 1];
1338  vallen--;
1339  }
1340 #endif
1341  }
1342  }
1343 
1344  if (signvalue)
1345  dopr_outch(signvalue, &target);
1346 
1347  dostr(convert, vallen, &target);
1348 
1349 fail:
1350  *(target.bufptr) = '\0';
1351  return target.failed ? -1 : (target.bufptr - target.bufstart
1352  + target.nchars);
1353 }
char * bufend
Definition: snprintf.c:129
static void dopr_outch(int c, PrintfTarget *target)
Definition: snprintf.c:1394
static struct @144 value
static void dostr(const char *str, int slen, PrintfTarget *target)
Definition: snprintf.c:1357
char * bufstart
Definition: snprintf.c:128
#define sprintf
Definition: port.h:194
static void convert(const int32 val, char *const buf)
Definition: zic.c:1927
int isinf(double x)
FILE * stream
Definition: snprintf.c:131
bool failed
Definition: snprintf.c:133
#define Assert(condition)
Definition: c.h:732
char * bufptr
Definition: snprintf.c:127

◆ pg_strncasecmp()

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 check_datestyle(), check_ddl_tag(), check_special_value(), check_timezone(), command_no_begin(), do_pset(), equivalent_locale(), float4in(), float8in_internal_opt_error(), helpSQL(), is_select_command(), MainLoop(), makeVariableValue(), map_sql_identifier_to_xml_name(), numeric_in(), parse_bool_with_len(), parse_jsonb_index_flags(), parse_or_operator(), ParseTzFile(), ParseVariableBool(), pqPacketSend(), range_parse(), scan_directory_ci(), set_unicode_line_style(), set_var_from_str(), and SpecialTags().

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:1061
char * s1
char * s2

◆ pg_strong_random()

bool pg_strong_random ( void *  buf,
size_t  len 
)

Definition at line 100 of file pg_strong_random.c.

References i.

Referenced by BootStrapXLOG(), build_client_first_message(), build_server_first_message(), CheckMD5Auth(), drandom(), gen_random_uuid(), init_sess_key(), InitProcessGlobals(), mp_px_rand(), pad_eme_pkcs1_v15(), PerformRadiusTransaction(), pg_be_scram_build_verifier(), pg_fe_scram_build_verifier(), pg_random_bytes(), pgp_s2k_fill(), px_gen_salt(), RandomCancelKey(), set_random_seed(), and write_prefix().

101 {
102  /*
103  * When built with OpenSSL, use OpenSSL's RAND_bytes function.
104  */
105 #if defined(USE_OPENSSL_RANDOM)
106  int i;
107 
108  /*
109  * Check that OpenSSL's CSPRNG has been sufficiently seeded, and if not
110  * add more seed data using RAND_poll(). With some older versions of
111  * OpenSSL, it may be necessary to call RAND_poll() a number of times.
112  */
113 #define NUM_RAND_POLL_RETRIES 8
114 
115  for (i = 0; i < NUM_RAND_POLL_RETRIES; i++)
116  {
117  if (RAND_status() == 1)
118  {
119  /* The CSPRNG is sufficiently seeded */
120  break;
121  }
122 
123  if (RAND_poll() == 0)
124  {
125  /*
126  * RAND_poll() failed to generate any seed data, which means that
127  * RAND_bytes() will probably fail. For now, just fall through
128  * and let that happen. XXX: maybe we could seed it some other
129  * way.
130  */
131  break;
132  }
133  }
134 
135  if (RAND_bytes(buf, len) == 1)
136  return true;
137  return false;
138 
139  /*
140  * Windows has CryptoAPI for strong cryptographic numbers.
141  */
142 #elif defined(USE_WIN32_RANDOM)
143  if (hProvider == 0)
144  {
145  if (!CryptAcquireContext(&hProvider,
146  NULL,
147  MS_DEF_PROV,
148  PROV_RSA_FULL,
149  CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
150  {
151  /*
152  * On failure, set back to 0 in case the value was for some reason
153  * modified.
154  */
155  hProvider = 0;
156  }
157  }
158  /* Re-check in case we just retrieved the provider */
159  if (hProvider != 0)
160  {
161  if (CryptGenRandom(hProvider, len, buf))
162  return true;
163  }
164  return false;
165 
166  /*
167  * Read /dev/urandom ourselves.
168  */
169 #elif defined(USE_DEV_URANDOM)
170  if (random_from_file("/dev/urandom", buf, len))
171  return true;
172  return false;
173 
174 #else
175  /* The autoconf script should not have allowed this */
176 #error no source of random numbers configured
177 #endif
178 }
static char * buf
Definition: pg_test_fsync.c:68
int i

◆ pg_strsignal()

const char* pg_strsignal ( int  signum)

Definition at line 37 of file pgstrsignal.c.

Referenced by log_child_failure(), LogChildExit(), pgarch_archiveXlog(), and wait_result_to_str().

38 {
39  const char *result;
40 
41  /*
42  * If we have strsignal(3), use that --- but check its result for NULL.
43  */
44 #ifdef HAVE_STRSIGNAL
45  result = strsignal(signum);
46  if (result)
47  return result;
48 #else
49 
50  /*
51  * We used to have code here to try to use sys_siglist[] if available.
52  * However, it seems that all platforms with sys_siglist[] have also had
53  * strsignal() for many years now, so that was just a waste of code.
54  */
55 #endif
56 
57  /*
58  * Fallback case: just return "unrecognized signal". Project style is for
59  * callers to print the numeric signal value along with the result of this
60  * function, so there's no need to work harder than this.
61  */
62  result = "unrecognized signal";
63  return result;
64 }

◆ pg_tolower()

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:1061

◆ pg_toupper()

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:1061

◆ pg_usleep()

void pg_usleep ( long  microsec)

Definition at line 53 of file signal.c.

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

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

54 {
56  if (WaitForSingleObject(pgwin32_signal_event,
57  (microsec < 500 ? 1 : (microsec + 500) / 1000))
58  == WAIT_OBJECT_0)
59  {
61  errno = EINTR;
62  return;
63  }
64 }
HANDLE pgwin32_signal_event
Definition: signal.c:27
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:108
#define Assert(condition)
Definition: c.h:732
#define EINTR
Definition: win32_port.h:332

◆ pg_vfprintf()

int int pg_vfprintf ( FILE *  stream,
const char *  fmt,
va_list  args 
)

Definition at line 242 of file snprintf.c.

References PrintfTarget::bufend, PrintfTarget::bufptr, PrintfTarget::bufstart, dopr(), PrintfTarget::failed, flushbuffer(), PrintfTarget::nchars, and PrintfTarget::stream.

Referenced by pg_fprintf(), pg_printf(), and pg_vprintf().

243 {
244  PrintfTarget target;
245  char buffer[1024]; /* size is arbitrary */
246 
247  if (stream == NULL)
248  {
249  errno = EINVAL;
250  return -1;
251  }
252  target.bufstart = target.bufptr = buffer;
253  target.bufend = buffer + sizeof(buffer); /* use the whole buffer */
254  target.stream = stream;
255  target.nchars = 0;
256  target.failed = false;
257  dopr(&target, fmt, args);
258  /* dump any remaining buffer contents */
259  flushbuffer(&target);
260  return target.failed ? -1 : target.nchars;
261 }
char * bufend
Definition: snprintf.c:129
char * bufstart
Definition: snprintf.c:128
static void flushbuffer(PrintfTarget *target)
Definition: snprintf.c:298
FILE * stream
Definition: snprintf.c:131
bool failed
Definition: snprintf.c:133
static void dopr(PrintfTarget *target, const char *format, va_list args)
Definition: snprintf.c:376
char * bufptr
Definition: snprintf.c:127

◆ pg_vprintf()

int int pg_vprintf ( const char *  fmt,
va_list  args 
)

Definition at line 276 of file snprintf.c.

References pg_vfprintf(), and generate_unaccent_rules::stdout.

277 {
278  return pg_vfprintf(stdout, fmt, args);
279 }
int pg_vfprintf(FILE *stream, const char *fmt, va_list args)
Definition: snprintf.c:242

◆ pg_vsnprintf()

int pg_vsnprintf ( char *  str,
size_t  count,
const char *  fmt,
va_list  args 
)

Definition at line 174 of file snprintf.c.

References PrintfTarget::bufend, PrintfTarget::bufptr, PrintfTarget::bufstart, dopr(), PrintfTarget::failed, PrintfTarget::nchars, generate_unaccent_rules::str, and PrintfTarget::stream.

Referenced by pg_snprintf().

175 {
176  PrintfTarget target;
177  char onebyte[1];
178 
179  /*
180  * C99 allows the case str == NULL when count == 0. Rather than
181  * special-casing this situation further down, we substitute a one-byte
182  * local buffer. Callers cannot tell, since the function result doesn't
183  * depend on count.
184  */
185  if (count == 0)
186  {
187  str = onebyte;
188  count = 1;
189  }
190  target.bufstart = target.bufptr = str;
191  target.bufend = str + count - 1;
192  target.stream = NULL;
193  target.nchars = 0;
194  target.failed = false;
195  dopr(&target, fmt, args);
196  *(target.bufptr) = '\0';
197  return target.failed ? -1 : (target.bufptr - target.bufstart
198  + target.nchars);
199 }
char * bufend
Definition: snprintf.c:129
char * bufstart
Definition: snprintf.c:128
FILE * stream
Definition: snprintf.c:131
bool failed
Definition: snprintf.c:133
static void dopr(PrintfTarget *target, const char *format, va_list args)
Definition: snprintf.c:376
char * bufptr
Definition: snprintf.c:127

◆ pg_vsprintf()

int int pg_vsprintf ( char *  str,
const char *  fmt,
va_list  args 
)

Definition at line 214 of file snprintf.c.

References PrintfTarget::bufend, PrintfTarget::bufptr, PrintfTarget::bufstart, dopr(), PrintfTarget::failed, PrintfTarget::nchars, generate_unaccent_rules::str, and PrintfTarget::stream.

Referenced by pg_sprintf().

215 {
216  PrintfTarget target;
217 
218  target.bufstart = target.bufptr = str;
219  target.bufend = NULL;
220  target.stream = NULL;
221  target.nchars = 0; /* not really used in this case */
222  target.failed = false;
223  dopr(&target, fmt, args);
224  *(target.bufptr) = '\0';
225  return target.failed ? -1 : (target.bufptr - target.bufstart
226  + target.nchars);
227 }
char * bufend
Definition: snprintf.c:129
char * bufstart
Definition: snprintf.c:128
FILE * stream
Definition: snprintf.c:131
bool failed
Definition: snprintf.c:133
static void dopr(PrintfTarget *target, const char *format, va_list args)
Definition: snprintf.c:376
char * bufptr
Definition: snprintf.c:127

◆ pgfnames()

char** pgfnames ( const char *  path)

Definition at line 37 of file pgfnames.c.

References closedir(), dirent::d_name, opendir(), palloc(), pg_log_warning, pstrdup(), readdir(), and repalloc().

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

38 {
39  DIR *dir;
40  struct dirent *file;
41  char **filenames;
42  int numnames = 0;
43  int fnsize = 200; /* enough for many small dbs */
44 
45  dir = opendir(path);
46  if (dir == NULL)
47  {
48  pg_log_warning("could not open directory \"%s\": %m", path);
49  return NULL;
50  }
51 
52  filenames = (char **) palloc(fnsize * sizeof(char *));
53 
54  while (errno = 0, (file = readdir(dir)) != NULL)
55  {
56  if (strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
57  {
58  if (numnames + 1 >= fnsize)
59  {
60  fnsize *= 2;
61  filenames = (char **) repalloc(filenames,
62  fnsize * sizeof(char *));
63  }
64  filenames[numnames++] = pstrdup(file->d_name);
65  }
66  }
67 
68  if (errno)
69  pg_log_warning("could not read directory \"%s\": %m", path);
70 
71  filenames[numnames] = NULL;
72 
73  if (closedir(dir))
74  pg_log_warning("could not close directory \"%s\": %m", path);
75 
76  return filenames;
77 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int closedir(DIR *)
Definition: dirent.c:113
Definition: dirent.h:9
Definition: dirent.c:25
DIR * opendir(const char *)
Definition: dirent.c:33
struct dirent * readdir(DIR *)
Definition: dirent.c:77
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
void * palloc(Size size)
Definition: mcxt.c:924
char d_name[MAX_PATH]
Definition: dirent.h:14
#define pg_log_warning(...)
Definition: pgfnames.c:24

◆ pgfnames_cleanup()

void pgfnames_cleanup ( char **  filenames)

Definition at line 86 of file pgfnames.c.

References fn(), and pfree().

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

87 {
88  char **fn;
89 
90  for (fn = filenames; *fn; fn++)
91  pfree(*fn);
92 
93  pfree(filenames);
94 }
void pfree(void *pointer)
Definition: mcxt.c:1031
static void * fn(void *arg)

◆ pqGethostbyname()

int pqGethostbyname ( const char *  name,
struct hostent *  resultbuf,
char *  buffer,
size_t  buflen,
struct hostent **  result,
int *  herrno 
)

Definition at line 90 of file thread.c.

Referenced by getaddrinfo().

95 {
96 #if defined(FRONTEND) && defined(ENABLE_THREAD_SAFETY) && defined(HAVE_GETHOSTBYNAME_R)
97 
98  /*
99  * broken (well early POSIX draft) gethostbyname_r() which returns 'struct
100  * hostent *'
101  */
102  *result = gethostbyname_r(name, resultbuf, buffer, buflen, herrno);
103  return (*result == NULL) ? -1 : 0;
104 #else
105 
106  /* no gethostbyname_r(), just use gethostbyname() */
107  *result = gethostbyname(name);
108 
109  if (*result != NULL)
110  *herrno = h_errno;
111 
112  if (*result != NULL)
113  return 0;
114  else
115  return -1;
116 #endif
117 }
const char * name
Definition: encode.c:521

◆ pqGetpwuid()

int pqGetpwuid ( uid_t  uid,
struct passwd *  resultbuf,
char *  buffer,
size_t  buflen,
struct passwd **  result 
)

Definition at line 68 of file thread.c.

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

70 {
71 #if defined(FRONTEND) && defined(ENABLE_THREAD_SAFETY) && defined(HAVE_GETPWUID_R)
72  return getpwuid_r(uid, resultbuf, buffer, buflen, result);
73 #else
74  /* no getpwuid_r() available, just use getpwuid() */
75  errno = 0;
76  *result = getpwuid(uid);
77  /* paranoia: ensure we return zero on success */
78  return (*result == NULL) ? errno : 0;
79 #endif
80 }

◆ pqsignal()

pqsigfunc pqsignal ( int  signo,
pqsigfunc  func 
)

◆ pqsignal_no_restart()

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 SIGCHLD
Definition: win32_port.h:173
#define SIG_ERR
Definition: win32_port.h:159

◆ qsort_arg()

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(), build_column_frequencies(), build_sorted_items(), compute_range_stats(), compute_scalar_stats(), create_list_bounds(), create_range_bounds(), gbt_num_picksplit(), gbt_var_picksplit(), ginExtractEntries(), isort(), mcelem_array_selec(), ndistinct_for_combination(), range_gist_double_sorting_split(), range_gist_single_sorting_split(), SortAndUniqItems(), spg_range_quad_picksplit(), startScanKey(), statext_mcv_serialize(), 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:890
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

◆ random()

◆ rint()

double rint ( double  x)

Definition at line 21 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(), convert_int_from_base_unit(), convert_real_from_base_unit(), convert_to_base_unit(), 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(), optimal_k(), parse_int(), ParseFractionalSecond(), set_append_rel_size(), system_beginsamplescan(), and table_block_relation_estimate_size().

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

◆ rmtree()

bool rmtree ( const char *  path,
bool  rmtopdir 
)

Definition at line 42 of file rmtree.c.

References filename, lstat, MAXPGPATH, pg_log_warning, pgfnames(), pgfnames_cleanup(), rmtree(), S_ISDIR, snprintf, and stat.

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

43 {
44  bool result = true;
45  char pathbuf[MAXPGPATH];
46  char **filenames;
47  char **filename;
48  struct stat statbuf;
49 
50  /*
51  * we copy all the names out of the directory before we start modifying
52  * it.
53  */
54  filenames = pgfnames(path);
55 
56  if (filenames == NULL)
57  return false;
58 
59  /* now we have the names we can start removing things */
60  for (filename = filenames; *filename; filename++)
61  {
62  snprintf(pathbuf, MAXPGPATH, "%s/%s", path, *filename);
63 
64  /*
65  * It's ok if the file is not there anymore; we were just about to
66  * delete it anyway.
67  *
68  * This is not an academic possibility. One scenario where this
69  * happens is when bgwriter has a pending unlink request for a file in
70  * a database that's being dropped. In dropdb(), we call
71  * ForgetDatabaseSyncRequests() to flush out any such pending unlink
72  * requests, but because that's asynchronous, it's not guaranteed that
73  * the bgwriter receives the message in time.
74  */
75  if (lstat(pathbuf, &statbuf) != 0)
76  {
77  if (errno != ENOENT)
78  {
79  pg_log_warning("could not stat file or directory \"%s\": %m",
80  pathbuf);
81  result = false;
82  }
83  continue;
84  }
85 
86  if (S_ISDIR(statbuf.st_mode))
87  {
88  /* call ourselves recursively for a directory */
89  if (!rmtree(pathbuf, true))
90  {
91  /* we already reported the error */
92  result = false;
93  }
94  }
95  else
96  {
97  if (unlink(pathbuf) != 0)
98  {
99  if (errno != ENOENT)
100  {
101  pg_log_warning("could not remove file or directory \"%s\": %m",
102  pathbuf);
103  result = false;
104  }
105  }
106  }
107  }
108 
109  if (rmtopdir)
110  {
111  if (rmdir(path) != 0)
112  {
113  pg_log_warning("could not remove file or directory \"%s\": %m",
114  path);
115  result = false;
116  }
117  }
118 
119  pgfnames_cleanup(filenames);
120 
121  return result;
122 }
char ** pgfnames(const char *path)
Definition: pgfnames.c:37
#define MAXPGPATH
#define pg_log_warning(...)
Definition: rmtree.c:24
#define stat(a, b)
Definition: win32_port.h:264
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void pgfnames_cleanup(char **filenames)
Definition: pgfnames.c:86
#define S_ISDIR(m)
Definition: win32_port.h:305
#define lstat(path, sb)
Definition: win32_port.h:253
static char * filename
Definition: pg_dumpall.c:91
#define snprintf
Definition: port.h:192

◆ set_pglocale_pgservice()

void set_pglocale_pgservice ( const char *  argv0,
const char *  app 
)

Definition at line 565 of file exec.c.

References _, AddUserToTokenDacl(), canonicalize_path(), cleanup(), errcode(), FALSE, find_my_exec(), get_etc_path(), get_locale_path(), i, log_error, MAXPGPATH, my_exec_path, PG_TEXTDOMAIN, putenv, setlocale, snprintf, and TRUE.

Referenced by main(), and regression_main().

566 {
567  char path[MAXPGPATH];
568  char my_exec_path[MAXPGPATH];
569  char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
570  * PGLOCALEDIR */
571  char *dup_path;
572 
573  /* don't set LC_ALL in the backend */
574  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
575  {
576  setlocale(LC_ALL, "");
577 
578  /*
579  * One could make a case for reproducing here PostmasterMain()'s test
580  * for whether the process is multithreaded. Unlike the postmaster,
581  * no frontend program calls sigprocmask() or otherwise provides for
582  * mutual exclusion between signal handlers. While frontends using
583  * fork(), if multithreaded, are formally exposed to undefined
584  * behavior, we have not witnessed a concrete bug. Therefore,
585  * complaining about multithreading here may be mere pedantry.
586  */
587  }
588 
589  if (find_my_exec(argv0, my_exec_path) < 0)
590  return;
591 
592 #ifdef ENABLE_NLS
593  get_locale_path(my_exec_path, path);
594  bindtextdomain(app, path);
595  textdomain(app);
596 
597  if (getenv("PGLOCALEDIR") == NULL)
598  {
599  /* set for libpq to use */
600  snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
601  canonicalize_path(env_path + 12);
602  dup_path = strdup(env_path);
603  if (dup_path)
604  putenv(dup_path);
605  }
606 #endif
607 
608  if (getenv("PGSYSCONFDIR") == NULL)
609  {
610  get_etc_path(my_exec_path, path);
611 
612  /* set for libpq to use */
613  snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
614  canonicalize_path(env_path + 13);
615  dup_path = strdup(env_path);
616  if (dup_path)
617  putenv(dup_path);
618  }
619 }
static char * argv0
Definition: pg_ctl.c:96
#define setlocale(a, b)
Definition: win32_port.h:417
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1121
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:713
#define putenv(x)
Definition: win32_port.h:483
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
#define snprintf
Definition: port.h:192

◆ simple_prompt()

void simple_prompt ( const char *  prompt,
char *  destination,
size_t  destlen,
bool  echo 
)

Definition at line 37 of file sprompt.c.

References _, and buf.

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

◆ srandom()

void srandom ( unsigned int  seed)

Definition at line 22 of file srandom.c.

References pg_srand48().

Referenced by choose_dsm_implementation(), InitProcessGlobals(), and update_spins_per_delay().

23 {
24  pg_srand48((long int) seed);
25 }
void pg_srand48(long seed)
Definition: erand48.c:131

◆ strlcat()

size_t strlcat ( char *  dst,
const char *  src,
size_t  siz 
)

Definition at line 33 of file strlcat.c.

Referenced by _PrepParallelRestore(), 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 }

◆ strlcpy()

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_peer_issuer_name(), be_tls_get_peer_serial(), be_tls_get_peer_subject_name(), ChooseExtendedStatisticNameAddition(), ChooseForeignKeyConstraintNameAddition(), ChooseIndexNameAddition(), CleanupPriorWALFiles(), 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(), get_tablespace_mapping(), gnuish_strerror_r(), hash_create(), ident_inet(), identify_system_timezone(), initCreatePKeys(), initialize_SSL(), InitPostgres(), internal_cancel(), isolation_init(), join_path_components(), KeepFileRestoredFromArchive(), logfile_getname(), main(), make_oper_cache_key(), make_relative_path(), mdsyncfiletag(), mdunlinkfiletag(), ParseAbortRecord(), parseCommandLine(), ParseCommitRecord(), ParseLongOption(), parseServiceInfo(), pg_getnameinfo_all(), pg_GSS_error_int(), pg_open_tzfile(), pg_perm_setlocale(), pg_stat_get_wal_receiver(), pg_timezone_abbrevs(), pg_TZDIR(), pg_tzenumerate_next(), pgarch_archiveXlog(), pgstat_bestart(), PostmasterMarkPIDForWorkerNotify(), postprocess_sql_command(), PQcancel(), pqGetErrorNotice3(), pqGetHomeDirectory(), pqParseInput2(), pqParseInput3(), PQrequestCancel(), process_file(), process_postgres_switches(), ReceiveAndUnpackTarFile(), recoveryStopsAfter(), replace_string(), RequestXLogStreaming(), resolve_symlinks(), results_differ(), scan_available_timezones(), scan_directory(), scan_directory_ci(), SerializeLibraryState(), set_ps_display(), setup_bin_paths(), SetWALFileNameForCleanup(), SimpleLruInit(), SSLerrmessage(), tar_close(), tarCreateHeader(), 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 }

◆ strnlen()

size_t strnlen ( const char *  str,
size_t  maxlen 
)

Definition at line 26 of file strnlen.c.

References generate_unaccent_rules::str.

Referenced by fmtstr(), pnstrdup(), and xml_is_document().

27 {
28  const char *p = str;
29 
30  while (maxlen-- > 0 && *p)
31  p++;
32  return p - str;
33 }

◆ strtof()

float strtof ( const char *  nptr,
char **  endptr 
)

Definition at line 28 of file strtof.c.

References isinf().

Referenced by float4in().

29 {
30  int caller_errno = errno;
31  double dresult;
32  float fresult;
33 
34  errno = 0;
35  dresult = strtod(nptr, endptr);
36  fresult = (float) dresult;
37 
38  if (errno == 0)
39  {
40  /*
41  * Value might be in-range for double but not float.
42  */
43  if (dresult != 0 && fresult == 0)
44  caller_errno = ERANGE; /* underflow */
45  if (!isinf(dresult) && isinf(fresult))
46  caller_errno = ERANGE; /* overflow */
47  }
48  else
49  caller_errno = errno;
50 
51  errno = caller_errno;
52  return fresult;
53 }
int isinf(double x)

◆ unsetenv()

void unsetenv ( const char *  name)

Definition at line 20 of file unsetenv.c.

References malloc, putenv, and sprintf.

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 malloc(a)
Definition: header.h:50
#define sprintf
Definition: port.h:194
#define putenv(x)
Definition: win32_port.h:483
const char * name
Definition: encode.c:521

◆ wait_result_is_any_signal()

bool wait_result_is_any_signal ( int  exit_status,
bool  include_command_not_found 
)

Definition at line 111 of file wait_error.c.

References WEXITSTATUS, WIFEXITED, and WIFSIGNALED.

Referenced by ExecuteRecoveryCommand(), pgarch_archiveXlog(), and RestoreArchivedFile().

112 {
113  if (WIFSIGNALED(exit_status))
114  return true;
115  if (WIFEXITED(exit_status) &&
116  WEXITSTATUS(exit_status) > (include_command_not_found ? 125 : 128))
117  return true;
118  return false;
119 }
#define WIFEXITED(w)
Definition: win32_port.h:147
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define WEXITSTATUS(w)
Definition: win32_port.h:149

◆ wait_result_is_signal()

bool wait_result_is_signal ( int  exit_status,
int  signum 
)

Definition at line 92 of file wait_error.c.

References WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by ClosePipeToProgram(), and RestoreArchivedFile().

93 {
94  if (WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum)
95  return true;
96  if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == 128 + signum)
97  return true;
98  return false;
99 }
#define WTERMSIG(w)
Definition: win32_port.h:150
#define WIFEXITED(w)
Definition: win32_port.h:147
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define WEXITSTATUS(w)
Definition: win32_port.h:149

◆ wait_result_to_str()

char* wait_result_to_str ( int  exit_status)

Definition at line 32 of file wait_error.c.

References _, pg_strsignal(), pstrdup(), snprintf, generate_unaccent_rules::str, WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

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

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  {
60 #if defined(WIN32)
61  snprintf(str, sizeof(str),
62  _("child process was terminated by exception 0x%X"),
63  WTERMSIG(exitstatus));
64 #else
65  snprintf(str, sizeof(str),
66  _("child process was terminated by signal %d: %s"),
67  WTERMSIG(exitstatus), pg_strsignal(WTERMSIG(exitstatus)));
68 #endif
69  }
70  else
71  snprintf(str, sizeof(str),
72  _("child process exited with unrecognized status %d"),
73  exitstatus);
74 
75  return pstrdup(str);
76 }
#define WTERMSIG(w)
Definition: win32_port.h:150
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define WIFEXITED(w)
Definition: win32_port.h:147
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:37
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:84
#define WEXITSTATUS(w)
Definition: win32_port.h:149