M = Move variable declaration to its initialization.
R = Reduce scope.
S = Split scope, create separate variables from one variable.
B = Insert braces, creating a block scope.
O = Change order of initializations.
* lib/accept4.c (accept4): M.
* lib/acl-internal.c (acl_ace_nontrivial): R.
* lib/acosl.c (acosl): MS.
* lib/af_alg.c (afalg_stream): B.
* lib/alignalloc.h (alignalloc): R.
* lib/alloca.c (find_stack_direction): M.
(alloca): M.
* lib/amemxfrm.c (amemxfrm): MR.
* lib/arcfour.c (arcfour_stream): MB.
(arcfour_setkey): MB.
* lib/arctwo.c (arctwo_encrypt): M.
(arctwo_decrypt): M.
(arctwo_setkey_ekb): M.
* lib/areadlink-with-size.c (areadlink_with_size): MR.
* lib/areadlinkat-with-size.c (areadlinkat_with_size): MR.
* lib/argmatch.c (argmatch): MO.
(main): RBO.
* lib/argp-fmtstream.c (__argp_make_fmtstream): M.
(__argp_fmtstream_update): M.
(__argp_fmtstream_ensure): R.
(__argp_fmtstream_printf): R.
* lib/argp-fmtstream.h (__argp_fmtstream_set_lmargin): M.
(__argp_fmtstream_set_rmargin): M.
(__argp_fmtstream_set_wmargin): M.
* lib/argp-help.c (validate_uparams): M.
(fill_in_uparams): MR.
(make_hol): MRSO.
(hol_entry_short_iterate): R.
(hol_entry_long_iterate): R.
(hol_entry_first_long): Rename 'num' to 'nopts'.
(canon_doc_option): M.
(hol_append): MR.
(argp_hol): O.
(hol_entry_help): RSBO.
(hol_help): RB.
(usage_argful_short_opt): R.
(usage_long_opt): R.
(hol_usage): SB.
(argp_args_levels): R.
(argp_args_usage): MRB.
(argp_doc): RBO.
(_help): MR.
(__argp_error): R.
* lib/argp-parse.c (group_parse): M.
(parser_init): MRB.
(parser_finalize): MS.
(parser_parse_next): R.
(__argp_parse): MR.
(__argp_input): M.
* lib/argz.c (argz_add_sep): M.
(argz_create_sep): M.
(argz_create): R.
(argz_replace): RB.
* lib/asinl.c (asinl): MRS.
* lib/asnprintf.c (asnprintf): M.
* lib/asnwprintf.c (asnwprintf): M.
* lib/asprintf.c (asprintf): M.
* lib/astrxfrm.c (astrxfrm): MR.
* lib/aszprintf.c (aszprintf): M.
* lib/at-func.c (AT_FUNC_NAME): MR.
* lib/at-func2.c (at_func2): MRS.
* lib/atanl.c (atanl): MRS.
* lib/backupfile.c (numbered_backup): R.
* lib/base32.c (decode_8): R.
(base32_decode_ctx): R.
* lib/base64.c (decode_4): R.
(base64_decode_ctx): R.
* lib/basename-lgpl.c (last_component): R.
(base_len): RO.
* lib/bitset.c (bitset_copy_): R.
* lib/bitset/list.c (lbitset_prune): MR.
(lbitset_weed): MR.
(lbitset_list): SB.
* lib/bitset/table.c (tbitset_list): SB.
* lib/boot-time-aux.h (get_windows_boot_time_fallback): R.
* lib/btoc32.c (btoc32): R.
* lib/c-asprintf.c (c_asprintf): M.
* lib/c-aszprintf.c (c_aszprintf): M.
* lib/c-snprintf.c (c_snprintf): M.
* lib/c-snzprintf.c (c_snzprintf): M.
* lib/c-strcasecmp.c (c_strcasecmp): R.
* lib/c-strcasestr.c (c_strcasestr): MRSB.
* lib/c-strncasecmp.c (c_strncasecmp): R.
* lib/c-strtod.c (C_STRTOD): R.
* lib/c-vsnzprintf.c (c_vsnzprintf): M.
* lib/c-xasprintf.c (c_xasprintf): M.
* lib/c32tob.c (c32tob): R.
* lib/canon-host.c (canon_host_r): MR.
* lib/canonicalize.c (canonicalize_filename_mode_stk): R.
* lib/canonicalize-lgpl.c (realpath_stk): R.
* lib/cbrt.c (cbrt): M.
* lib/cbrtf.c (cbrtf): M.
* lib/cbrtl.c (cbrtl): MR.
* lib/chdir-long.c (chdir_long): M.
(main): MR.
* lib/classpath.c (new_classpath): MB.
* lib/clean-temp.c (create_temp_dir): M.
(unregister_temp_file): M.
(unregister_temp_subdir): M.
(cleanup_temp_file): M.
(cleanup_temp_subdir): M.
(cleanup_temp_dir_contents): MSB.
(open_temp): R.
(fopen_temp): R.
(close_temp): RB.
(fclose_variant_temp): RB.
* lib/clean-temp-simple.c (cleanup_action): MSB.
(cleanup_temporary_file): M.
* lib/copy-file.c (copy_file_internal): MRB.
* lib/cosl.c (cosl): MR.
* lib/crc-generate-table.c (make_crc_table): M.
* lib/crc-x86_64-pclmul.c (crc32_update_no_xor_pclmul): MRSB.
* lib/crc.c (crc32_update_no_xor_slice_by_8): S.
(crc32_update_no_xor_slice_by_n): M.
(crc32_update_no_xor): MR.
* lib/csharpcomp.c (compile_csharp_using_mono): MRB.
(compile_csharp_using_dotnet): MRSB.
(compile_csharp_using_sscli): MRB.
* lib/csharpexec.c (execute_csharp_using_mono): MO.
(execute_csharp_using_dotnet): MO.
(execute_csharp_using_sscli): MO.
(execute_csharp_program): R.
* lib/cygpath.c (execute_and_read_line): M.
* lib/des.c (gl_des_is_weak_key): M.
(gl_3des_ecb_crypt): MO.
* lib/dfa.c (closure): B.
(dfamust): MRB.
* lib/di-set.c (map_device): M.
(di_set_insert): M.
(di_set_lookup): M.
* lib/dirname-lgpl.c (dir_len): R.
* lib/dprintf.c (dprintf): M.
* lib/dup.c (dup_nothrow): R.
* lib/dup2.c (ms_windows_dup2): M.
(klibc_dup2dirfd): M.
(klibc_dup2): MR.
(rpl_dup2): M.
* lib/dup3.c (dup3): M.
* lib/duplocale.c (duplocale): MRSB.
* lib/dzprintf.c (dzprintf): M.
* lib/euidaccess.c (euidaccess): MR.
(main): M.
* lib/exclude.c (add_exclude): R.
* lib/execl.c (execl): SB.
* lib/execle.c (execle): SB.
* lib/execlp.c (execlp): SB.
* lib/execute.c (execute): R.
* lib/fchdir.c (ensure_dirs_slot): M.
(get_name): M.
(_gl_register_fd): R.
* lib/fclose.c (rpl_fclose): MR.
* lib/fcntl.c (dupfd): RO.
(fcntl): R.
(klibc_dupdirfd): M.
(klibc_fcntl): MRSB.
* lib/fdopen.c (rpl_fdopen): M.
* lib/file-has-acl.c (get_aclinfo): R.
(fdfile_has_aclinfo): MR.
* lib/file-remote.c (main): M.
* lib/file-set.c (record_file): M.
(seen_file): R.
* lib/findprog.c (find_in_path): MR.
* lib/findprog-in.c (find_in_given_path): MR.
* lib/flock.c (do_lock): MR.
(do_unlock): M.
(flock): MR.
* lib/fma.c (decode): M.
* lib/fopen.c (rpl_fopen): MR.
* lib/forkpty.c (forkpty): M.
* lib/fprintf.c (fprintf): M.
* lib/freadseek.c (freadseek): MR.
* lib/freopen.c (rpl_freopen): M.
* lib/freopen-safer.c (freopen_safer): M.
* lib/frexp.c (FUNC): MR.
* lib/fseterr.c (fseterr): M.
* lib/fstatat.c (rpl_fstatat): M.
* lib/fstrcmp.c (fstrcmp_free_resources): M.
(fstrcmp_bounded): MR.
* lib/fsusage.c (statvfs_works): R.
* lib/fsync.c (fsync): M.
* lib/ftello.c (ftello): M.
* lib/ftruncate.c (SetFileSize): M.
* lib/fts.c (fts_open): MR.
(fts_load): M.
(fts_close): MR.
(filesystem_type): MRO.
(fts_read): MB.
(fts_children): M.
(fts_build): MR.
(fts_cross_check): RO.
(fd_ring_print): RO.
(fts_stat): RO.
(fts_sort): R.
(fts_alloc): M.
(fts_lfree): R.
(fts_palloc): M.
(fts_padjust): MS.
(fts_maxarglen): M.
(fts_safe_changedir): MR.
* lib/fts-cycle.c (enter_dir): MRO.
(leave_dir): M.
* lib/fzprintf.c (fzprintf): M.
* lib/gc-gnulib.c (gc_cipher_open): MR.
(gc_cipher_setkey): MSB.
(gc_cipher_setiv): M.
(gc_cipher_encrypt_inline): M.
(gc_cipher_decrypt_inline): M.
(gc_hash_open): MR.
(gc_hash_clone): M.
* lib/gc-libgcrypt.c (gc_init): Remove local variable 'err'.
(gc_cipher_open): MR.
(gc_cipher_setkey): M.
(gc_cipher_setiv): M.
(gc_hash_open): MR.
(gc_hash_clone): M.
(gc_md4): MR.
(gc_md5): MR.
(gc_sha1): MR.
(gc_sha256): MR.
(gc_sha512): MR.
(gc_sm3): MR.
(gc_hmac_md5): MR. Remove local variable 'err'.
(gc_hmac_sha1): MR. Remove local variable 'err'.
(gc_hmac_sha256): MR. Remove local variable 'err'.
(gc_hmac_sha512): MR. Remove local variable 'err'.
* lib/gc-pbkdf2.c (gc_pbkdf2_prf): MR.
* lib/gen-uni-tables.c (fill_attributes): M.
(debug_output_predicate): M.
(output_predicate_test): M.
(output_predicate): MR.
(output_category): MR.
(output_combclass): MR.
(output_bidi_category): MR.
(output_decimal_digit_test): M.
(output_decimal_digit): MR.
(output_digit_test): M.
(output_digit): MR.
(output_numeric_test): M.
(output_numeric): MR.
(fill_mirror): MR.
(get_mirror_value): M.
(output_mirror): MR.
(fill_properties): MR.
(fill_property30): MR.
(output_indic_conjunct_break_test): M.
(output_indic_conjunct_break): MR.
(fill_arabicshaping): MR.
(output_joining_type_test): M.
(output_joining_type): MR.
(output_joining_group_test): M.
(output_joining_group): MR.
(fill_scripts): MR.
(output_scripts): MR.
(output_scripts_byname): M.
(fill_blocks): MR.
(output_blocks): M.
(output_ident_category): MR.
(output_charclass): MR.
(output_charmap): MR.
(output_tables): M.
(fill_width): MR.
(output_nonspacing_property): MR.
(output_width_property_test): M.
(debug_output_lbrk_tables): M.
(fill_org_lbp): MR.
(debug_output_org_lbrk_tables): M.
(output_lbpea): M.
(output_lbrk_tables): R.
(output_lbrk_rules_as_tables): M.
(debug_output_wbrk_tables): M.
(fill_org_wbp): MR.
(debug_output_org_wbrk_tables): M.
(output_wbp): M.
(output_wbrk_tables): M.
(output_gbp_test): MR.
(output_gbp_table): MR.
(fill_org_gbp): MR.
(get_decomposition): MR.
(output_decomposition): M.
(output_decomposition_tables): R.
(fill_composition_exclusions): MR.
(debug_output_composition_tables): M.
(output_composition_tables): MSB.
(output_simple_mapping_test): M.
(output_simple_mapping): MR.
(fill_casing_rules): MR.
(fill_casefolding_rules): MR.
(output_casing_rules): M.
(output_version): MR.
* lib/get-rusage-as.c (get_rusage_as_via_setrlimit): R.
(get_rusage_as): M.
* lib/get-rusage-data.c (get_rusage_data_via_setrlimit): R.
(get_rusage_data): M.
* lib/get_ppid_of.c (get_ppid_of): M.
* lib/get_progname_of.c (get_progname_of): MR.
* lib/getaddrinfo.c (use_win32_p): M.
(getaddrinfo): MR.
(freeaddrinfo): M.
* lib/getcwd.c (__getcwd_generic): MRSBO.
* lib/getcwd-lgpl.c (rpl_getcwd): MS.
* lib/getdelim.c (getdelim): MR.
* lib/getdomainname.c (getdomainname): M.
* lib/getentropy.c (getentropy): R.
* lib/getgroups.c (rpl_getgroups): MR.
* lib/gethostname.c (rpl_gethostname): M.
* lib/getloadavg.c (getloadavg): MRB.
* lib/getlocalename_l-unsafe.c (newlocale): MR.
(duplocale): MR.
(freelocale): M.
* lib/getlogin_r.c (getlogin_r): M.
* lib/getndelim2.c (getndelim2): MR.
* lib/getopt.c (exchange): MS.
(process_long_option): MRB.
(_getopt_internal_r): MR.
(_getopt_internal): M.
(main): M.
* lib/getopt1.c (main): M.
* lib/getpass.c (getpass): MRB.
* lib/getprogname.c (getprogname): M.
* lib/getrusage.c (getrusage): M.
* lib/getsockopt.c (rpl_getsockopt): M.
* lib/getsubopt.c (getsubopt): M.
* lib/gettext.h (dcpgettext_expr): M.
(dcnpgettext_expr): M.
* lib/gettimeofday.c (gettimeofday): R.
* lib/getugroups.c (getugroups): MR.
* lib/getumask.c (getumask): R.
* lib/gl_anyavltree_list2.h (rebalance): MR.
(gl_tree_remove_node_from_tree): MR.
(gl_tree_nx_add_before): R.
(gl_tree_nx_add_after): R.
* lib/gl_anyhash2.h (hash_resize): M.
* lib/gl_anylinked_list2.h (gl_linked_get_at): R.
(gl_linked_nx_set_at): R.
(gl_linked_search_from_to): R.
(gl_linked_indexof_from_to): MR.
(gl_linked_nx_add_at): M.
(gl_linked_remove_node): M.
(gl_linked_remove_at): MR.
(gl_linked_iterator_from_to): M.
(gl_linked_sortedlist_search_from_to): R.
(gl_linked_sortedlist_indexof_from_to): R.
* lib/gl_anyrbtree_list2.h (rebalance_after_add): MR.
(gl_tree_remove_node_from_tree): M.
* lib/gl_anytree_list2.h (gl_tree_iterator): MB.
(gl_tree_sortedlist_indexof_from_to): R.
* lib/gl_anytree_omap.h (gl_tree_nx_getput): M.
(gl_tree_iterator): MB.
* lib/gl_anytree_oset.h (gl_tree_nx_add): M.
(gl_tree_update): M.
(gl_tree_iterator): MB.
* lib/gl_anytreehash_list1.h (add_to_bucket): M.
* lib/gl_array_list.c (grow): M.
(gl_array_nx_add_first): M.
(gl_array_nx_add_before): M.
(gl_array_nx_add_after): M.
(gl_array_nx_add_at): M.
(gl_array_remove_node): M.
(gl_array_remove_at): M.
* lib/gl_array_map.c (grow): M.
(gl_array_nx_getput): M.
(gl_array_remove_at): M.
* lib/gl_array_omap.c (grow): M.
(gl_array_nx_add_at): M.
(gl_array_remove_at): M.
* lib/gl_array_oset.c (grow): M.
(gl_array_nx_add_at): M.
(gl_array_remove_at): M.
* lib/gl_array_set.c (grow): M.
* lib/gl_avltree_ordered.h (rebalance): M.
(gl_tree_add_node_before): R.
(gl_tree_add_node_after): R.
(gl_tree_remove_node_no_free): M.
* lib/gl_carray_list.c (gl_carray_node_value): M.
(gl_carray_node_nx_set_value): M.
(gl_carray_get_at): M.
(gl_carray_nx_set_at): M.
(gl_carray_indexof_from_to): M.
(grow): M.
(gl_carray_nx_add_last): M.
(gl_carray_nx_add_at): M.
(gl_carray_remove_at): M.
(gl_carray_iterator_from_to): R.
(gl_carray_sortedlist_indexof_from_to): M.
(gl_carray_sortedlist_nx_add): M.
* lib/gl_rbtree_ordered.h (rebalance_after_add): M.
(gl_tree_remove_node_no_free): M.
* lib/gl_sublist.c (gl_sublist_sortedlist_search_from_to): M.
(gl_sublist_sortedlist_indexof_from_to): M.
* lib/glob.c (__glob): MR.
* lib/globfree.c (globfree): M.
* lib/glthread/lock.c (glthread_rwlock_init_for_glibc): M.
(glthread_rwlock_init_multithreaded): M.
(glthread_rwlock_rdlock_multithreaded): M.
(glthread_rwlock_wrlock_multithreaded): M.
(glthread_rwlock_destroy_multithreaded): M.
(glthread_rwlock_init_multithreaded): M.
(glthread_rwlock_rdlock_multithreaded): M.
(glthread_rwlock_wrlock_multithreaded): M.
(glthread_rwlock_unlock_multithreaded): M.
(glthread_rwlock_destroy_multithreaded): M.
(glthread_recursive_lock_init_multithreaded): M.
(glthread_recursive_lock_lock_multithreaded): M.
(glthread_recursive_lock_destroy_multithreaded): M.
(glthread_recursive_lock_init_multithreaded): M.
(glthread_recursive_lock_lock_multithreaded): M.
* lib/glthread/thread.c (gl_thread_create): M.
* lib/group-member.c (group_member): M.
(main): M.
* lib/hash.c (hash_get_next): MB.
(check_tuning): M.
(hash_initialize): M.
(hash_clear): M.
(hash_free): MS.
(transfer_entries): M.
(hash_rehash): MR.
(hash_insert_if_absent): MR.
(hash_remove): MR.
(hash_print): M.
* lib/hasmntopt.c (hasmntopt): M.
* lib/hmac.c (hmac_hash): R.
(GL_HMAC_FN): R.
* lib/human.c (group_number): MRO.
(human_readable): MR.
(humblock): M.
* lib/hypot.c (hypot): M.
* lib/hypotl.c (hypotl): M.
* lib/i-ring.c (i_ring_pop): M.
* lib/iconv_open.c (rpl_iconv_open): R.
* lib/idcache.c (getuidbyname): M.
(getgidbyname): M.
* lib/inet_ntop.c (inet_ntop4): M.
(inet_ntop6): R.
* lib/inet_pton.c (inet_pton4): MRBO.
(inet_pton6): MRBO.
* lib/ino-map.c (ino_map_insert): M.
* lib/integer_length.c (integer_length): M.
* lib/ioctl.c (rpl_ioctl): M.
(ioctl): M.
* lib/is_l-impl.h (FUNC): M.
* lib/isatty.c (IsCygwinConsoleHandle): R.
* lib/isnan.c (FUNC): MR.
* lib/javacomp.c (compile_using_envjavac): MRB.
(compile_using_javac): MB.
(execute_and_read_line): M.
(write_temp_file): M.
(get_classfile_version): MR.
(is_envjavac_usable): MR.
(is_javac_present): M.
(is_javac_usable): MR.
(compile_java_class): MR.
* lib/javaexec.c (execute_java_class): MRBO.
* lib/javaversion.c (execute_and_read_line): M.
(javaexec_version): R.
* lib/kwset.c (treefails): M.
(kwsprep): MRSB.
(bmexec_trans): MRSO.
(acexec_trans): MRS.
* lib/lchown.c (rpl_lchown): R.
* lib/linebuffer.c (readlinebuffer_delim): RO.
* lib/link.c (link): MRBO.
(rpl_link): M.
* lib/linkat.c (link_immediate): R.
(link_follow): M.
(linkat_follow): M.
* lib/localcharset.c (locale_charset): MR.
* lib/localeinfo.c (is_using_utf8): R. Rename 'mbs' to 'state'.
(init_localeinfo): Rename 's' to 'state'.
* lib/localename.c (gl_locale_name): MSB.
* lib/localename-environ.c (gl_locale_name_environ): MSB.
* lib/localename-unsafe.c (gl_locale_name_canonicalize): MSB.
(gl_locale_name_from_win32_LANGID): M.
(gl_locale_name_from_win32_LCID): M.
(enum_locales_fn): R.
(gl_locale_name_unsafe): MSB.
* lib/log2.c (log2): M.
* lib/log2f.c (log2f): M.
* lib/log2l.c (log2l): M.
* lib/login_tty.c (login_tty): M.
* lib/logl.c (logl): MR.
* lib/long-options.c (parse_long_options): MR.
(parse_gnu_standard_options_only): M.
* lib/mbfile.h (mbfile_multi_getc): MR.
* lib/mbmemcasecoll.c (apply_c32tolower): M.
(mbmemcasecoll): MR.
* lib/mbrtoc32.c (mbrtoc32): R.
* lib/mbrtowc.c (rpl_mbrtowc): MRS.
* lib/mbrtowc-impl.h: MRB.
* lib/mbscasestr.c (knuth_morris_pratt_multibyte): MR.
(mbscasestr): R.
* lib/mbscspn.c (mbscspn): MR.
* lib/mbsnrtowcs-impl.h (FUNC): M.
* lib/mbspbrk.c (mbspbrk): MR.
* lib/mbsrtowcs-impl.h (FUNC): M.
* lib/mbsspn.c (mbsspn): MR.
* lib/mbsstr.c (knuth_morris_pratt_multibyte): MR.
(mbsstr): MR.
* lib/mbswidth.c (mbsnwidth): M.
* lib/mbtowc-impl.h (mbtowc): MR.
* lib/mbtowc-lock.h (mbtowc_with_lock): M.
* lib/mcel.h: MR in comments.
* lib/md2.c (md2_finish_ctx): M.
(md2_process_bytes): M.
(md2_update_chksum): M.
(md2_compress): M.
* lib/md2-stream.c (md2_stream): MR.
* lib/md4.c (md4_finish_ctx): M.
(md4_process_block): MR.
* lib/md4-stream.c (md4_stream): MR.
* lib/md5-stream.c (md5_stream): MR.
* lib/mem-hash-map.c (compute_hashval): M.
(lookup): M.
* lib/memchr.c (__memchr): MRB.
* lib/memchr2.c (memchr2): MRB.
* lib/memrchr.c (__memrchr): MRB.
* lib/mgetgroups.c (mgetgroups): MRS.
* lib/mkancesdirs.c (mkancesdirs): M.
* lib/mkdir.c (rpl_mkdir): MR.
* lib/mkdir-p.c (make_dir_parents): R.
* lib/modechange.c (mode_compile): R.
* lib/mountlist.c (fstype_to_string): M.
(dev_from_mount_options): MR.
(read_file_system_list): MR.
* lib/mpsort.c (mpsort_into_tmp): M.
(mpsort_with_tmp): M.
* lib/msvc-inval.h (TRY_MSVC_INVAL): M.
* lib/mtx.c (mtx_init): MSB.
* lib/nanosleep.c (nanosleep): M.
* lib/nl_langinfo.c (ctype_codeset): MR.
(nl_langinfo_with_lock): M.
* lib/nonblocking.c (get_nonblocking_flag): M.
(set_nonblocking_flag): M.
* lib/nproc.c (num_processors_via_affinity_mask): M.
(cgroup2_mount): MR.
(get_cgroup2_cpu_quota): M.
(parse_omp_threads): Remove variable 'ret'.
(num_processors): M.
* lib/obstack.c (_obstack_newchunk): M.
(_obstack_allocated_p): M.
(__obstack_free): M.
* lib/obstack_printf.c (OBSTACK_PRINTF): M.
(OBSTACK_VPRINTF): M.
* lib/omp-init.c (parse_omp_threads): Remove variable 'ret'.
* lib/openat-proc.c (openat_proc_name): R.
* lib/openat2.c (do_openat2): R.
(openat2): MSB.
* lib/opendir.c (opendir): MR.
* lib/openpty.c (openpty): M.
* lib/os2-spawn.c (prepare_spawn): M.
(spawnpvech): R.
* lib/pagealign_alloc.c (pagealign_alloc): MR.
(pagealign_xalloc): M.
(pagealign_free): M.
* lib/parse-duration.c (parse_scaled_value): M.
(parse_year_month_day): M.
(parse_yearmonthday): MR.
(parse_YMWD): SB.
(parse_hour_minute_second): M.
(parse_hourminutesecond): MR.
(parse_HMS): SB.
(parse_time): M.
(parse_period): MR.
(parse_non_iso8601): M.
* lib/passfd.c (sendfd): MRO.
(recvfd): MRO.
* lib/perror.c (perror): M.
* lib/physmem.c (physmem_total): M.
(physmem_claimable): M.
* lib/pipe-filter-gi.c (filter_loop): MRB.
(pipe_filter_gi_create): M.
(pipe_filter_gi_close): M.
* lib/pipe-filter-ii.c (_beginthreadex): M.
(WaitForMultipleObjects): MR.
(pipe_filter_ii_execute): MRB.
* lib/poll.c (IsSocketHandle): R.
(windows_compute_revents): MRB.
(windows_compute_revents_socket): M.
(poll): MRB. Remove variable 'bRet'.
* lib/popen.c (rpl_popen): MB.
* lib/posix_openpt.c (posix_openpt): M.
* lib/posixtm.c (posix_time_parse): R.
(posixtime): R.
* lib/pread.c (pread): M.
* lib/printf.c (printf): M.
* lib/printf-frexp.c (FUNC): R.
* lib/printf-parse.c (PRINTF_PARSE): MR.
* lib/progreloc.c (maybe_executable): R.
(find_executable): MRSB.
(prepare_relocate): M.
* lib/propername.c (mbsstr_trimmed_wordbounded): RSB.
(proper_name_utf8): M.
* lib/pselect.c (pselect): MR.
* lib/pt_chown.c (do_pt_chown): MR.
* lib/pthread-cond.c (pthread_cond_timedwait): R.
* lib/pthread-rwlock.c (pthread_rwlockattr_init): MSB.
(pthread_rwlock_init): MSB.
(pthread_rwlock_rdlock): MSB.
(pthread_rwlock_wrlock): MSB.
(pthread_rwlock_tryrdlock): MB.
(pthread_rwlock_trywrlock): MB.
(pthread_rwlock_timedrdlock): MSB.
(pthread_rwlock_timedwrlock): MSB.
(pthread_rwlock_unlock): MSB.
(pthread_rwlock_destroy): MSB.
(pthread_rwlock_init): MSB.
(pthread_rwlock_timedrdlock): MRB.
(pthread_rwlock_timedwrlock): MRB.
* lib/pthread_mutex_timedlock.c (pthread_mutex_timedlock): MRB.
* lib/pthread_sigmask.c (pthread_sigmask): MR.
* lib/ptsname_r.c (ptsname_r): MR.
* lib/putenv.c (putenv): M.
* lib/pwrite.c (pwrite): M.
* lib/qcopy-acl.c (qcopy_acl): Remove a use of variable 'ret'.
* lib/qset-acl.c (qset_acl): M.
* lib/qsort.c (_quicksort): MR.
* lib/quotearg.c (set_quoting_flags): M.
(quotearg_buffer_restyled): MRSB.
* lib/random.c (__initstate): M.
(__setstate): M.
(__random): R.
* lib/random_r.c (__srandom_r): M.
(__setstate_r): MO.
(__random_r): M.
* lib/rawmemchr.c (rawmemchr): RB.
* lib/read-file.c (fread_file): M.
(read_file): M.
* lib/readdir.c (readdir): MR.
* lib/readline.c (readline): R.
* lib/readtokens.c (readtoken): R.
(readtokens): M.
* lib/regex-quote.c (regex_quote_spec_gnu): MB.
(regex_quote_spec_pcre): MB.
(regex_quote_length): MR.
(regex_quote): MB.
* lib/relocatable.c (set_this_relocation_prefix): M.
(compute_curr_prefix): MR.
(find_shared_library_fullname): MRS.
(relocate): M.
* lib/relocwrapper.c (activate_libdirs): MB.
(main): M.
* lib/rename.c (rpl_rename): MRBO.
* lib/renameatu.c (renameatu): MRB.
* lib/rijndael-alg-fst.c (rijndaelKeySetupEnc): MSB.
(rijndaelKeySetupDec): MRSB.
(rijndaelEncrypt): MSB.
(rijndaelDecrypt): MSB.
* lib/rijndael-api-fst.c (rijndaelMakeKey): MRSB.
(rijndaelCipherInit): MSB.
(rijndaelBlockEncrypt): MRSB.
(rijndaelPadEncrypt): MRSB.
(rijndaelBlockDecrypt): MRSB.
(rijndaelPadDecrypt): MRSB.
* lib/rmdir.c (rpl_rmdir): M.
* lib/rpmatch.c (localized_pattern): MS.
(try): M.
(rpmatch): MSB.
* lib/same.c (same_nameat): R. Remove variable 'flags'.
* lib/savedir.c (streamsavedir): MRB.
* lib/scandir.c (SCANDIR): MR.
* lib/select.c (IsSocketHandle): R.
(windows_poll_handle): MRSB. Remove variable 'bRet'.
(rpl_select): MR. Remove variable 'bRet'.
* lib/set-permissions.c (set_acls_from_mode): R.
(context_acl_from_mode): R.
(context_aclv_from_mode): M.
(set_acls_from_mode): MR.
(context_acl_from_mode): M.
(set_acls): R.
(set_permissions): MS.
* lib/setenv.c (__add_to_environ): M.
(rpl_setenv): M.
* lib/sethostname.c (sethostname): MR.
* lib/setlocale.c (setlocale_unixlike): MR.
(langcmp): R.
(setlocale_improved): MR.
* lib/setlocale_null.c (setlocale_null_r_with_lock): M.
(setlocale_null): M.
* lib/setsockopt.c (rpl_setsockopt): R.
* lib/sh-quote.c (shell_quote_argv): MB.
* lib/sha1.c (sha1_process_block): R.
* lib/sha1-stream.c (sha1_stream): M.
* lib/sha256.c (sha256_process_block): MR.
* lib/sha256-stream.c (shaxxx_stream): M.
* lib/sha3.c (sha3_read_ctx): R.
(sha3_process_block): R.
* lib/sha3-stream.c (sha3_xxx_stream): M.
* lib/sha512-stream.c (shaxxx_stream): M.
* lib/sig2str.c (str2signum): RS.
(sig2str): MR.
* lib/sigaction.c (sigaction_handler): MR.
(sigaction): MRB.
* lib/sigprocmask.c (sigprocmask): M.
* lib/sigsegv.c (sigsegv_handler): MR.
* lib/sincosl.c (kernel_sinl): MRS.
(kernel_cosl): MRS.
* lib/sinl.c (sinl): MR.
* lib/sleep.c (rpl_sleep): M.
* lib/sm3.c (sm3_process_block): MR.
* lib/sm3-stream.c (sm3_stream): MR.
* lib/snprintf.c (snprintf): M.
* lib/snzprintf.c (snzprintf): M.
* lib/socket.c (rpl_socket): M.
* lib/sockets.c (close_fd_maybe_socket): MR.
(ioctl_fd_maybe_socket): MR.
(gl_sockets_startup): M.
(gl_sockets_cleanup): M.
* lib/spawn-pipe.c (create_pipe): MR.
* lib/spawni.c (__spawni): Split variable declaration.
* lib/sprintf.c (sprintf): M.
* lib/sqrtl.c (sqrtl): MR.
* lib/ssfmalloc.h (allocate_block_from_pool): MSB.
* lib/stackvma.c (rof_open): M.
(vma_iterate_proc): RSB.
(vma_iterate_bsd): MB.
(mapped_range_start): M.
(mapped_range_end): M.
(is_unmapped): MR.
(mapped_range_start): M.
(mapped_range_end): M.
(vma_iterate): MR.
* lib/stat-w32.c (_gl_convert_FILETIME_to_timespec): R.
* lib/stdio-consolesafe.c (gl_consolesafe_fprintf): R.
(gl_consolesafe_printf): R.
* lib/stdio-read.c (CALL_WITH_ERRNO_FIX): M.
(scanf): M.
(fscanf): M.
* lib/stdio-write.c (CALL_WITH_SIGPIPE_EMULATION): M.
(printf): M.
(fprintf): M.
* lib/stpncpy.c (__stpncpy): MSB.
* lib/str-kmp.h (knuth_morris_pratt): M.
* lib/str-two-way.h (critical_factorization): MSB.
(two_way_short_needle): MS.
(two_way_long_needle): MRS.
* lib/strcasecmp.c (strcasecmp): R.
* lib/strcasecmp_l.c (strcasecmp_l): MR.
* lib/strcasestr.c (strcasestr): MRSB.
* lib/strchrnul.c (strchrnul): MRB.
* lib/strerror.c (strerror): M.
* lib/strerror_l.c (strerror_l_r): R.
* lib/strerror_r.c (local_snprintf): M.
(strerror_r): M.
* lib/strfmon_l.c (rpl_strfmon_l): MR.
* lib/strftime.c (__strftime_internal): MR.
* lib/striconv.c (mem_cd_iconv): MR.
(str_cd_iconv): MR.
(str_iconv): M.
* lib/striconveh.c (iconveh_open): MR.
(utf8conv_carefully): M.
(mem_cd_iconveh_internal): MR.
(mem_iconveh): M.
(str_iconveh): M.
* lib/striconveha.c (uniconv_register_autodetect): MRSB.
(mem_iconveha_notranslit): MS.
(mem_iconveha): M.
(str_iconveha_notranslit): MS.
(str_iconveha): M.
* lib/string-buffer-printf.c (sb_appendvf): R.
(sb_appendf): R.
* lib/string-buffer-reversed-printf.c (sbr_prependvf): R.
(sbr_prependf): R.
* lib/string-desc.c (sd_new): R.
* lib/stripslash.c (strip_trailing_slashes): M.
* lib/strncasecmp.c (strncasecmp): R.
* lib/strncasecmp_l.c (strncasecmp_l): MR.
* lib/strptime.c (__strptime_internal): RSB.
* lib/strsep.c (strsep): R.
* lib/strsignal.c (strsignal): R.
* lib/strstr.c (strstr): MRSB.
* lib/strtod.c (parse_number): MR.
(STRTOD): MR.
* lib/strtok_r.c (__strtok_r): M.
* lib/strtol.c (strtol): MR.
* lib/struniq.h (struniq): M.
* lib/supersede.c (open_supersede): R.
* lib/system-quote.c (system_quote_argv): MB.
* lib/szprintf.c (szprintf): M.
* lib/tanl.c (kernel_tanl): MRS.
(tanl): MR.
* lib/tempname.c (try_tempname_len): M.
* lib/term-style-control.c (sprintf_integer): MR.
* lib/textstyle.in.h (ostream_printf): MR.
* lib/time.c (time): M.
* lib/times.c (filetime2clock): M.
* lib/timespec-add.c (timespec_add): R.
* lib/timespec-sub.c (timespec_sub): R.
* lib/tmpdir.c (path_search): MR.
* lib/tmpfile.c (tmpfile): M.
* lib/to_l-impl.h (FUNC): M.
* lib/tparm.c (tparm): MRB.
* lib/trigl.c (ieee754_rem_pio2l): MRS.
(kernel_rem_pio2): MRS.
* lib/trim.c (trim2): MR.
* lib/tsearch.c (check_tree): R.
(maybe_split_for_insert): M.
(__tsearch): MR.
(__tfind): M.
(__tdelete): MRB.
* lib/ttyname_r.c (ttyname_r): M.
* lib/uname.c (uname): MR.
* lib/unicase/locale-language.c (uc_locale_language): M.
* lib/unicase/u-casecmp.h (FUNC): MR.
* lib/unicase/u-casecoll.h (FUNC): MR.
* lib/unicase/u-casemap.h (FUNC): MR.
* lib/unicase/u-casexfrm.h (FUNC): MR.
* lib/unicase/u-ct-casefold.h (FUNC): MR.
* lib/unicase/u-ct-totitle.h (FUNC): MR.
* lib/unicase/u-is-cased.h (FUNC): MR.
* lib/unicase/u-is-invariant.h (FUNC): MR.
* lib/unicase/u8-casefold.c (read_file): M.
* lib/unicase/u8-tolower.c (read_file): M.
* lib/unicase/u8-totitle.c (read_file): M.
* lib/unicase/u8-toupper.c (read_file): M.
* lib/unicase/ulc-casecmp.c (ulc_u8_casefold): MR.
* lib/unicase/ulc-casexfrm.c (ulc_casexfrm): MR.
* lib/unicodeio.c (unicode_to_mb): MR.
* lib/uniconv/u-conv-from-enc.h (FUNC): M.
* lib/uniconv/u-conv-to-enc.h (FUNC): MR.
* lib/uniconv/u-strconv-from-enc.h (FUNC): M.
* lib/uniconv/u-strconv-to-enc.h (FUNC): M.
* lib/uniconv/u16-conv-to-enc.c (FUNC): MR.
* lib/uniconv/u8-conv-from-enc.c (u8_conv_from_encoding): R.
* lib/uniconv/u8-conv-to-enc.c (u8_conv_to_encoding): R.
* lib/uniconv/u8-strconv-to-enc.c (u8_strconv_to_encoding): MS.
* lib/unictype/3level.h (CONCAT(TABLE,_add)): M.
(CONCAT(TABLE,_finalize)): MRB.
* lib/unictype/3levelbit.h (CONCAT(TABLE,_add)): M.
(CONCAT(TABLE,_finalize)): MRB.
* lib/unictype/bidi_byname.c (uc_bidi_class_byname): M.
* lib/unictype/categ_and.c (uc_general_category_and): MR.
* lib/unictype/categ_and_not.c (uc_general_category_and_not): MR.
* lib/unictype/categ_byname.c (uc_general_category_byname): M.
* lib/unictype/categ_of.c (uc_general_category): R.
* lib/unictype/categ_or.c (uc_general_category_or): MR.
* lib/unictype/combiningclass_byname.c (uc_combining_class_byname): M.
* lib/unictype/incb_byname.c (uc_indic_conjunct_break_byname): M.
* lib/unictype/joininggroup_byname.c (uc_joining_group_byname): M.
* lib/unictype/joiningtype_byname.c (uc_joining_type_byname): M.
* lib/unictype/pr_byname.c (uc_property_byname): MRB.
* lib/unictype/scripts.c (uc_script_byname): M.
* lib/unigbrk/u-grapheme-prev.h
(ends_with_incb_consonant_extended_linker_extended): M.
(ends_with_emoji_modifier_sequence): M.
(ends_with_ri_count): M.
(FUNC): M.
* lib/unigbrk/uc-is-grapheme-break.c (uc_is_grapheme_break): M.
* lib/unigbrk/ulc-grapheme-breaks.c (ulc_grapheme_breaks): M.
* lib/unilbrk/u16-width-linebreaks.c (u16_width_linebreaks_internal): M.
* lib/unilbrk/u32-width-linebreaks.c (u32_width_linebreaks_internal): M.
* lib/unilbrk/u8-possible-linebreaks.c (read_file): M.
* lib/unilbrk/u8-width-linebreaks.c (u8_width_linebreaks_internal): M.
(read_file): M.
* lib/unilbrk/ulc-possible-linebreaks.c
(ulc_possible_linebreaks_internal): M.
(read_file): M.
* lib/unilbrk/ulc-width-linebreaks.c (ulc_width_linebreaks_internal): M.
(read_file): M.
* lib/uniname/uniname.c (unicode_name_word): MR.
(unicode_character_name): M.
(unicode_name_character): MR.
* lib/uninorm/canonical-decomposition.c (uc_canonical_decomposition): M.
* lib/uninorm/composition.c (uc_composition): M.
* lib/uninorm/decomposition.c (uc_decomposition): M.
* lib/uninorm/u-normalize-internal.h (FUNC): MR.
* lib/uninorm/u-normcmp.h (FUNC): MR.
* lib/uninorm/u-normcoll.h (FUNC): MR.
* lib/uninorm/u-normxfrm.h (FUNC): MR.
* lib/uninorm/uninorm-filter.c (uninorm_filter_write): M.
* lib/unistdio/u-asnprintf.h (ASNPRINTF): M.
* lib/unistdio/u-asprintf.h (ASPRINTF): M.
* lib/unistdio/u-snprintf.h (SNPRINTF): M.
* lib/unistdio/u-sprintf.h (SPRINTF): M.
* lib/unistdio/u-vsnprintf.h (VSNPRINTF): M.
* lib/unistdio/u-vsprintf.h (VSPRINTF): M.
* lib/unistdio/ulc-fprintf.c (ulc_fprintf): M.
* lib/unistdio/ulc-vfprintf.c (ulc_vfprintf): M.
* lib/unistr/u16-chr.c (u16_chr): R.
* lib/unistr/u16-mbsnlen.c (u16_mbsnlen): M.
* lib/unistr/u16-next.c (u16_next): M.
* lib/unistr/u16-strchr.c (u16_strchr): R.
* lib/unistr/u16-strrchr.c (u16_strrchr): R.
* lib/unistr/u16-to-u32.c (FUNC): MR.
* lib/unistr/u16-to-u8.c (FUNC): MR.
* lib/unistr/u32-next.c (u32_next): M.
* lib/unistr/u32-to-u16.c (FUNC): MR.
* lib/unistr/u32-to-u8.c (FUNC): MR.
* lib/unistr/u8-chr.c (u8_chr): M.
* lib/unistr/u8-mbsnlen.c (u8_mbsnlen): M.
* lib/unistr/u8-next.c (u8_next): M.
* lib/unistr/u8-strchr.c (u8_strchr): R.
* lib/unistr/u8-strrchr.c (u8_strrchr): R.
* lib/unistr/u8-to-u16.c (FUNC): MR.
* lib/unistr/u8-to-u32.c (FUNC): MR.
* lib/uniwbrk/u8-wordbreaks.c (read_file): M.
* lib/uniwbrk/ulc-wordbreaks.c (ulc_wordbreaks): M.
(read_file): M.
* lib/uniwidth/u16-width.c (u16_width): M.
* lib/uniwidth/u32-width.c (u32_width): M.
* lib/uniwidth/u8-width.c (u8_width): M.
* lib/unlinkat.c (rpl_unlinkat): MR.
* lib/unsetenv.c (unsetenv): M.
(rpl_unsetenv): R.
* lib/userspec.c (parse_with_separator): MRS.
(main): MR.
* lib/utime.c (_gl_utimens_windows): M.
* lib/utimecmp.c (utimecmpat): R.
* lib/utimens.c (validate_timespec): R.
(fdutimens): MR.
(lutimens): MR.
* lib/utimensat.c (rpl_utimensat): M.
* lib/vasnprintf.c (divide): M.
(decode_long_double): MR.
(decode_double): MR.
(scale10_round_decimal_decoded): MR.
(floorlog10l): MR.
(floorlog10): MR.
(VASNPRINTF): MR.
* lib/vc-mtime.c (is_git_present): MR.
(git_vc_controlled): MR.
(git_unmodified): M.
(git_mtime): MR.
(abs_git_checkout): MR.
(max_vc_mtime): MR.
* lib/vdzprintf.c (vdzprintf): M.
* lib/vfzprintf.c (vfzprintf): M.
* lib/vma-iter.c (rof_open): M.
(vma_iterate_proc): MRSB.
(vma_iterate_bsd): MB.
(vma_iterate): MR.
* lib/vsnzprintf.c (vsnzprintf): M.
* lib/vszprintf.c (vszprintf): M.
* lib/wait-process.c (klibc_waitpid): M.
(wait_subprocess): MR.
* lib/wcs-two-way.h (critical_factorization): MSB.
(two_way_short_needle): MS.
* lib/wcsstr-impl.h (FUNC): MRSB.
* lib/wcswidth-impl.h (FUNC): B.
* lib/wcsxfrm-impl.h (wcsxfrm): MR.
* lib/wctomb-impl.h (wctomb): M.
* lib/wgetcwd-lgpl.c (wgetcwd): MRS.
* lib/windows-cond.c (glwthread_waitqueue_add): M.
(glwthread_waitqueue_notify_first): M.
(glwthread_waitqueue_notify_all): M.
(glwthread_cond_wait): M.
(glwthread_cond_timedwait): MRS.
* lib/windows-cygpath.c (execute_and_read_line): MR.
* lib/windows-rwlock.c (glwthread_waitqueue_add): M.
(glwthread_rwlock_rdlock): M.
(glwthread_rwlock_wrlock): M.
* lib/windows-spawn.c (quoted_arg_length): M.
(quoted_arg_string): M.
(prepare_spawn): MR.
(compose_command): MRB.
(compose_envblock): RSB.
* lib/windows-thread.c (glwthread_thread_self): M.
(glwthread_thread_create): M.
* lib/windows-timedmutex.c (glwthread_timedmutex_timedlock): MR.
* lib/windows-timedrecmutex.c (glwthread_timedrecmutex_timedlock): MR.
* lib/windows-timedrwlock.c (glwthread_waitqueue_add): M.
(glwthread_waitqueue_notify_first): M.
(glwthread_waitqueue_notify_all): M.
(glwthread_timedrwlock_rdlock): M.
(glwthread_timedrwlock_wrlock): M.
(glwthread_timedrwlock_timedrdlock): MR.
(glwthread_timedrwlock_timedwrlock): MR.
* lib/xasprintf.c (xasprintf): M.
* lib/xconcat-filename.c (xconcatenated_filename): M.
* lib/xmalloc.c (xpalloc): R.
* lib/xmalloca.c (xmmalloca): M.
* lib/xprintf.c (xprintf): M.
(xfprintf): M.
* lib/xstring-buffer-printf.c (sb_xappendf): M.
* lib/xstring-buffer-reversed-printf.c (sbr_xprependf): M.
* lib/xstrtod.c (XSTRTOD): MR.
* lib/xstrtol.c (__xstrtol): R.
* lib/xstrtol-error.c (xstrtol_error): R.
* lib/xvasprintf.c (xstrcat): MB.
(xvasprintf): R.
* lib/zprintf.c (zprintf): M.
+2025-12-09 Bruno Haible <bruno@clisp.org>
+
+ lib: Reduce scope of local variables.
+ M = Move variable declaration to its initialization.
+ R = Reduce scope.
+ S = Split scope, create separate variables from one variable.
+ B = Insert braces, creating a block scope.
+ O = Change order of initializations.
+ * lib/accept4.c (accept4): M.
+ * lib/acl-internal.c (acl_ace_nontrivial): R.
+ * lib/acosl.c (acosl): MS.
+ * lib/af_alg.c (afalg_stream): B.
+ * lib/alignalloc.h (alignalloc): R.
+ * lib/alloca.c (find_stack_direction): M.
+ (alloca): M.
+ * lib/amemxfrm.c (amemxfrm): MR.
+ * lib/arcfour.c (arcfour_stream): MB.
+ (arcfour_setkey): MB.
+ * lib/arctwo.c (arctwo_encrypt): M.
+ (arctwo_decrypt): M.
+ (arctwo_setkey_ekb): M.
+ * lib/areadlink-with-size.c (areadlink_with_size): MR.
+ * lib/areadlinkat-with-size.c (areadlinkat_with_size): MR.
+ * lib/argmatch.c (argmatch): MO.
+ (main): RBO.
+ * lib/argp-fmtstream.c (__argp_make_fmtstream): M.
+ (__argp_fmtstream_update): M.
+ (__argp_fmtstream_ensure): R.
+ (__argp_fmtstream_printf): R.
+ * lib/argp-fmtstream.h (__argp_fmtstream_set_lmargin): M.
+ (__argp_fmtstream_set_rmargin): M.
+ (__argp_fmtstream_set_wmargin): M.
+ * lib/argp-help.c (validate_uparams): M.
+ (fill_in_uparams): MR.
+ (make_hol): MRSO.
+ (hol_entry_short_iterate): R.
+ (hol_entry_long_iterate): R.
+ (hol_entry_first_long): Rename 'num' to 'nopts'.
+ (canon_doc_option): M.
+ (hol_append): MR.
+ (argp_hol): O.
+ (hol_entry_help): RSBO.
+ (hol_help): RB.
+ (usage_argful_short_opt): R.
+ (usage_long_opt): R.
+ (hol_usage): SB.
+ (argp_args_levels): R.
+ (argp_args_usage): MRB.
+ (argp_doc): RBO.
+ (_help): MR.
+ (__argp_error): R.
+ * lib/argp-parse.c (group_parse): M.
+ (parser_init): MRB.
+ (parser_finalize): MS.
+ (parser_parse_next): R.
+ (__argp_parse): MR.
+ (__argp_input): M.
+ * lib/argz.c (argz_add_sep): M.
+ (argz_create_sep): M.
+ (argz_create): R.
+ (argz_replace): RB.
+ * lib/asinl.c (asinl): MRS.
+ * lib/asnprintf.c (asnprintf): M.
+ * lib/asnwprintf.c (asnwprintf): M.
+ * lib/asprintf.c (asprintf): M.
+ * lib/astrxfrm.c (astrxfrm): MR.
+ * lib/aszprintf.c (aszprintf): M.
+ * lib/at-func.c (AT_FUNC_NAME): MR.
+ * lib/at-func2.c (at_func2): MRS.
+ * lib/atanl.c (atanl): MRS.
+ * lib/backupfile.c (numbered_backup): R.
+ * lib/base32.c (decode_8): R.
+ (base32_decode_ctx): R.
+ * lib/base64.c (decode_4): R.
+ (base64_decode_ctx): R.
+ * lib/basename-lgpl.c (last_component): R.
+ (base_len): RO.
+ * lib/bitset.c (bitset_copy_): R.
+ * lib/bitset/list.c (lbitset_prune): MR.
+ (lbitset_weed): MR.
+ (lbitset_list): SB.
+ * lib/bitset/table.c (tbitset_list): SB.
+ * lib/boot-time-aux.h (get_windows_boot_time_fallback): R.
+ * lib/btoc32.c (btoc32): R.
+ * lib/c-asprintf.c (c_asprintf): M.
+ * lib/c-aszprintf.c (c_aszprintf): M.
+ * lib/c-snprintf.c (c_snprintf): M.
+ * lib/c-snzprintf.c (c_snzprintf): M.
+ * lib/c-strcasecmp.c (c_strcasecmp): R.
+ * lib/c-strcasestr.c (c_strcasestr): MRSB.
+ * lib/c-strncasecmp.c (c_strncasecmp): R.
+ * lib/c-strtod.c (C_STRTOD): R.
+ * lib/c-vsnzprintf.c (c_vsnzprintf): M.
+ * lib/c-xasprintf.c (c_xasprintf): M.
+ * lib/c32tob.c (c32tob): R.
+ * lib/canon-host.c (canon_host_r): MR.
+ * lib/canonicalize.c (canonicalize_filename_mode_stk): R.
+ * lib/canonicalize-lgpl.c (realpath_stk): R.
+ * lib/cbrt.c (cbrt): M.
+ * lib/cbrtf.c (cbrtf): M.
+ * lib/cbrtl.c (cbrtl): MR.
+ * lib/chdir-long.c (chdir_long): M.
+ (main): MR.
+ * lib/classpath.c (new_classpath): MB.
+ * lib/clean-temp.c (create_temp_dir): M.
+ (unregister_temp_file): M.
+ (unregister_temp_subdir): M.
+ (cleanup_temp_file): M.
+ (cleanup_temp_subdir): M.
+ (cleanup_temp_dir_contents): MSB.
+ (open_temp): R.
+ (fopen_temp): R.
+ (close_temp): RB.
+ (fclose_variant_temp): RB.
+ * lib/clean-temp-simple.c (cleanup_action): MSB.
+ (cleanup_temporary_file): M.
+ * lib/copy-file.c (copy_file_internal): MRB.
+ * lib/cosl.c (cosl): MR.
+ * lib/crc-generate-table.c (make_crc_table): M.
+ * lib/crc-x86_64-pclmul.c (crc32_update_no_xor_pclmul): MRSB.
+ * lib/crc.c (crc32_update_no_xor_slice_by_8): S.
+ (crc32_update_no_xor_slice_by_n): M.
+ (crc32_update_no_xor): MR.
+ * lib/csharpcomp.c (compile_csharp_using_mono): MRB.
+ (compile_csharp_using_dotnet): MRSB.
+ (compile_csharp_using_sscli): MRB.
+ * lib/csharpexec.c (execute_csharp_using_mono): MO.
+ (execute_csharp_using_dotnet): MO.
+ (execute_csharp_using_sscli): MO.
+ (execute_csharp_program): R.
+ * lib/cygpath.c (execute_and_read_line): M.
+ * lib/des.c (gl_des_is_weak_key): M.
+ (gl_3des_ecb_crypt): MO.
+ * lib/dfa.c (closure): B.
+ (dfamust): MRB.
+ * lib/di-set.c (map_device): M.
+ (di_set_insert): M.
+ (di_set_lookup): M.
+ * lib/dirname-lgpl.c (dir_len): R.
+ * lib/dprintf.c (dprintf): M.
+ * lib/dup.c (dup_nothrow): R.
+ * lib/dup2.c (ms_windows_dup2): M.
+ (klibc_dup2dirfd): M.
+ (klibc_dup2): MR.
+ (rpl_dup2): M.
+ * lib/dup3.c (dup3): M.
+ * lib/duplocale.c (duplocale): MRSB.
+ * lib/dzprintf.c (dzprintf): M.
+ * lib/euidaccess.c (euidaccess): MR.
+ (main): M.
+ * lib/exclude.c (add_exclude): R.
+ * lib/execl.c (execl): SB.
+ * lib/execle.c (execle): SB.
+ * lib/execlp.c (execlp): SB.
+ * lib/execute.c (execute): R.
+ * lib/fchdir.c (ensure_dirs_slot): M.
+ (get_name): M.
+ (_gl_register_fd): R.
+ * lib/fclose.c (rpl_fclose): MR.
+ * lib/fcntl.c (dupfd): RO.
+ (fcntl): R.
+ (klibc_dupdirfd): M.
+ (klibc_fcntl): MRSB.
+ * lib/fdopen.c (rpl_fdopen): M.
+ * lib/file-has-acl.c (get_aclinfo): R.
+ (fdfile_has_aclinfo): MR.
+ * lib/file-remote.c (main): M.
+ * lib/file-set.c (record_file): M.
+ (seen_file): R.
+ * lib/findprog.c (find_in_path): MR.
+ * lib/findprog-in.c (find_in_given_path): MR.
+ * lib/flock.c (do_lock): MR.
+ (do_unlock): M.
+ (flock): MR.
+ * lib/fma.c (decode): M.
+ * lib/fopen.c (rpl_fopen): MR.
+ * lib/forkpty.c (forkpty): M.
+ * lib/fprintf.c (fprintf): M.
+ * lib/freadseek.c (freadseek): MR.
+ * lib/freopen.c (rpl_freopen): M.
+ * lib/freopen-safer.c (freopen_safer): M.
+ * lib/frexp.c (FUNC): MR.
+ * lib/fseterr.c (fseterr): M.
+ * lib/fstatat.c (rpl_fstatat): M.
+ * lib/fstrcmp.c (fstrcmp_free_resources): M.
+ (fstrcmp_bounded): MR.
+ * lib/fsusage.c (statvfs_works): R.
+ * lib/fsync.c (fsync): M.
+ * lib/ftello.c (ftello): M.
+ * lib/ftruncate.c (SetFileSize): M.
+ * lib/fts.c (fts_open): MR.
+ (fts_load): M.
+ (fts_close): MR.
+ (filesystem_type): MRO.
+ (fts_read): MB.
+ (fts_children): M.
+ (fts_build): MR.
+ (fts_cross_check): RO.
+ (fd_ring_print): RO.
+ (fts_stat): RO.
+ (fts_sort): R.
+ (fts_alloc): M.
+ (fts_lfree): R.
+ (fts_palloc): M.
+ (fts_padjust): MS.
+ (fts_maxarglen): M.
+ (fts_safe_changedir): MR.
+ * lib/fts-cycle.c (enter_dir): MRO.
+ (leave_dir): M.
+ * lib/fzprintf.c (fzprintf): M.
+ * lib/gc-gnulib.c (gc_cipher_open): MR.
+ (gc_cipher_setkey): MSB.
+ (gc_cipher_setiv): M.
+ (gc_cipher_encrypt_inline): M.
+ (gc_cipher_decrypt_inline): M.
+ (gc_hash_open): MR.
+ (gc_hash_clone): M.
+ * lib/gc-libgcrypt.c (gc_init): Remove local variable 'err'.
+ (gc_cipher_open): MR.
+ (gc_cipher_setkey): M.
+ (gc_cipher_setiv): M.
+ (gc_hash_open): MR.
+ (gc_hash_clone): M.
+ (gc_md4): MR.
+ (gc_md5): MR.
+ (gc_sha1): MR.
+ (gc_sha256): MR.
+ (gc_sha512): MR.
+ (gc_sm3): MR.
+ (gc_hmac_md5): MR. Remove local variable 'err'.
+ (gc_hmac_sha1): MR. Remove local variable 'err'.
+ (gc_hmac_sha256): MR. Remove local variable 'err'.
+ (gc_hmac_sha512): MR. Remove local variable 'err'.
+ * lib/gc-pbkdf2.c (gc_pbkdf2_prf): MR.
+ * lib/gen-uni-tables.c (fill_attributes): M.
+ (debug_output_predicate): M.
+ (output_predicate_test): M.
+ (output_predicate): MR.
+ (output_category): MR.
+ (output_combclass): MR.
+ (output_bidi_category): MR.
+ (output_decimal_digit_test): M.
+ (output_decimal_digit): MR.
+ (output_digit_test): M.
+ (output_digit): MR.
+ (output_numeric_test): M.
+ (output_numeric): MR.
+ (fill_mirror): MR.
+ (get_mirror_value): M.
+ (output_mirror): MR.
+ (fill_properties): MR.
+ (fill_property30): MR.
+ (output_indic_conjunct_break_test): M.
+ (output_indic_conjunct_break): MR.
+ (fill_arabicshaping): MR.
+ (output_joining_type_test): M.
+ (output_joining_type): MR.
+ (output_joining_group_test): M.
+ (output_joining_group): MR.
+ (fill_scripts): MR.
+ (output_scripts): MR.
+ (output_scripts_byname): M.
+ (fill_blocks): MR.
+ (output_blocks): M.
+ (output_ident_category): MR.
+ (output_charclass): MR.
+ (output_charmap): MR.
+ (output_tables): M.
+ (fill_width): MR.
+ (output_nonspacing_property): MR.
+ (output_width_property_test): M.
+ (debug_output_lbrk_tables): M.
+ (fill_org_lbp): MR.
+ (debug_output_org_lbrk_tables): M.
+ (output_lbpea): M.
+ (output_lbrk_tables): R.
+ (output_lbrk_rules_as_tables): M.
+ (debug_output_wbrk_tables): M.
+ (fill_org_wbp): MR.
+ (debug_output_org_wbrk_tables): M.
+ (output_wbp): M.
+ (output_wbrk_tables): M.
+ (output_gbp_test): MR.
+ (output_gbp_table): MR.
+ (fill_org_gbp): MR.
+ (get_decomposition): MR.
+ (output_decomposition): M.
+ (output_decomposition_tables): R.
+ (fill_composition_exclusions): MR.
+ (debug_output_composition_tables): M.
+ (output_composition_tables): MSB.
+ (output_simple_mapping_test): M.
+ (output_simple_mapping): MR.
+ (fill_casing_rules): MR.
+ (fill_casefolding_rules): MR.
+ (output_casing_rules): M.
+ (output_version): MR.
+ * lib/get-rusage-as.c (get_rusage_as_via_setrlimit): R.
+ (get_rusage_as): M.
+ * lib/get-rusage-data.c (get_rusage_data_via_setrlimit): R.
+ (get_rusage_data): M.
+ * lib/get_ppid_of.c (get_ppid_of): M.
+ * lib/get_progname_of.c (get_progname_of): MR.
+ * lib/getaddrinfo.c (use_win32_p): M.
+ (getaddrinfo): MR.
+ (freeaddrinfo): M.
+ * lib/getcwd.c (__getcwd_generic): MRSBO.
+ * lib/getcwd-lgpl.c (rpl_getcwd): MS.
+ * lib/getdelim.c (getdelim): MR.
+ * lib/getdomainname.c (getdomainname): M.
+ * lib/getentropy.c (getentropy): R.
+ * lib/getgroups.c (rpl_getgroups): MR.
+ * lib/gethostname.c (rpl_gethostname): M.
+ * lib/getloadavg.c (getloadavg): MRB.
+ * lib/getlocalename_l-unsafe.c (newlocale): MR.
+ (duplocale): MR.
+ (freelocale): M.
+ * lib/getlogin_r.c (getlogin_r): M.
+ * lib/getndelim2.c (getndelim2): MR.
+ * lib/getopt.c (exchange): MS.
+ (process_long_option): MRB.
+ (_getopt_internal_r): MR.
+ (_getopt_internal): M.
+ (main): M.
+ * lib/getopt1.c (main): M.
+ * lib/getpass.c (getpass): MRB.
+ * lib/getprogname.c (getprogname): M.
+ * lib/getrusage.c (getrusage): M.
+ * lib/getsockopt.c (rpl_getsockopt): M.
+ * lib/getsubopt.c (getsubopt): M.
+ * lib/gettext.h (dcpgettext_expr): M.
+ (dcnpgettext_expr): M.
+ * lib/gettimeofday.c (gettimeofday): R.
+ * lib/getugroups.c (getugroups): MR.
+ * lib/getumask.c (getumask): R.
+ * lib/gl_anyavltree_list2.h (rebalance): MR.
+ (gl_tree_remove_node_from_tree): MR.
+ (gl_tree_nx_add_before): R.
+ (gl_tree_nx_add_after): R.
+ * lib/gl_anyhash2.h (hash_resize): M.
+ * lib/gl_anylinked_list2.h (gl_linked_get_at): R.
+ (gl_linked_nx_set_at): R.
+ (gl_linked_search_from_to): R.
+ (gl_linked_indexof_from_to): MR.
+ (gl_linked_nx_add_at): M.
+ (gl_linked_remove_node): M.
+ (gl_linked_remove_at): MR.
+ (gl_linked_iterator_from_to): M.
+ (gl_linked_sortedlist_search_from_to): R.
+ (gl_linked_sortedlist_indexof_from_to): R.
+ * lib/gl_anyrbtree_list2.h (rebalance_after_add): MR.
+ (gl_tree_remove_node_from_tree): M.
+ * lib/gl_anytree_list2.h (gl_tree_iterator): MB.
+ (gl_tree_sortedlist_indexof_from_to): R.
+ * lib/gl_anytree_omap.h (gl_tree_nx_getput): M.
+ (gl_tree_iterator): MB.
+ * lib/gl_anytree_oset.h (gl_tree_nx_add): M.
+ (gl_tree_update): M.
+ (gl_tree_iterator): MB.
+ * lib/gl_anytreehash_list1.h (add_to_bucket): M.
+ * lib/gl_array_list.c (grow): M.
+ (gl_array_nx_add_first): M.
+ (gl_array_nx_add_before): M.
+ (gl_array_nx_add_after): M.
+ (gl_array_nx_add_at): M.
+ (gl_array_remove_node): M.
+ (gl_array_remove_at): M.
+ * lib/gl_array_map.c (grow): M.
+ (gl_array_nx_getput): M.
+ (gl_array_remove_at): M.
+ * lib/gl_array_omap.c (grow): M.
+ (gl_array_nx_add_at): M.
+ (gl_array_remove_at): M.
+ * lib/gl_array_oset.c (grow): M.
+ (gl_array_nx_add_at): M.
+ (gl_array_remove_at): M.
+ * lib/gl_array_set.c (grow): M.
+ * lib/gl_avltree_ordered.h (rebalance): M.
+ (gl_tree_add_node_before): R.
+ (gl_tree_add_node_after): R.
+ (gl_tree_remove_node_no_free): M.
+ * lib/gl_carray_list.c (gl_carray_node_value): M.
+ (gl_carray_node_nx_set_value): M.
+ (gl_carray_get_at): M.
+ (gl_carray_nx_set_at): M.
+ (gl_carray_indexof_from_to): M.
+ (grow): M.
+ (gl_carray_nx_add_last): M.
+ (gl_carray_nx_add_at): M.
+ (gl_carray_remove_at): M.
+ (gl_carray_iterator_from_to): R.
+ (gl_carray_sortedlist_indexof_from_to): M.
+ (gl_carray_sortedlist_nx_add): M.
+ * lib/gl_rbtree_ordered.h (rebalance_after_add): M.
+ (gl_tree_remove_node_no_free): M.
+ * lib/gl_sublist.c (gl_sublist_sortedlist_search_from_to): M.
+ (gl_sublist_sortedlist_indexof_from_to): M.
+ * lib/glob.c (__glob): MR.
+ * lib/globfree.c (globfree): M.
+ * lib/glthread/lock.c (glthread_rwlock_init_for_glibc): M.
+ (glthread_rwlock_init_multithreaded): M.
+ (glthread_rwlock_rdlock_multithreaded): M.
+ (glthread_rwlock_wrlock_multithreaded): M.
+ (glthread_rwlock_destroy_multithreaded): M.
+ (glthread_rwlock_init_multithreaded): M.
+ (glthread_rwlock_rdlock_multithreaded): M.
+ (glthread_rwlock_wrlock_multithreaded): M.
+ (glthread_rwlock_unlock_multithreaded): M.
+ (glthread_rwlock_destroy_multithreaded): M.
+ (glthread_recursive_lock_init_multithreaded): M.
+ (glthread_recursive_lock_lock_multithreaded): M.
+ (glthread_recursive_lock_destroy_multithreaded): M.
+ (glthread_recursive_lock_init_multithreaded): M.
+ (glthread_recursive_lock_lock_multithreaded): M.
+ * lib/glthread/thread.c (gl_thread_create): M.
+ * lib/group-member.c (group_member): M.
+ (main): M.
+ * lib/hash.c (hash_get_next): MB.
+ (check_tuning): M.
+ (hash_initialize): M.
+ (hash_clear): M.
+ (hash_free): MS.
+ (transfer_entries): M.
+ (hash_rehash): MR.
+ (hash_insert_if_absent): MR.
+ (hash_remove): MR.
+ (hash_print): M.
+ * lib/hasmntopt.c (hasmntopt): M.
+ * lib/hmac.c (hmac_hash): R.
+ (GL_HMAC_FN): R.
+ * lib/human.c (group_number): MRO.
+ (human_readable): MR.
+ (humblock): M.
+ * lib/hypot.c (hypot): M.
+ * lib/hypotl.c (hypotl): M.
+ * lib/i-ring.c (i_ring_pop): M.
+ * lib/iconv_open.c (rpl_iconv_open): R.
+ * lib/idcache.c (getuidbyname): M.
+ (getgidbyname): M.
+ * lib/inet_ntop.c (inet_ntop4): M.
+ (inet_ntop6): R.
+ * lib/inet_pton.c (inet_pton4): MRBO.
+ (inet_pton6): MRBO.
+ * lib/ino-map.c (ino_map_insert): M.
+ * lib/integer_length.c (integer_length): M.
+ * lib/ioctl.c (rpl_ioctl): M.
+ (ioctl): M.
+ * lib/is_l-impl.h (FUNC): M.
+ * lib/isatty.c (IsCygwinConsoleHandle): R.
+ * lib/isnan.c (FUNC): MR.
+ * lib/javacomp.c (compile_using_envjavac): MRB.
+ (compile_using_javac): MB.
+ (execute_and_read_line): M.
+ (write_temp_file): M.
+ (get_classfile_version): MR.
+ (is_envjavac_usable): MR.
+ (is_javac_present): M.
+ (is_javac_usable): MR.
+ (compile_java_class): MR.
+ * lib/javaexec.c (execute_java_class): MRBO.
+ * lib/javaversion.c (execute_and_read_line): M.
+ (javaexec_version): R.
+ * lib/kwset.c (treefails): M.
+ (kwsprep): MRSB.
+ (bmexec_trans): MRSO.
+ (acexec_trans): MRS.
+ * lib/lchown.c (rpl_lchown): R.
+ * lib/linebuffer.c (readlinebuffer_delim): RO.
+ * lib/link.c (link): MRBO.
+ (rpl_link): M.
+ * lib/linkat.c (link_immediate): R.
+ (link_follow): M.
+ (linkat_follow): M.
+ * lib/localcharset.c (locale_charset): MR.
+ * lib/localeinfo.c (is_using_utf8): R. Rename 'mbs' to 'state'.
+ (init_localeinfo): Rename 's' to 'state'.
+ * lib/localename.c (gl_locale_name): MSB.
+ * lib/localename-environ.c (gl_locale_name_environ): MSB.
+ * lib/localename-unsafe.c (gl_locale_name_canonicalize): MSB.
+ (gl_locale_name_from_win32_LANGID): M.
+ (gl_locale_name_from_win32_LCID): M.
+ (enum_locales_fn): R.
+ (gl_locale_name_unsafe): MSB.
+ * lib/log2.c (log2): M.
+ * lib/log2f.c (log2f): M.
+ * lib/log2l.c (log2l): M.
+ * lib/login_tty.c (login_tty): M.
+ * lib/logl.c (logl): MR.
+ * lib/long-options.c (parse_long_options): MR.
+ (parse_gnu_standard_options_only): M.
+ * lib/mbfile.h (mbfile_multi_getc): MR.
+ * lib/mbmemcasecoll.c (apply_c32tolower): M.
+ (mbmemcasecoll): MR.
+ * lib/mbrtoc32.c (mbrtoc32): R.
+ * lib/mbrtowc.c (rpl_mbrtowc): MRS.
+ * lib/mbrtowc-impl.h: MRB.
+ * lib/mbscasestr.c (knuth_morris_pratt_multibyte): MR.
+ (mbscasestr): R.
+ * lib/mbscspn.c (mbscspn): MR.
+ * lib/mbsnrtowcs-impl.h (FUNC): M.
+ * lib/mbspbrk.c (mbspbrk): MR.
+ * lib/mbsrtowcs-impl.h (FUNC): M.
+ * lib/mbsspn.c (mbsspn): MR.
+ * lib/mbsstr.c (knuth_morris_pratt_multibyte): MR.
+ (mbsstr): MR.
+ * lib/mbswidth.c (mbsnwidth): M.
+ * lib/mbtowc-impl.h (mbtowc): MR.
+ * lib/mbtowc-lock.h (mbtowc_with_lock): M.
+ * lib/mcel.h: MR in comments.
+ * lib/md2.c (md2_finish_ctx): M.
+ (md2_process_bytes): M.
+ (md2_update_chksum): M.
+ (md2_compress): M.
+ * lib/md2-stream.c (md2_stream): MR.
+ * lib/md4.c (md4_finish_ctx): M.
+ (md4_process_block): MR.
+ * lib/md4-stream.c (md4_stream): MR.
+ * lib/md5-stream.c (md5_stream): MR.
+ * lib/mem-hash-map.c (compute_hashval): M.
+ (lookup): M.
+ * lib/memchr.c (__memchr): MRB.
+ * lib/memchr2.c (memchr2): MRB.
+ * lib/memrchr.c (__memrchr): MRB.
+ * lib/mgetgroups.c (mgetgroups): MRS.
+ * lib/mkancesdirs.c (mkancesdirs): M.
+ * lib/mkdir.c (rpl_mkdir): MR.
+ * lib/mkdir-p.c (make_dir_parents): R.
+ * lib/modechange.c (mode_compile): R.
+ * lib/mountlist.c (fstype_to_string): M.
+ (dev_from_mount_options): MR.
+ (read_file_system_list): MR.
+ * lib/mpsort.c (mpsort_into_tmp): M.
+ (mpsort_with_tmp): M.
+ * lib/msvc-inval.h (TRY_MSVC_INVAL): M.
+ * lib/mtx.c (mtx_init): MSB.
+ * lib/nanosleep.c (nanosleep): M.
+ * lib/nl_langinfo.c (ctype_codeset): MR.
+ (nl_langinfo_with_lock): M.
+ * lib/nonblocking.c (get_nonblocking_flag): M.
+ (set_nonblocking_flag): M.
+ * lib/nproc.c (num_processors_via_affinity_mask): M.
+ (cgroup2_mount): MR.
+ (get_cgroup2_cpu_quota): M.
+ (parse_omp_threads): Remove variable 'ret'.
+ (num_processors): M.
+ * lib/obstack.c (_obstack_newchunk): M.
+ (_obstack_allocated_p): M.
+ (__obstack_free): M.
+ * lib/obstack_printf.c (OBSTACK_PRINTF): M.
+ (OBSTACK_VPRINTF): M.
+ * lib/omp-init.c (parse_omp_threads): Remove variable 'ret'.
+ * lib/openat-proc.c (openat_proc_name): R.
+ * lib/openat2.c (do_openat2): R.
+ (openat2): MSB.
+ * lib/opendir.c (opendir): MR.
+ * lib/openpty.c (openpty): M.
+ * lib/os2-spawn.c (prepare_spawn): M.
+ (spawnpvech): R.
+ * lib/pagealign_alloc.c (pagealign_alloc): MR.
+ (pagealign_xalloc): M.
+ (pagealign_free): M.
+ * lib/parse-duration.c (parse_scaled_value): M.
+ (parse_year_month_day): M.
+ (parse_yearmonthday): MR.
+ (parse_YMWD): SB.
+ (parse_hour_minute_second): M.
+ (parse_hourminutesecond): MR.
+ (parse_HMS): SB.
+ (parse_time): M.
+ (parse_period): MR.
+ (parse_non_iso8601): M.
+ * lib/passfd.c (sendfd): MRO.
+ (recvfd): MRO.
+ * lib/perror.c (perror): M.
+ * lib/physmem.c (physmem_total): M.
+ (physmem_claimable): M.
+ * lib/pipe-filter-gi.c (filter_loop): MRB.
+ (pipe_filter_gi_create): M.
+ (pipe_filter_gi_close): M.
+ * lib/pipe-filter-ii.c (_beginthreadex): M.
+ (WaitForMultipleObjects): MR.
+ (pipe_filter_ii_execute): MRB.
+ * lib/poll.c (IsSocketHandle): R.
+ (windows_compute_revents): MRB.
+ (windows_compute_revents_socket): M.
+ (poll): MRB. Remove variable 'bRet'.
+ * lib/popen.c (rpl_popen): MB.
+ * lib/posix_openpt.c (posix_openpt): M.
+ * lib/posixtm.c (posix_time_parse): R.
+ (posixtime): R.
+ * lib/pread.c (pread): M.
+ * lib/printf.c (printf): M.
+ * lib/printf-frexp.c (FUNC): R.
+ * lib/printf-parse.c (PRINTF_PARSE): MR.
+ * lib/progreloc.c (maybe_executable): R.
+ (find_executable): MRSB.
+ (prepare_relocate): M.
+ * lib/propername.c (mbsstr_trimmed_wordbounded): RSB.
+ (proper_name_utf8): M.
+ * lib/pselect.c (pselect): MR.
+ * lib/pt_chown.c (do_pt_chown): MR.
+ * lib/pthread-cond.c (pthread_cond_timedwait): R.
+ * lib/pthread-rwlock.c (pthread_rwlockattr_init): MSB.
+ (pthread_rwlock_init): MSB.
+ (pthread_rwlock_rdlock): MSB.
+ (pthread_rwlock_wrlock): MSB.
+ (pthread_rwlock_tryrdlock): MB.
+ (pthread_rwlock_trywrlock): MB.
+ (pthread_rwlock_timedrdlock): MSB.
+ (pthread_rwlock_timedwrlock): MSB.
+ (pthread_rwlock_unlock): MSB.
+ (pthread_rwlock_destroy): MSB.
+ (pthread_rwlock_init): MSB.
+ (pthread_rwlock_timedrdlock): MRB.
+ (pthread_rwlock_timedwrlock): MRB.
+ * lib/pthread_mutex_timedlock.c (pthread_mutex_timedlock): MRB.
+ * lib/pthread_sigmask.c (pthread_sigmask): MR.
+ * lib/ptsname_r.c (ptsname_r): MR.
+ * lib/putenv.c (putenv): M.
+ * lib/pwrite.c (pwrite): M.
+ * lib/qcopy-acl.c (qcopy_acl): Remove a use of variable 'ret'.
+ * lib/qset-acl.c (qset_acl): M.
+ * lib/qsort.c (_quicksort): MR.
+ * lib/quotearg.c (set_quoting_flags): M.
+ (quotearg_buffer_restyled): MRSB.
+ * lib/random.c (__initstate): M.
+ (__setstate): M.
+ (__random): R.
+ * lib/random_r.c (__srandom_r): M.
+ (__setstate_r): MO.
+ (__random_r): M.
+ * lib/rawmemchr.c (rawmemchr): RB.
+ * lib/read-file.c (fread_file): M.
+ (read_file): M.
+ * lib/readdir.c (readdir): MR.
+ * lib/readline.c (readline): R.
+ * lib/readtokens.c (readtoken): R.
+ (readtokens): M.
+ * lib/regex-quote.c (regex_quote_spec_gnu): MB.
+ (regex_quote_spec_pcre): MB.
+ (regex_quote_length): MR.
+ (regex_quote): MB.
+ * lib/relocatable.c (set_this_relocation_prefix): M.
+ (compute_curr_prefix): MR.
+ (find_shared_library_fullname): MRS.
+ (relocate): M.
+ * lib/relocwrapper.c (activate_libdirs): MB.
+ (main): M.
+ * lib/rename.c (rpl_rename): MRBO.
+ * lib/renameatu.c (renameatu): MRB.
+ * lib/rijndael-alg-fst.c (rijndaelKeySetupEnc): MSB.
+ (rijndaelKeySetupDec): MRSB.
+ (rijndaelEncrypt): MSB.
+ (rijndaelDecrypt): MSB.
+ * lib/rijndael-api-fst.c (rijndaelMakeKey): MRSB.
+ (rijndaelCipherInit): MSB.
+ (rijndaelBlockEncrypt): MRSB.
+ (rijndaelPadEncrypt): MRSB.
+ (rijndaelBlockDecrypt): MRSB.
+ (rijndaelPadDecrypt): MRSB.
+ * lib/rmdir.c (rpl_rmdir): M.
+ * lib/rpmatch.c (localized_pattern): MS.
+ (try): M.
+ (rpmatch): MSB.
+ * lib/same.c (same_nameat): R. Remove variable 'flags'.
+ * lib/savedir.c (streamsavedir): MRB.
+ * lib/scandir.c (SCANDIR): MR.
+ * lib/select.c (IsSocketHandle): R.
+ (windows_poll_handle): MRSB. Remove variable 'bRet'.
+ (rpl_select): MR. Remove variable 'bRet'.
+ * lib/set-permissions.c (set_acls_from_mode): R.
+ (context_acl_from_mode): R.
+ (context_aclv_from_mode): M.
+ (set_acls_from_mode): MR.
+ (context_acl_from_mode): M.
+ (set_acls): R.
+ (set_permissions): MS.
+ * lib/setenv.c (__add_to_environ): M.
+ (rpl_setenv): M.
+ * lib/sethostname.c (sethostname): MR.
+ * lib/setlocale.c (setlocale_unixlike): MR.
+ (langcmp): R.
+ (setlocale_improved): MR.
+ * lib/setlocale_null.c (setlocale_null_r_with_lock): M.
+ (setlocale_null): M.
+ * lib/setsockopt.c (rpl_setsockopt): R.
+ * lib/sh-quote.c (shell_quote_argv): MB.
+ * lib/sha1.c (sha1_process_block): R.
+ * lib/sha1-stream.c (sha1_stream): M.
+ * lib/sha256.c (sha256_process_block): MR.
+ * lib/sha256-stream.c (shaxxx_stream): M.
+ * lib/sha3.c (sha3_read_ctx): R.
+ (sha3_process_block): R.
+ * lib/sha3-stream.c (sha3_xxx_stream): M.
+ * lib/sha512-stream.c (shaxxx_stream): M.
+ * lib/sig2str.c (str2signum): RS.
+ (sig2str): MR.
+ * lib/sigaction.c (sigaction_handler): MR.
+ (sigaction): MRB.
+ * lib/sigprocmask.c (sigprocmask): M.
+ * lib/sigsegv.c (sigsegv_handler): MR.
+ * lib/sincosl.c (kernel_sinl): MRS.
+ (kernel_cosl): MRS.
+ * lib/sinl.c (sinl): MR.
+ * lib/sleep.c (rpl_sleep): M.
+ * lib/sm3.c (sm3_process_block): MR.
+ * lib/sm3-stream.c (sm3_stream): MR.
+ * lib/snprintf.c (snprintf): M.
+ * lib/snzprintf.c (snzprintf): M.
+ * lib/socket.c (rpl_socket): M.
+ * lib/sockets.c (close_fd_maybe_socket): MR.
+ (ioctl_fd_maybe_socket): MR.
+ (gl_sockets_startup): M.
+ (gl_sockets_cleanup): M.
+ * lib/spawn-pipe.c (create_pipe): MR.
+ * lib/spawni.c (__spawni): Split variable declaration.
+ * lib/sprintf.c (sprintf): M.
+ * lib/sqrtl.c (sqrtl): MR.
+ * lib/ssfmalloc.h (allocate_block_from_pool): MSB.
+ * lib/stackvma.c (rof_open): M.
+ (vma_iterate_proc): RSB.
+ (vma_iterate_bsd): MB.
+ (mapped_range_start): M.
+ (mapped_range_end): M.
+ (is_unmapped): MR.
+ (mapped_range_start): M.
+ (mapped_range_end): M.
+ (vma_iterate): MR.
+ * lib/stat-w32.c (_gl_convert_FILETIME_to_timespec): R.
+ * lib/stdio-consolesafe.c (gl_consolesafe_fprintf): R.
+ (gl_consolesafe_printf): R.
+ * lib/stdio-read.c (CALL_WITH_ERRNO_FIX): M.
+ (scanf): M.
+ (fscanf): M.
+ * lib/stdio-write.c (CALL_WITH_SIGPIPE_EMULATION): M.
+ (printf): M.
+ (fprintf): M.
+ * lib/stpncpy.c (__stpncpy): MSB.
+ * lib/str-kmp.h (knuth_morris_pratt): M.
+ * lib/str-two-way.h (critical_factorization): MSB.
+ (two_way_short_needle): MS.
+ (two_way_long_needle): MRS.
+ * lib/strcasecmp.c (strcasecmp): R.
+ * lib/strcasecmp_l.c (strcasecmp_l): MR.
+ * lib/strcasestr.c (strcasestr): MRSB.
+ * lib/strchrnul.c (strchrnul): MRB.
+ * lib/strerror.c (strerror): M.
+ * lib/strerror_l.c (strerror_l_r): R.
+ * lib/strerror_r.c (local_snprintf): M.
+ (strerror_r): M.
+ * lib/strfmon_l.c (rpl_strfmon_l): MR.
+ * lib/strftime.c (__strftime_internal): MR.
+ * lib/striconv.c (mem_cd_iconv): MR.
+ (str_cd_iconv): MR.
+ (str_iconv): M.
+ * lib/striconveh.c (iconveh_open): MR.
+ (utf8conv_carefully): M.
+ (mem_cd_iconveh_internal): MR.
+ (mem_iconveh): M.
+ (str_iconveh): M.
+ * lib/striconveha.c (uniconv_register_autodetect): MRSB.
+ (mem_iconveha_notranslit): MS.
+ (mem_iconveha): M.
+ (str_iconveha_notranslit): MS.
+ (str_iconveha): M.
+ * lib/string-buffer-printf.c (sb_appendvf): R.
+ (sb_appendf): R.
+ * lib/string-buffer-reversed-printf.c (sbr_prependvf): R.
+ (sbr_prependf): R.
+ * lib/string-desc.c (sd_new): R.
+ * lib/stripslash.c (strip_trailing_slashes): M.
+ * lib/strncasecmp.c (strncasecmp): R.
+ * lib/strncasecmp_l.c (strncasecmp_l): MR.
+ * lib/strptime.c (__strptime_internal): RSB.
+ * lib/strsep.c (strsep): R.
+ * lib/strsignal.c (strsignal): R.
+ * lib/strstr.c (strstr): MRSB.
+ * lib/strtod.c (parse_number): MR.
+ (STRTOD): MR.
+ * lib/strtok_r.c (__strtok_r): M.
+ * lib/strtol.c (strtol): MR.
+ * lib/struniq.h (struniq): M.
+ * lib/supersede.c (open_supersede): R.
+ * lib/system-quote.c (system_quote_argv): MB.
+ * lib/szprintf.c (szprintf): M.
+ * lib/tanl.c (kernel_tanl): MRS.
+ (tanl): MR.
+ * lib/tempname.c (try_tempname_len): M.
+ * lib/term-style-control.c (sprintf_integer): MR.
+ * lib/textstyle.in.h (ostream_printf): MR.
+ * lib/time.c (time): M.
+ * lib/times.c (filetime2clock): M.
+ * lib/timespec-add.c (timespec_add): R.
+ * lib/timespec-sub.c (timespec_sub): R.
+ * lib/tmpdir.c (path_search): MR.
+ * lib/tmpfile.c (tmpfile): M.
+ * lib/to_l-impl.h (FUNC): M.
+ * lib/tparm.c (tparm): MRB.
+ * lib/trigl.c (ieee754_rem_pio2l): MRS.
+ (kernel_rem_pio2): MRS.
+ * lib/trim.c (trim2): MR.
+ * lib/tsearch.c (check_tree): R.
+ (maybe_split_for_insert): M.
+ (__tsearch): MR.
+ (__tfind): M.
+ (__tdelete): MRB.
+ * lib/ttyname_r.c (ttyname_r): M.
+ * lib/uname.c (uname): MR.
+ * lib/unicase/locale-language.c (uc_locale_language): M.
+ * lib/unicase/u-casecmp.h (FUNC): MR.
+ * lib/unicase/u-casecoll.h (FUNC): MR.
+ * lib/unicase/u-casemap.h (FUNC): MR.
+ * lib/unicase/u-casexfrm.h (FUNC): MR.
+ * lib/unicase/u-ct-casefold.h (FUNC): MR.
+ * lib/unicase/u-ct-totitle.h (FUNC): MR.
+ * lib/unicase/u-is-cased.h (FUNC): MR.
+ * lib/unicase/u-is-invariant.h (FUNC): MR.
+ * lib/unicase/u8-casefold.c (read_file): M.
+ * lib/unicase/u8-tolower.c (read_file): M.
+ * lib/unicase/u8-totitle.c (read_file): M.
+ * lib/unicase/u8-toupper.c (read_file): M.
+ * lib/unicase/ulc-casecmp.c (ulc_u8_casefold): MR.
+ * lib/unicase/ulc-casexfrm.c (ulc_casexfrm): MR.
+ * lib/unicodeio.c (unicode_to_mb): MR.
+ * lib/uniconv/u-conv-from-enc.h (FUNC): M.
+ * lib/uniconv/u-conv-to-enc.h (FUNC): MR.
+ * lib/uniconv/u-strconv-from-enc.h (FUNC): M.
+ * lib/uniconv/u-strconv-to-enc.h (FUNC): M.
+ * lib/uniconv/u16-conv-to-enc.c (FUNC): MR.
+ * lib/uniconv/u8-conv-from-enc.c (u8_conv_from_encoding): R.
+ * lib/uniconv/u8-conv-to-enc.c (u8_conv_to_encoding): R.
+ * lib/uniconv/u8-strconv-to-enc.c (u8_strconv_to_encoding): MS.
+ * lib/unictype/3level.h (CONCAT(TABLE,_add)): M.
+ (CONCAT(TABLE,_finalize)): MRB.
+ * lib/unictype/3levelbit.h (CONCAT(TABLE,_add)): M.
+ (CONCAT(TABLE,_finalize)): MRB.
+ * lib/unictype/bidi_byname.c (uc_bidi_class_byname): M.
+ * lib/unictype/categ_and.c (uc_general_category_and): MR.
+ * lib/unictype/categ_and_not.c (uc_general_category_and_not): MR.
+ * lib/unictype/categ_byname.c (uc_general_category_byname): M.
+ * lib/unictype/categ_of.c (uc_general_category): R.
+ * lib/unictype/categ_or.c (uc_general_category_or): MR.
+ * lib/unictype/combiningclass_byname.c (uc_combining_class_byname): M.
+ * lib/unictype/incb_byname.c (uc_indic_conjunct_break_byname): M.
+ * lib/unictype/joininggroup_byname.c (uc_joining_group_byname): M.
+ * lib/unictype/joiningtype_byname.c (uc_joining_type_byname): M.
+ * lib/unictype/pr_byname.c (uc_property_byname): MRB.
+ * lib/unictype/scripts.c (uc_script_byname): M.
+ * lib/unigbrk/u-grapheme-prev.h
+ (ends_with_incb_consonant_extended_linker_extended): M.
+ (ends_with_emoji_modifier_sequence): M.
+ (ends_with_ri_count): M.
+ (FUNC): M.
+ * lib/unigbrk/uc-is-grapheme-break.c (uc_is_grapheme_break): M.
+ * lib/unigbrk/ulc-grapheme-breaks.c (ulc_grapheme_breaks): M.
+ * lib/unilbrk/u16-width-linebreaks.c (u16_width_linebreaks_internal): M.
+ * lib/unilbrk/u32-width-linebreaks.c (u32_width_linebreaks_internal): M.
+ * lib/unilbrk/u8-possible-linebreaks.c (read_file): M.
+ * lib/unilbrk/u8-width-linebreaks.c (u8_width_linebreaks_internal): M.
+ (read_file): M.
+ * lib/unilbrk/ulc-possible-linebreaks.c
+ (ulc_possible_linebreaks_internal): M.
+ (read_file): M.
+ * lib/unilbrk/ulc-width-linebreaks.c (ulc_width_linebreaks_internal): M.
+ (read_file): M.
+ * lib/uniname/uniname.c (unicode_name_word): MR.
+ (unicode_character_name): M.
+ (unicode_name_character): MR.
+ * lib/uninorm/canonical-decomposition.c (uc_canonical_decomposition): M.
+ * lib/uninorm/composition.c (uc_composition): M.
+ * lib/uninorm/decomposition.c (uc_decomposition): M.
+ * lib/uninorm/u-normalize-internal.h (FUNC): MR.
+ * lib/uninorm/u-normcmp.h (FUNC): MR.
+ * lib/uninorm/u-normcoll.h (FUNC): MR.
+ * lib/uninorm/u-normxfrm.h (FUNC): MR.
+ * lib/uninorm/uninorm-filter.c (uninorm_filter_write): M.
+ * lib/unistdio/u-asnprintf.h (ASNPRINTF): M.
+ * lib/unistdio/u-asprintf.h (ASPRINTF): M.
+ * lib/unistdio/u-snprintf.h (SNPRINTF): M.
+ * lib/unistdio/u-sprintf.h (SPRINTF): M.
+ * lib/unistdio/u-vsnprintf.h (VSNPRINTF): M.
+ * lib/unistdio/u-vsprintf.h (VSPRINTF): M.
+ * lib/unistdio/ulc-fprintf.c (ulc_fprintf): M.
+ * lib/unistdio/ulc-vfprintf.c (ulc_vfprintf): M.
+ * lib/unistr/u16-chr.c (u16_chr): R.
+ * lib/unistr/u16-mbsnlen.c (u16_mbsnlen): M.
+ * lib/unistr/u16-next.c (u16_next): M.
+ * lib/unistr/u16-strchr.c (u16_strchr): R.
+ * lib/unistr/u16-strrchr.c (u16_strrchr): R.
+ * lib/unistr/u16-to-u32.c (FUNC): MR.
+ * lib/unistr/u16-to-u8.c (FUNC): MR.
+ * lib/unistr/u32-next.c (u32_next): M.
+ * lib/unistr/u32-to-u16.c (FUNC): MR.
+ * lib/unistr/u32-to-u8.c (FUNC): MR.
+ * lib/unistr/u8-chr.c (u8_chr): M.
+ * lib/unistr/u8-mbsnlen.c (u8_mbsnlen): M.
+ * lib/unistr/u8-next.c (u8_next): M.
+ * lib/unistr/u8-strchr.c (u8_strchr): R.
+ * lib/unistr/u8-strrchr.c (u8_strrchr): R.
+ * lib/unistr/u8-to-u16.c (FUNC): MR.
+ * lib/unistr/u8-to-u32.c (FUNC): MR.
+ * lib/uniwbrk/u8-wordbreaks.c (read_file): M.
+ * lib/uniwbrk/ulc-wordbreaks.c (ulc_wordbreaks): M.
+ (read_file): M.
+ * lib/uniwidth/u16-width.c (u16_width): M.
+ * lib/uniwidth/u32-width.c (u32_width): M.
+ * lib/uniwidth/u8-width.c (u8_width): M.
+ * lib/unlinkat.c (rpl_unlinkat): MR.
+ * lib/unsetenv.c (unsetenv): M.
+ (rpl_unsetenv): R.
+ * lib/userspec.c (parse_with_separator): MRS.
+ (main): MR.
+ * lib/utime.c (_gl_utimens_windows): M.
+ * lib/utimecmp.c (utimecmpat): R.
+ * lib/utimens.c (validate_timespec): R.
+ (fdutimens): MR.
+ (lutimens): MR.
+ * lib/utimensat.c (rpl_utimensat): M.
+ * lib/vasnprintf.c (divide): M.
+ (decode_long_double): MR.
+ (decode_double): MR.
+ (scale10_round_decimal_decoded): MR.
+ (floorlog10l): MR.
+ (floorlog10): MR.
+ (VASNPRINTF): MR.
+ * lib/vc-mtime.c (is_git_present): MR.
+ (git_vc_controlled): MR.
+ (git_unmodified): M.
+ (git_mtime): MR.
+ (abs_git_checkout): MR.
+ (max_vc_mtime): MR.
+ * lib/vdzprintf.c (vdzprintf): M.
+ * lib/vfzprintf.c (vfzprintf): M.
+ * lib/vma-iter.c (rof_open): M.
+ (vma_iterate_proc): MRSB.
+ (vma_iterate_bsd): MB.
+ (vma_iterate): MR.
+ * lib/vsnzprintf.c (vsnzprintf): M.
+ * lib/vszprintf.c (vszprintf): M.
+ * lib/wait-process.c (klibc_waitpid): M.
+ (wait_subprocess): MR.
+ * lib/wcs-two-way.h (critical_factorization): MSB.
+ (two_way_short_needle): MS.
+ * lib/wcsstr-impl.h (FUNC): MRSB.
+ * lib/wcswidth-impl.h (FUNC): B.
+ * lib/wcsxfrm-impl.h (wcsxfrm): MR.
+ * lib/wctomb-impl.h (wctomb): M.
+ * lib/wgetcwd-lgpl.c (wgetcwd): MRS.
+ * lib/windows-cond.c (glwthread_waitqueue_add): M.
+ (glwthread_waitqueue_notify_first): M.
+ (glwthread_waitqueue_notify_all): M.
+ (glwthread_cond_wait): M.
+ (glwthread_cond_timedwait): MRS.
+ * lib/windows-cygpath.c (execute_and_read_line): MR.
+ * lib/windows-rwlock.c (glwthread_waitqueue_add): M.
+ (glwthread_rwlock_rdlock): M.
+ (glwthread_rwlock_wrlock): M.
+ * lib/windows-spawn.c (quoted_arg_length): M.
+ (quoted_arg_string): M.
+ (prepare_spawn): MR.
+ (compose_command): MRB.
+ (compose_envblock): RSB.
+ * lib/windows-thread.c (glwthread_thread_self): M.
+ (glwthread_thread_create): M.
+ * lib/windows-timedmutex.c (glwthread_timedmutex_timedlock): MR.
+ * lib/windows-timedrecmutex.c (glwthread_timedrecmutex_timedlock): MR.
+ * lib/windows-timedrwlock.c (glwthread_waitqueue_add): M.
+ (glwthread_waitqueue_notify_first): M.
+ (glwthread_waitqueue_notify_all): M.
+ (glwthread_timedrwlock_rdlock): M.
+ (glwthread_timedrwlock_wrlock): M.
+ (glwthread_timedrwlock_timedrdlock): MR.
+ (glwthread_timedrwlock_timedwrlock): MR.
+ * lib/xasprintf.c (xasprintf): M.
+ * lib/xconcat-filename.c (xconcatenated_filename): M.
+ * lib/xmalloc.c (xpalloc): R.
+ * lib/xmalloca.c (xmmalloca): M.
+ * lib/xprintf.c (xprintf): M.
+ (xfprintf): M.
+ * lib/xstring-buffer-printf.c (sb_xappendf): M.
+ * lib/xstring-buffer-reversed-printf.c (sbr_xprependf): M.
+ * lib/xstrtod.c (XSTRTOD): MR.
+ * lib/xstrtol.c (__xstrtol): R.
+ * lib/xstrtol-error.c (xstrtol_error): R.
+ * lib/xvasprintf.c (xstrcat): MB.
+ (xvasprintf): R.
+ * lib/zprintf.c (zprintf): M.
+
2025-12-09 Bruno Haible <bruno@clisp.org>
Remove unnecessary variable initializations.
int
accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
{
- int fd;
-
#if HAVE_DECL_ACCEPT4
# undef accept4
/* Try the system call first, if it exists. (We may be running with a glibc
return -1;
}
- fd = accept (sockfd, addr, addrlen);
+ int fd = accept (sockfd, addr, addrlen);
if (fd < 0)
return -1;
{
HANDLE curr_process = GetCurrentProcess ();
HANDLE old_handle = (HANDLE) _get_osfhandle (fd);
- HANDLE new_handle;
- int nfd;
+ HANDLE new_handle;
if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
old_handle, /* SourceHandle */
curr_process, /* TargetProcessHandle */
/* Closing fd before allocating the new fd ensures that the new fd will
have the minimum possible value. */
close (fd);
- nfd = _open_osfhandle ((intptr_t) new_handle,
- O_NOINHERIT | (flags & (O_TEXT | O_BINARY)));
+ int nfd = _open_osfhandle ((intptr_t) new_handle,
+ O_NOINHERIT | (flags & (O_TEXT | O_BINARY)));
if (nfd < 0)
{
CloseHandle (new_handle);
for (int i = 0; i < count; i++)
{
ace_t *ace = &entries[i];
- unsigned int index1;
- unsigned int index2;
+ unsigned int index1;
if (ace->a_type == NEW_ACE_ACCESS_ALLOWED_ACE_TYPE)
index1 = 1;
else if (ace->a_type == NEW_ACE_ACCESS_DENIED_ACE_TYPE)
else
return 1;
+ unsigned int index2;
if (ace->a_flags == NEW_ACE_OWNER)
index2 = 0;
else if (ace->a_flags == (NEW_ACE_GROUP | NEW_ACE_IDENTIFIER_GROUP))
long double
acosl (long double x)
{
- long double t, p, q;
+ long double t;
if (x < 0.0L)
{
return (x - x) / (x - x); /* asin(|x|>1) is NaN */
}
- else if (x < 0.5L) /* |x| < 0.5 */
+ if (x < 0.5L) /* |x| < 0.5 */
{
if (x < 0.000000000000000006938893903907228377647697925567626953125L) /* |x| < 2**-57 */
/* acos(0)=+-pi/2 with inexact */
return x * pio2_hi + x * pio2_lo;
t = x * x;
- p = (((((((((pS9 * t
- + pS8) * t
- + pS7) * t
- + pS6) * t
- + pS5) * t
- + pS4) * t
- + pS3) * t
- + pS2) * t
- + pS1) * t
- + pS0) * t;
-
- q = (((((((( t
- + qS8) * t
- + qS7) * t
- + qS6) * t
- + qS5) * t
- + qS4) * t
- + qS3) * t
- + qS2) * t
- + qS1) * t
- + qS0;
+ long double p = (((((((((pS9 * t
+ + pS8) * t
+ + pS7) * t
+ + pS6) * t
+ + pS5) * t
+ + pS4) * t
+ + pS3) * t
+ + pS2) * t
+ + pS1) * t
+ + pS0) * t;
+
+ long double q = (((((((( t
+ + qS8) * t
+ + qS7) * t
+ + qS6) * t
+ + qS5) * t
+ + qS4) * t
+ + qS3) * t
+ + qS2) * t
+ + qS1) * t
+ + qS0;
return pio2_hi - (x + x * (p / q) - pio2_lo);
}
else if (x < 0.625) /* 0.625 */
{
t = x - 0.5625;
- p = ((((((((((rS10 * t
- + rS9) * t
- + rS8) * t
- + rS7) * t
- + rS6) * t
- + rS5) * t
- + rS4) * t
- + rS3) * t
- + rS2) * t
- + rS1) * t
- + rS0) * t;
-
- q = ((((((((( t
- + sS9) * t
- + sS8) * t
- + sS7) * t
- + sS6) * t
- + sS5) * t
- + sS4) * t
- + sS3) * t
- + sS2) * t
- + sS1) * t
- + sS0;
+ long double p = ((((((((((rS10 * t
+ + rS9) * t
+ + rS8) * t
+ + rS7) * t
+ + rS6) * t
+ + rS5) * t
+ + rS4) * t
+ + rS3) * t
+ + rS2) * t
+ + rS1) * t
+ + rS0) * t;
+
+ long double q = ((((((((( t
+ + sS9) * t
+ + sS8) * t
+ + sS7) * t
+ + sS6) * t
+ + sS5) * t
+ + sS4) * t
+ + sS3) * t
+ + sS2) * t
+ + sS1) * t
+ + sS0;
return (pio2_hi - asinr5625) - (p / q - pio2_lo);
}
read-write loop work around an empty-input bug noted below. */
int fd = fileno (stream);
int result;
- struct stat st;
- off_t off = ftello (stream);
- if (0 <= off && fstat (fd, &st) == 0
- && (S_ISREG (st.st_mode) || S_TYPEISSHM (&st) || S_TYPEISTMO (&st))
- && off < st.st_size && st.st_size - off < SYS_BUFSIZE_MAX)
- {
- /* Make sure the offset of fileno (stream) reflects how many bytes
- have been read from stream before this function got invoked.
- Note: fflush on an input stream after ungetc does not work as expected
- on some platforms. Therefore this situation is not supported here. */
- if (fflush (stream))
- result = -EIO;
- else
- {
- off_t nbytes = st.st_size - off;
- if (sendfile (ofd, fd, &off, nbytes) == nbytes)
- {
- if (read (ofd, resblock, hashlen) == hashlen)
- {
- /* The input buffers of stream are no longer valid. */
- if (lseek (fd, off, SEEK_SET) != (off_t)-1)
- result = 0;
- else
- /* The file position of fd has not changed. */
+ {
+ struct stat st;
+ off_t off = ftello (stream);
+ if (0 <= off && fstat (fd, &st) == 0
+ && (S_ISREG (st.st_mode) || S_TYPEISSHM (&st) || S_TYPEISTMO (&st))
+ && off < st.st_size && st.st_size - off < SYS_BUFSIZE_MAX)
+ {
+ /* Make sure the offset of fileno (stream) reflects how many bytes
+ have been read from stream before this function got invoked.
+ Note: fflush on an input stream after ungetc does not work as expected
+ on some platforms. Therefore this situation is not supported here. */
+ if (fflush (stream))
+ result = -EIO;
+ else
+ {
+ off_t nbytes = st.st_size - off;
+ if (sendfile (ofd, fd, &off, nbytes) == nbytes)
+ {
+ if (read (ofd, resblock, hashlen) == hashlen)
+ {
+ /* The input buffers of stream are no longer valid. */
+ if (lseek (fd, off, SEEK_SET) != (off_t)-1)
+ result = 0;
+ else
+ /* The file position of fd has not changed. */
+ result = -EAFNOSUPPORT;
+ }
+ else
+ /* The file position of fd has not changed. */
+ result = -EAFNOSUPPORT;
+ }
+ else
+ /* The file position of fd has not changed. */
+ result = -EAFNOSUPPORT;
+ }
+ }
+ else
+ {
+ /* sendfile not possible, do a classic read-write loop. */
+
+ /* Number of bytes to seek (backwards) in case of error. */
+ off_t nseek = 0;
+
+ for (;;)
+ {
+ char buf[BLOCKSIZE];
+ /* When the stream is not seekable, start with a single-byte block,
+ so that we can use ungetc() in the case that send() fails. */
+ size_t blocksize = (nseek == 0 && off < 0 ? 1 : BLOCKSIZE);
+ ssize_t size = fread (buf, 1, blocksize, stream);
+ if (size == 0)
+ {
+ /* On Linux < 4.9, the value for an empty stream is wrong (all 0).
+ See <https://patchwork.kernel.org/patch/9308641/>.
+ This was not fixed properly until November 2016,
+ see <https://patchwork.kernel.org/patch/9434741/>. */
+ result = ferror (stream) ? -EIO : nseek == 0 ? -EAFNOSUPPORT : 0;
+ break;
+ }
+ nseek -= size;
+ if (send (ofd, buf, size, MSG_MORE) != size)
+ {
+ if (nseek == -1)
+ {
+ /* 1 byte of pushback buffer is guaranteed on stream, even
+ if stream is not seekable. */
+ ungetc ((unsigned char) buf[0], stream);
result = -EAFNOSUPPORT;
- }
- else
- /* The file position of fd has not changed. */
- result = -EAFNOSUPPORT;
- }
- else
- /* The file position of fd has not changed. */
- result = -EAFNOSUPPORT;
- }
- }
- else
- {
- /* sendfile not possible, do a classic read-write loop. */
-
- /* Number of bytes to seek (backwards) in case of error. */
- off_t nseek = 0;
-
- for (;;)
- {
- char buf[BLOCKSIZE];
- /* When the stream is not seekable, start with a single-byte block,
- so that we can use ungetc() in the case that send() fails. */
- size_t blocksize = (nseek == 0 && off < 0 ? 1 : BLOCKSIZE);
- ssize_t size = fread (buf, 1, blocksize, stream);
- if (size == 0)
- {
- /* On Linux < 4.9, the value for an empty stream is wrong (all 0).
- See <https://patchwork.kernel.org/patch/9308641/>.
- This was not fixed properly until November 2016,
- see <https://patchwork.kernel.org/patch/9434741/>. */
- result = ferror (stream) ? -EIO : nseek == 0 ? -EAFNOSUPPORT : 0;
- break;
- }
- nseek -= size;
- if (send (ofd, buf, size, MSG_MORE) != size)
- {
- if (nseek == -1)
- {
- /* 1 byte of pushback buffer is guaranteed on stream, even
- if stream is not seekable. */
- ungetc ((unsigned char) buf[0], stream);
+ }
+ else if (fseeko (stream, nseek, SEEK_CUR) == 0)
+ /* The position of stream has been restored. */
result = -EAFNOSUPPORT;
- }
- else if (fseeko (stream, nseek, SEEK_CUR) == 0)
- /* The position of stream has been restored. */
- result = -EAFNOSUPPORT;
- else
- result = -EIO;
- break;
- }
-
- /* Don't assume that EOF is sticky. See:
- <https://sourceware.org/PR19476>. */
- if (feof (stream))
- {
- result = 0;
- break;
- }
- }
-
- if (result == 0 && read (ofd, resblock, hashlen) != hashlen)
- {
- if (nseek == 0 || fseeko (stream, nseek, SEEK_CUR) == 0)
- /* The position of stream has been restored. */
- result = -EAFNOSUPPORT;
- else
- result = -EIO;
- }
- }
+ else
+ result = -EIO;
+ break;
+ }
+
+ /* Don't assume that EOF is sticky. See:
+ <https://sourceware.org/PR19476>. */
+ if (feof (stream))
+ {
+ result = 0;
+ break;
+ }
+ }
+
+ if (result == 0 && read (ofd, resblock, hashlen) != hashlen)
+ {
+ if (nseek == 0 || fseeko (stream, nseek, SEEK_CUR) == 0)
+ /* The position of stream has been restored. */
+ result = -EAFNOSUPPORT;
+ else
+ result = -EIO;
+ }
+ }
+ }
close (ofd);
return result;
}
# if ALIGNALLOC_VIA_ALIGNED_ALLOC
return aligned_alloc (alignment, size);
# else
- void *ptr = NULL;
if (alignment < sizeof (void *))
alignment = sizeof (void *);
+ void *ptr = NULL;
/* Work around posix_memalign glitch by treating a 0 size as if it were 1,
so that returning NULL is equivalent to failing. */
errno = posix_memalign (&ptr, alignment, size ? size : 1);
static int
find_stack_direction (int *addr, int depth)
{
- int dir, dummy = 0;
+ int dummy = 0;
if (! addr)
addr = &dummy;
*addr = addr < &dummy ? 1 : addr == &dummy ? 0 : -1;
- dir = depth ? find_stack_direction (addr, depth - 1) : 0;
+ int dir = depth ? find_stack_direction (addr, depth - 1) : 0;
return dir + dummy;
}
/* Allocate combined header + user data storage. */
{
- /* Address of header. */
- register header *new;
-
size_t combined_size = sizeof (header) + size;
if (combined_size < sizeof (header))
memory_full ();
- new = malloc (combined_size);
+ register header *new = malloc (combined_size);
if (! new)
memory_full ();
{
/* Result accumulator. */
char *result;
- size_t length;
size_t allocated;
-
- char orig_sentinel;
-
- /* Initial memory allocation. */
if (resultbuf != NULL && *lengthp > 0)
{
result = resultbuf;
if (result == NULL)
goto out_of_memory_2;
}
- length = 0;
+ size_t length = 0;
/* Add sentinel.byte. */
- orig_sentinel = s[n];
+ char orig_sentinel = s[n];
s[n] = '\0';
/* Iterate through S, transforming each NUL terminated segment.
const char *p_end = s + n + 1;
const char *p;
- p = s;
- for (;;)
+ for (p = s;;)
{
/* Search next NUL byte. */
size_t l = strlen (p);
for (;;)
{
- size_t k;
-
/* A call to strxfrm costs about 20 times more than a call to
strdup of the result. Therefore it is worth to try to avoid
calling strxfrm more than once on a given string, by making
if (3 * l >= allocated - length)
{
/* Grow the result buffer. */
- size_t new_allocated;
- char *new_result;
-
- new_allocated = length + 3 * l + 1;
+ size_t new_allocated = length + 3 * l + 1;
if (new_allocated < 2 * allocated)
new_allocated = 2 * allocated;
if (new_allocated < 64)
new_allocated = 64;
+
+ char *new_result;
if (result == resultbuf)
new_result = (char *) malloc (new_allocated);
else
}
errno = 0;
- k = strxfrm (result + length, p, allocated - length);
+ size_t k = strxfrm (result + length, p, allocated - length);
if (errno != 0)
goto fail;
if (k >= allocated - length)
{
/* Grow the result buffer. */
- size_t new_allocated;
- char *new_result;
-
- new_allocated = length + k + 1;
+ size_t new_allocated = length + k + 1;
if (new_allocated < 2 * allocated)
new_allocated = 2 * allocated;
if (new_allocated < 64)
new_allocated = 64;
+
+ char *new_result;
if (result == resultbuf)
new_result = (char *) malloc (new_allocated);
else
for (; length > 0; length--)
{
- char t;
-
i++;
j += sbox[i];
- t = sbox[i];
- sbox[i] = sbox[j];
- sbox[j] = t;
+ {
+ char t = sbox[i];
+ sbox[i] = sbox[j];
+ sbox[j] = t;
+ }
*outbuf++ = (*inbuf++
^ sbox[(0U + sbox[i] + sbox[j]) % ARCFOUR_SBOX_SIZE]);
}
size_t i, j, k;
for (i = j = k = 0; i < ARCFOUR_SBOX_SIZE; i++)
{
- char t;
j = (j + sbox[i] + key[k]) % ARCFOUR_SBOX_SIZE;
- t = sbox[i];
- sbox[i] = sbox[j];
- sbox[j] = t;
+ {
+ char t = sbox[i];
+ sbox[i] = sbox[j];
+ sbox[j] = t;
+ }
if (++k == keylen)
k = 0;
}
for (; length >= ARCTWO_BLOCK_SIZE; length -= ARCTWO_BLOCK_SIZE,
inbuf += ARCTWO_BLOCK_SIZE, outbuf += ARCTWO_BLOCK_SIZE)
{
- size_t j;
uint16_t word0 = 0, word1 = 0, word2 = 0, word3 = 0;
word0 = (word0 << 8) | to_uchar (inbuf[1]);
for (size_t i = 0; i < 16; i++)
{
- j = i * 4;
+ size_t j = i * 4;
/* For some reason I cannot combine those steps. */
word0 += (word1 & ~word3) + (word2 & word3) + context->S[j];
word0 = rotl16 (word0, 1);
for (; length >= ARCTWO_BLOCK_SIZE; length -= ARCTWO_BLOCK_SIZE,
inbuf += ARCTWO_BLOCK_SIZE, outbuf += ARCTWO_BLOCK_SIZE)
{
- size_t j;
uint16_t word0 = 0, word1 = 0, word2 = 0, word3 = 0;
word0 = (word0 << 8) | to_uchar (inbuf[1]);
for (size_t i = 16; i > 0; i--)
{
- j = (i - 1) * 4;
+ size_t j = (i - 1) * 4;
word3 = rotr16 (word3, 5);
word3 -= (word0 & ~word2) + (word1 & word2) + context->S[j + 3];
{
word3 = word3 - context->S[word2 & 63];
word2 = word2 - context->S[word1 & 63];
- word1 = word1 - context->S[word0 & 63];
- word0 = word0 - context->S[word3 & 63];
+ word1 = word1 - context->S[word0 & 63];
+ word0 = word0 - context->S[word3 & 63];
}
}
arctwo_setkey_ekb (arctwo_context *context,
size_t keylen, const char *key, size_t effective_keylen)
{
- uint8_t *S, x;
-
if (keylen < 40 / 8 || effective_keylen > 1024)
return;
- S = (uint8_t *) context->S;
+ uint8_t *S = (uint8_t *) context->S;
for (size_t i = 0; i < keylen; i++)
S[i] = (uint8_t) key[i];
{
size_t len = (effective_keylen + 7) >> 3;
size_t i = 128 - len;
- x = arctwo_sbox[S[i] & (255 >> (7 & -effective_keylen))];
+ uint8_t x = arctwo_sbox[S[i] & (255 >> (7 & -effective_keylen))];
S[i] = x;
while (i--)
while (1)
{
- ssize_t r;
- size_t link_length;
char stackbuf[stackbuf_size];
char *buf = stackbuf;
char *buffer = NULL;
}
}
- r = readlink (file, buf, buf_size);
- link_length = r;
-
+ ssize_t r = readlink (file, buf, buf_size);
if (r < 0)
{
free (buffer);
return NULL;
}
+ size_t link_length = r;
if (link_length < buf_size)
{
buf[link_length] = 0;
while (1)
{
- ssize_t r;
- size_t link_length;
char stackbuf[stackbuf_size];
char *buf = stackbuf;
char *buffer = NULL;
return NULL;
}
- r = readlinkat (fd, file, buf, buf_size);
- link_length = r;
-
+ ssize_t r = readlinkat (fd, file, buf, buf_size);
if (r < 0)
{
free (buffer);
return NULL;
}
+ size_t link_length = r;
if (link_length < buf_size)
{
buf[link_length] = 0;
argmatch (const char *arg, const char *const *arglist,
const void *vallist, size_t valsize)
{
- size_t arglen; /* Length of ARG. */
+ size_t arglen = strlen (arg); /* Length of ARG. */
+
ptrdiff_t matchind = -1; /* Index of first nonexact match. */
bool ambiguous = false; /* If true, multiple nonexact match(es). */
- arglen = strlen (arg);
-
/* Test all elements for either exact match or abbreviated matches. */
for (size_t i = 0; arglist[i]; i++)
{
bool allow_abbreviation)
{
ptrdiff_t res;
-
if (allow_abbreviation)
res = argmatch (arg, arglist, vallist, valsize);
else
int
main (int argc, const char *const *argv)
{
- const char *cp;
- enum backup_type backup_type = no_backups;
-
if (argc > 2)
{
fprintf (stderr, "Usage: %s [VERSION_CONTROL]\n", getprogname ());
exit (1);
}
- if ((cp = getenv ("VERSION_CONTROL")))
- backup_type = XARGMATCH ("$VERSION_CONTROL", cp,
- backup_args, backup_vals);
+ enum backup_type backup_type = no_backups;
+
+ {
+ const char *cp;
+ if ((cp = getenv ("VERSION_CONTROL")))
+ backup_type = XARGMATCH ("$VERSION_CONTROL", cp,
+ backup_args, backup_vals);
+ }
if (argc == 2)
backup_type = XARGMATCH (getprogname (), argv[1],
__argp_make_fmtstream (FILE *stream,
size_t lmargin, size_t rmargin, ssize_t wmargin)
{
- argp_fmtstream_t fs;
-
- fs = (struct argp_fmtstream *) malloc (sizeof (struct argp_fmtstream));
+ argp_fmtstream_t fs =
+ (struct argp_fmtstream *) malloc (sizeof (struct argp_fmtstream));
if (fs != NULL)
{
fs->stream = stream;
void
__argp_fmtstream_update (argp_fmtstream_t fs)
{
- char *buf, *nl;
- size_t len;
+ char *buf;
/* Scan the buffer for newlines. */
buf = fs->buf + fs->point_offs;
fs->point_col = pad;
}
- len = fs->p - buf;
- nl = memchr (buf, '\n', len);
+ size_t len = fs->p - buf;
+ char *nl = memchr (buf, '\n', len);
if (fs->point_col < 0)
fs->point_col = 0;
{
if ((size_t) (fs->end - fs->p) < amount)
{
- ssize_t wrote;
-
/* Flush FS's buffer. */
__argp_fmtstream_update (fs);
+ ssize_t wrote;
#ifdef _LIBC
__fxprintf (fs->stream, "%.*s", (int) (fs->p - fs->buf), fs->buf);
wrote = fs->p - fs->buf;
do
{
- va_list args;
-
if (! __argp_fmtstream_ensure (fs, size_guess))
return -1;
+ va_list args;
va_start (args, fmt);
avail = fs->end - fs->p;
out = __vsnprintf (fs->p, avail, fmt, args);
ARGP_FS_EI size_t
__argp_fmtstream_set_lmargin (argp_fmtstream_t __fs, size_t __lmargin)
{
- size_t __old;
if ((size_t) (__fs->p - __fs->buf) > __fs->point_offs)
__argp_fmtstream_update (__fs);
- __old = __fs->lmargin;
+ size_t __old = __fs->lmargin;
__fs->lmargin = __lmargin;
return __old;
}
ARGP_FS_EI size_t
__argp_fmtstream_set_rmargin (argp_fmtstream_t __fs, size_t __rmargin)
{
- size_t __old;
if ((size_t) (__fs->p - __fs->buf) > __fs->point_offs)
__argp_fmtstream_update (__fs);
- __old = __fs->rmargin;
+ size_t __old = __fs->rmargin;
__fs->rmargin = __rmargin;
return __old;
}
ARGP_FS_EI size_t
__argp_fmtstream_set_wmargin (argp_fmtstream_t __fs, size_t __wmargin)
{
- size_t __old;
if ((size_t) (__fs->p - __fs->buf) > __fs->point_offs)
__argp_fmtstream_update (__fs);
- __old = __fs->wmargin;
+ size_t __old = __fs->wmargin;
__fs->wmargin = __wmargin;
return __old;
}
static void
validate_uparams (const struct argp_state *state, struct uparams *upptr)
{
- const struct uparam_name *up;
-
- for (up = uparam_names; up < uparam_names + nuparam_names; up++)
+ for (const struct uparam_name *up = uparam_names;
+ up < uparam_names + nuparam_names;
+ up++)
{
if (!(up->is_bool
|| up->uparams_offs == offsetof (struct uparams, rmargin)))
if (isalpha ((unsigned char) *var))
{
- size_t var_len;
- const struct uparam_name *un;
- int unspec = 0, val = 0;
const char *arg = var;
while (isalnum ((unsigned char) *arg) || *arg == '-' || *arg == '_')
arg++;
- var_len = arg - var;
+ size_t var_len = arg - var;
SKIPWS (arg);
+ int unspec = 0;
if (*arg == '\0' || *arg == ',')
unspec = 1;
else if (*arg == '=')
SKIPWS (arg);
}
+ int val = 0;
if (unspec)
{
if (var[0] == 'n' && var[1] == 'o' && var[2] == '-')
SKIPWS (arg);
}
+ const struct uparam_name *un;
for (un = uparam_names;
un < uparam_names + nuparam_names;
un++)
static struct hol *
make_hol (const struct argp *argp, struct hol_cluster *cluster)
{
- char *so;
- const struct argp_option *o;
- const struct argp_option *opts = argp->options;
- struct hol_entry *entry;
- unsigned num_short_options = 0;
struct hol *hol = malloc (sizeof (struct hol));
-
assert (hol);
-
hol->num_entries = 0;
hol->clusters = NULL;
+ const struct argp_option *opts = argp->options;
if (opts)
{
int cur_group = 0;
assert (! oalias (opts));
/* Calculate the space needed. */
- for (o = opts; ! oend (o); o++)
+ unsigned num_short_options = 0;
+ for (const struct argp_option *o = opts; ! oend (o); o++)
{
if (! oalias (o))
hol->num_entries++;
assert (hol->num_entries <= SIZE_MAX / sizeof (struct hol_entry));
/* Fill in the entries. */
- so = hol->short_options;
+ char *so = hol->short_options;
+ const struct argp_option *o;
+ struct hol_entry *entry;
for (o = opts, entry = hol->entries; ! oend (o); entry++)
{
entry->opt = o;
hol_free (struct hol *hol)
{
struct hol_cluster *cl = hol->clusters;
-
while (cl)
{
struct hol_cluster *next = cl->next;
const char *domain, void *cookie),
const char *domain, void *cookie)
{
- unsigned nopts;
- int val = 0;
- const struct argp_option *opt, *real = entry->opt;
+ const struct argp_option *real = entry->opt;
char *so = entry->short_options;
+ int val = 0;
+ const struct argp_option *opt;
+ unsigned nopts;
for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
if (oshort (opt) && *so == opt->key)
{
const char *domain, void *cookie),
const char *domain, void *cookie)
{
- unsigned nopts;
- int val = 0;
- const struct argp_option *opt, *real = entry->opt;
+ const struct argp_option *real = entry->opt;
+ int val = 0;
+ const struct argp_option *opt;
+ unsigned nopts;
for (opt = real, nopts = entry->num; nopts > 0 && !val; opt++, nopts--)
if (opt->name)
{
hol_entry_first_long (const struct hol_entry *entry)
{
const struct argp_option *opt;
- unsigned num;
- for (opt = entry->opt, num = entry->num; num > 0; opt++, num--)
+ unsigned nopts;
+ for (opt = entry->opt, nopts = entry->num; nopts > 0; opt++, nopts--)
if (opt->name && ovisible (opt))
return opt->name;
return NULL;
static int
canon_doc_option (const char **name)
{
- int non_opt;
/* Skip initial whitespace. */
while (isspace ((unsigned char) **name))
(*name)++;
/* Decide whether this looks like an option (leading '-') or not. */
- non_opt = (**name != '-');
+ int non_opt = (**name != '-');
/* Skip until part of name used for sorting. */
while (**name && !isalnum ((unsigned char) **name))
(*name)++;
more->num_entries = 0; /* Mark MORE's fields as invalid. */
}
else
- /* Append the entries in MORE to those in HOL, taking care to only add
- non-shadowed SHORT_OPTIONS values. */
{
- unsigned left;
- char *so, *more_so;
- struct hol_entry *e;
+ /* Append the entries in MORE to those in HOL, taking care to only add
+ non-shadowed SHORT_OPTIONS values. */
unsigned num_entries = hol->num_entries + more->num_entries;
struct hol_entry *entries =
malloc (num_entries * sizeof (struct hol_entry));
+
unsigned hol_so_len = strlen (hol->short_options);
char *short_options =
malloc (hol_so_len + strlen (more->short_options) + 1);
__mempcpy (short_options, hol->short_options, hol_so_len);
/* Fix up the short options pointers from HOL. */
+ struct hol_entry *e;
+ unsigned left;
for (e = entries, left = hol->num_entries; left > 0; e++, left--)
e->short_options
= short_options + (e->short_options - hol->short_options);
/* Now add the short options from MORE, fixing up its entries
too. */
- so = short_options + hol_so_len;
- more_so = more->short_options;
+ char *so = short_options + hol_so_len;
+ char *more_so = more->short_options;
for (left = more->num_entries; left > 0; e++, left--)
{
- int opts_left;
- const struct argp_option *opt;
-
e->short_options = so;
+ int opts_left;
+ const struct argp_option *opt;
for (opts_left = e->num, opt = e->opt; opts_left; opt++, opts_left--)
{
int ch = *more_so;
static struct hol *
argp_hol (const struct argp *argp, struct hol_cluster *cluster)
{
- const struct argp_child *child = argp->children;
struct hol *hol = make_hol (argp, cluster);
+
+ const struct argp_child *child = argp->children;
if (child)
while (child->argp)
{
hol_entry_help (struct hol_entry *entry, const struct argp_state *state,
argp_fmtstream_t stream, struct hol_help_state *hhstate)
{
- unsigned num;
- const struct argp_option *real = entry->opt, *opt;
- char *so = entry->short_options;
- int have_long_opt = 0; /* We have any long options. */
/* Saved margins. */
int old_lm = __argp_fmtstream_set_lmargin (stream, 0);
int old_wm = __argp_fmtstream_wmargin (stream);
+
/* PEST is a state block holding some of our variables that we'd like to
share with helper functions. */
struct pentry_state pest = { entry, stream, hhstate, 1, state };
+ const struct argp_option *real = entry->opt;
+
+ int have_long_opt = 0; /* We have any long options. */
if (! odoc (real))
+ {
+ const struct argp_option *opt;
+ unsigned num;
+ for (opt = real, num = entry->num; num > 0; opt++, num--)
+ if (opt->name && ovisible (opt))
+ {
+ have_long_opt = 1;
+ break;
+ }
+ }
+
+ /* First emit short options. */
+ {
+ __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
+ char *so = entry->short_options;
+
+ const struct argp_option *opt;
+ unsigned num;
for (opt = real, num = entry->num; num > 0; opt++, num--)
- if (opt->name && ovisible (opt))
+ if (oshort (opt) && opt->key == *so)
+ /* OPT has a valid (non shadowed) short option. */
{
- have_long_opt = 1;
- break;
+ if (ovisible (opt))
+ {
+ comma (uparams.short_opt_col, &pest);
+ __argp_fmtstream_putc (stream, '-');
+ __argp_fmtstream_putc (stream, *so);
+ if (!have_long_opt || uparams.dup_args)
+ arg (real, " %s", "[%s]",
+ state == NULL ? NULL : state->root_argp->argp_domain,
+ stream);
+ else if (real->arg)
+ hhstate->suppressed_dup_arg = 1;
+ }
+ so++;
}
-
- /* First emit short options. */
- __argp_fmtstream_set_wmargin (stream, uparams.short_opt_col); /* For truly bizarre cases. */
- for (opt = real, num = entry->num; num > 0; opt++, num--)
- if (oshort (opt) && opt->key == *so)
- /* OPT has a valid (non shadowed) short option. */
- {
- if (ovisible (opt))
- {
- comma (uparams.short_opt_col, &pest);
- __argp_fmtstream_putc (stream, '-');
- __argp_fmtstream_putc (stream, *so);
- if (!have_long_opt || uparams.dup_args)
- arg (real, " %s", "[%s]",
- state == NULL ? NULL : state->root_argp->argp_domain,
- stream);
- else if (real->arg)
- hhstate->suppressed_dup_arg = 1;
- }
- so++;
- }
+ }
/* Now, long options. */
if (odoc (real))
/* A "documentation" option. */
{
__argp_fmtstream_set_wmargin (stream, uparams.doc_opt_col);
+
+ const struct argp_option *opt;
+ unsigned num;
for (opt = real, num = entry->num; num > 0; opt++, num--)
if (opt->name && ovisible (opt))
{
/* A real long option. */
{
__argp_fmtstream_set_wmargin (stream, uparams.long_opt_col);
+
+ const struct argp_option *opt;
+ unsigned num;
for (opt = real, num = entry->num; num > 0; opt++, num--)
if (opt->name && ovisible (opt))
{
hol_help (struct hol *hol, const struct argp_state *state,
argp_fmtstream_t stream)
{
- unsigned num;
- struct hol_entry *entry;
struct hol_help_state hhstate = { NULL, 0, 0 };
- for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
- hol_entry_help (entry, state, stream, &hhstate);
+ {
+ struct hol_entry *entry;
+ unsigned num;
+ for (entry = hol->entries, num = hol->num_entries; num > 0; entry++, num--)
+ hol_entry_help (entry, state, stream, &hhstate);
+ }
if (hhstate.suppressed_dup_arg && uparams.dup_args_note)
{
const char *domain, void *cookie)
{
argp_fmtstream_t stream = cookie;
- const char *arg = opt->arg;
- int flags = opt->flags | real->flags;
+ const char *arg = opt->arg;
if (! arg)
arg = real->arg;
- if (arg && !(flags & OPTION_NO_USAGE))
+ if (arg)
{
- arg = dgettext (domain, arg);
-
- if (flags & OPTION_ARG_OPTIONAL)
- __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
- else
+ int flags = opt->flags | real->flags;
+ if (!(flags & OPTION_NO_USAGE))
{
- /* Manually do line wrapping so that it (probably) won't
- get wrapped at the embedded space. */
- space (stream, 6 + strlen (arg));
- __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
+ arg = dgettext (domain, arg);
+
+ if (flags & OPTION_ARG_OPTIONAL)
+ __argp_fmtstream_printf (stream, " [-%c[%s]]", opt->key, arg);
+ else
+ {
+ /* Manually do line wrapping so that it (probably) won't
+ get wrapped at the embedded space. */
+ space (stream, 6 + strlen (arg));
+ __argp_fmtstream_printf (stream, "[-%c %s]", opt->key, arg);
+ }
}
}
const char *domain, void *cookie)
{
argp_fmtstream_t stream = cookie;
- const char *arg = opt->arg;
- int flags = opt->flags | real->flags;
+ const char *arg = opt->arg;
if (! arg)
arg = real->arg;
+ int flags = opt->flags | real->flags;
if (! (flags & OPTION_NO_USAGE))
{
if (arg)
{
if (hol->num_entries > 0)
{
- unsigned nentries;
- struct hol_entry *entry;
char *short_no_arg_opts = alloca (strlen (hol->short_options) + 1);
char *snao_end = short_no_arg_opts;
/* First we put a list of short options without arguments. */
- for (entry = hol->entries, nentries = hol->num_entries
- ; nentries > 0
- ; entry++, nentries--)
- hol_entry_short_iterate (entry, add_argless_short_opt,
- entry->argp->argp_domain, &snao_end);
+ {
+ struct hol_entry *entry;
+ unsigned nentries;
+ for (entry = hol->entries, nentries = hol->num_entries
+ ; nentries > 0
+ ; entry++, nentries--)
+ hol_entry_short_iterate (entry, add_argless_short_opt,
+ entry->argp->argp_domain, &snao_end);
+ }
if (snao_end > short_no_arg_opts)
{
*snao_end++ = '\0';
}
/* Now a list of short options *with* arguments. */
- for (entry = hol->entries, nentries = hol->num_entries
- ; nentries > 0
- ; entry++, nentries--)
- hol_entry_short_iterate (entry, usage_argful_short_opt,
- entry->argp->argp_domain, stream);
+ {
+ struct hol_entry *entry;
+ unsigned nentries;
+ for (entry = hol->entries, nentries = hol->num_entries
+ ; nentries > 0
+ ; entry++, nentries--)
+ hol_entry_short_iterate (entry, usage_argful_short_opt,
+ entry->argp->argp_domain, stream);
+ }
/* Finally, a list of long options (whew!). */
- for (entry = hol->entries, nentries = hol->num_entries
- ; nentries > 0
- ; entry++, nentries--)
- hol_entry_long_iterate (entry, usage_long_opt,
- entry->argp->argp_domain, stream);
+ {
+ struct hol_entry *entry;
+ unsigned nentries;
+ for (entry = hol->entries, nentries = hol->num_entries
+ ; nentries > 0
+ ; entry++, nentries--)
+ hol_entry_long_iterate (entry, usage_long_opt,
+ entry->argp->argp_domain, stream);
+ }
}
}
\f
argp_args_levels (const struct argp *argp)
{
size_t levels = 0;
- const struct argp_child *child = argp->children;
if (argp->args_doc && strchr (argp->args_doc, '\n'))
levels++;
+ const struct argp_child *child = argp->children;
if (child)
while (child->argp)
levels += argp_args_levels ((child++)->argp);
{
char *our_level = *levels;
int multiple = 0;
- const struct argp_child *child = argp->children;
- const char *tdoc =
- argp->args_doc ? dgettext (argp->argp_domain, argp->args_doc) : NULL;
- const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
const char *nl = NULL;
- if (fdoc)
- {
- const char *cp = fdoc;
- nl = __strchrnul (cp, '\n');
- if (*nl != '\0')
- /* This is a 'multi-level' args doc; advance to the correct position
- as determined by our state in LEVELS, and update LEVELS. */
- {
- int i;
- multiple = 1;
- for (i = 0; i < *our_level; i++)
- cp = nl + 1, nl = __strchrnul (cp, '\n');
- (*levels)++;
- }
+ {
+ const char *tdoc =
+ argp->args_doc ? dgettext (argp->argp_domain, argp->args_doc) : NULL;
+ const char *fdoc = filter_doc (tdoc, ARGP_KEY_HELP_ARGS_DOC, argp, state);
- /* Manually do line wrapping so that it (probably) won't get wrapped at
- any embedded spaces. */
- space (stream, 1 + nl - cp);
+ if (fdoc)
+ {
+ const char *cp = fdoc;
+ nl = __strchrnul (cp, '\n');
+ if (*nl != '\0')
+ /* This is a 'multi-level' args doc; advance to the correct position
+ as determined by our state in LEVELS, and update LEVELS. */
+ {
+ multiple = 1;
+ for (int i = 0; i < *our_level; i++)
+ cp = nl + 1, nl = __strchrnul (cp, '\n');
+ (*levels)++;
+ }
- __argp_fmtstream_write (stream, cp, nl - cp);
- }
- if (fdoc && fdoc != tdoc)
- free ((char *)fdoc); /* Free user's modified doc string. */
+ /* Manually do line wrapping so that it (probably) won't get wrapped at
+ any embedded spaces. */
+ space (stream, 1 + nl - cp);
- if (child)
- while (child->argp)
- advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
+ __argp_fmtstream_write (stream, cp, nl - cp);
+ }
+ if (fdoc && fdoc != tdoc)
+ free ((char *)fdoc); /* Free user's modified doc string. */
+ }
+
+ {
+ const struct argp_child *child = argp->children;
+ if (child)
+ while (child->argp)
+ advance = !argp_args_usage ((child++)->argp, state, levels, advance, stream);
+ }
if (advance && multiple)
{
int post, int pre_blank, int first_only,
argp_fmtstream_t stream)
{
- const char *text;
const char *inp_text;
- void *input = NULL;
- int anything = 0;
size_t inp_text_limit = 0;
- const char *doc = argp->doc ? dgettext (argp->argp_domain, argp->doc) : NULL;
- const struct argp_child *child = argp->children;
- if (doc)
- {
- char const *vt = strchr (doc, '\v');
- inp_text = post ? (vt ? vt + 1 : NULL) : doc;
- inp_text_limit = (!post && vt) ? (vt - doc) : 0;
- }
- else
- inp_text = NULL;
+ {
+ const char *doc = argp->doc ? dgettext (argp->argp_domain, argp->doc) : NULL;
+ if (doc)
+ {
+ char const *vt = strchr (doc, '\v');
+ inp_text = post ? (vt ? vt + 1 : NULL) : doc;
+ inp_text_limit = (!post && vt) ? (vt - doc) : 0;
+ }
+ else
+ inp_text = NULL;
+ }
+ const char *text;
+ void *input = NULL;
if (argp->help_filter)
/* We have to filter the doc strings. */
{
else
text = (const char *) inp_text;
+ int anything = 0;
if (text)
{
if (pre_blank)
}
}
- if (child)
- while (child->argp && !(first_only && anything))
- anything |=
- argp_doc ((child++)->argp, state,
- post, anything || pre_blank, first_only,
- stream);
+ {
+ const struct argp_child *child = argp->children;
+ if (child)
+ while (child->argp && !(first_only && anything))
+ anything |=
+ argp_doc ((child++)->argp, state,
+ post, anything || pre_blank, first_only,
+ stream);
+ }
return anything;
}
_help (const struct argp *argp, const struct argp_state *state, FILE *stream,
unsigned flags, char *name)
{
- int anything = 0; /* Whether we've output anything. */
- struct hol *hol = NULL;
- argp_fmtstream_t fs;
-
if (! stream)
return;
if (! uparams.valid)
fill_in_uparams (state);
- fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
+ argp_fmtstream_t fs = __argp_make_fmtstream (stream, 0, uparams.rmargin, 0);
if (! fs)
{
#if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
return;
}
+ struct hol *hol = NULL;
if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG))
{
hol = argp_hol (argp, NULL);
hol_sort (hol);
}
+ int anything = 0; /* Whether we've output anything. */
if (flags & (ARGP_HELP_USAGE | ARGP_HELP_SHORT_USAGE))
/* Print a short "Usage:" message. */
{
if (stream)
{
- va_list ap;
-
#if _LIBC || (HAVE_FLOCKFILE && HAVE_FUNLOCKFILE)
__flockfile (stream);
#endif
+ va_list ap;
va_start (ap, fmt);
#ifdef _LIBC
if (fmt)
{
va_list ap;
-
va_start (ap, fmt);
+
#ifdef _LIBC
char *buf;
{
if (group->parser)
{
- error_t err;
state->hook = group->hook;
state->input = group->input;
state->child_inputs = group->child_inputs;
state->arg_num = group->args_processed;
- err = (*group->parser)(key, arg, state);
+ error_t err = (*group->parser)(key, arg, state);
group->hook = state->hook;
return err;
}
parser_init (struct parser *parser, const struct argp *argp,
int argc, char **argv, int flags, void *input)
{
- error_t err = 0;
- struct group *group;
struct parser_sizes szs;
- struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
- char *storage;
- size_t glen, gsum;
- size_t clen, csum;
- size_t llen, lsum;
- size_t slen, ssum;
-
szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
szs.long_len = 0;
szs.num_groups = 0;
calc_sizes (argp, &szs);
/* Lengths of the various bits of storage used by PARSER. */
- glen = (szs.num_groups + 1) * sizeof (struct group);
- clen = szs.num_child_inputs * sizeof (void *);
- llen = (szs.long_len + 1) * sizeof (struct option);
- slen = szs.short_len + 1;
+ size_t glen = (szs.num_groups + 1) * sizeof (struct group);
+ size_t clen = szs.num_child_inputs * sizeof (void *);
+ size_t llen = (szs.long_len + 1) * sizeof (struct option);
+ size_t slen = szs.short_len + 1;
/* Sums of previous lengths, properly aligned. There's no need to
align gsum, since struct group is aligned at least as strictly as
void * (since it contains a void * member). And there's no need
to align lsum, since struct option is aligned at least as
strictly as char. */
- gsum = glen;
- csum = alignto (gsum + clen, alignof (struct option));
- lsum = csum + llen;
- ssum = lsum + slen;
+ size_t gsum = glen;
+ size_t csum = alignto (gsum + clen, alignof (struct option));
+ size_t lsum = csum + llen;
+ size_t ssum = lsum + slen;
parser->storage = malloc (ssum);
if (! parser->storage)
return ENOMEM;
- storage = parser->storage;
+ char *storage = parser->storage;
parser->groups = parser->storage;
parser->child_inputs = (void **) (storage + gsum);
parser->long_opts = (struct option *) (storage + csum);
parser->short_opts = storage + lsum;
- parser->opt_data = opt_data;
+ {
+ struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
+ parser->opt_data = opt_data;
+ }
memset (parser->child_inputs, 0, clen);
parser_convert (parser, argp, flags);
values to child parsers. */
if (parser->groups < parser->egroup)
parser->groups->input = input;
- for (group = parser->groups;
- group < parser->egroup && (!err || err == EBADKEY);
- group++)
- {
- if (group->parent)
- /* If a child parser, get the initial input value from the parent. */
- group->input = group->parent->child_inputs[group->parent_index];
-
- if (!group->parser
- && group->argp->children && group->argp->children->argp)
- /* For the special case where no parsing function is supplied for an
- argp, propagate its input to its first child, if any (this just
- makes very simple wrapper argps more convenient). */
- group->child_inputs[0] = group->input;
-
- err = group_parse (group, &parser->state, ARGP_KEY_INIT, NULL);
- }
- if (err == EBADKEY)
- err = 0; /* Some parser didn't understand. */
+ {
+ error_t err = 0;
- if (err)
- return err;
+ for (struct group *group = parser->groups;
+ group < parser->egroup && (!err || err == EBADKEY);
+ group++)
+ {
+ if (group->parent)
+ /* If a child parser, get the initial input value from the parent. */
+ group->input = group->parent->child_inputs[group->parent_index];
+
+ if (!group->parser
+ && group->argp->children && group->argp->children->argp)
+ /* For the special case where no parsing function is supplied for an
+ argp, propagate its input to its first child, if any (this just
+ makes very simple wrapper argps more convenient). */
+ group->child_inputs[0] = group->input;
+
+ err = group_parse (group, &parser->state, ARGP_KEY_INIT, NULL);
+ }
+ if (err == EBADKEY)
+ err = 0; /* Some parser didn't understand. */
+
+ if (err)
+ return err;
+ }
if (parser->state.flags & ARGP_NO_ERRS)
{
parser_finalize (struct parser *parser,
error_t err, int arg_ebadkey, int *end_index)
{
- struct group *group;
-
if (err == EBADKEY && arg_ebadkey)
/* Suppress errors generated by unparsed arguments. */
err = 0;
/* We successfully parsed all arguments! Call all the parsers again,
just a few more times... */
{
- for (group = parser->groups;
+ for (struct group *group = parser->groups;
group < parser->egroup && (!err || err==EBADKEY);
group++)
if (group->args_processed == 0)
err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, NULL);
- for (group = parser->egroup - 1;
+ for (struct group *group = parser->egroup - 1;
group >= parser->groups && (!err || err==EBADKEY);
group--)
err = group_parse (group, &parser->state, ARGP_KEY_END, NULL);
ARGP_HELP_STD_ERR);
/* Since we didn't exit, give each parser an error indication. */
- for (group = parser->groups; group < parser->egroup; group++)
+ for (struct group *group = parser->groups; group < parser->egroup; group++)
group_parse (group, &parser->state, ARGP_KEY_ERROR, NULL);
}
else
/* We pass over the groups in reverse order so that child groups are
given a chance to do there processing before passing back a value to
the parent. */
- for (group = parser->egroup - 1
+ for (struct group *group = parser->egroup - 1
; group >= parser->groups && (!err || err == EBADKEY)
; group--)
err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, NULL);
}
/* Call parsers once more, to do any final cleanup. Errors are ignored. */
- for (group = parser->egroup - 1; group >= parser->groups; group--)
+ for (struct group *group = parser->egroup - 1; group >= parser->groups; group--)
group_parse (group, &parser->state, ARGP_KEY_FINI, NULL);
if (err == EBADKEY)
static error_t
parser_parse_next (struct parser *parser, int *arg_ebadkey)
{
- int opt;
- error_t err;
-
if (parser->state.quoted && parser->state.next < parser->state.quoted)
/* The next argument pointer has been moved to before the quoted
region, so pretend we never saw the quoting "--", and give getopt
process it again. */
parser->state.quoted = 0;
+ int opt;
if (parser->try_getopt && !parser->state.quoted)
/* Give getopt a chance to parse this. */
{
}
}
+ error_t err;
if (opt == KEY_ARG)
/* A non-option argument; try each parser in turn. */
err = parser_parse_arg (parser, parser->opt_data.optarg);
__argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
int *end_index, void *input)
{
- error_t err;
- struct parser parser;
-
- /* If true, then err == EBADKEY is a result of a non-option argument failing
- to be parsed (which in some cases isn't actually an error). */
- int arg_ebadkey = 0;
-
#ifndef _LIBC
if (!(flags & ARGP_PARSE_ARGV0))
{
}
/* Construct a parser for these arguments. */
- err = parser_init (&parser, argp, argc, argv, flags, input);
+ struct parser parser;
+ error_t err = parser_init (&parser, argp, argc, argv, flags, input);
if (! err)
/* Parse! */
{
+ /* If true, then err == EBADKEY is a result of a non-option argument
+ failing to be parsed (which in some cases isn't actually an error). */
+ int arg_ebadkey = 0;
+
while (! err)
err = parser_parse_next (&parser, &arg_ebadkey);
err = parser_finalize (&parser, err, arg_ebadkey, end_index);
{
if (state)
{
- struct group *group;
struct parser *parser = state->pstate;
- for (group = parser->groups; group < parser->egroup; group++)
+ for (struct group *group = parser->groups;
+ group < parser->egroup;
+ group++)
if (group->argp == argp)
return group->input;
}
if (nlen > 1)
{
- const char *rp;
- char *wp;
-
*argz = (char *) realloc (*argz, *argz_len + nlen);
if (*argz == NULL)
return ENOMEM;
- wp = *argz + *argz_len;
- rp = string;
+ char *wp = *argz + *argz_len;
+ const char *rp = string;
do
if (*rp == delim)
{
if (nlen > 1)
{
- const char *rp;
- char *wp;
-
*argz = (char *) malloc (nlen);
if (*argz == NULL)
return ENOMEM;
- rp = string;
- wp = *argz;
+ const char *rp = string;
+ char *wp = *argz;
do
if (*rp == delim)
{
argz_create (char *const argv[], char **argz, size_t *len)
{
size_t tlen = 0;
- char *const *ap;
- char *p;
for (int argc = 0; argv[argc] != NULL; ++argc)
tlen += strlen (argv[argc]) + 1;
if (*argz == NULL)
return ENOMEM;
+ char *p;
+ char *const *ap;
for (p = *argz, ap = argv; *ap; ++ap, ++p)
p = stpcpy (p, *ap);
}
if (str && *str)
{
- char *arg = 0;
char *src = *argz;
size_t src_len = *argz_len;
char *dst = 0;
int delayed_copy = 1; /* True while we've avoided copying anything. */
size_t str_len = strlen (str), with_len = strlen (with);
- while (!err && (arg = argz_next (src, src_len, arg)))
- {
- char *match = strstr (arg, str);
- if (match)
- {
- char *from = match + str_len;
- size_t to_len = match - arg;
- char *to = strndup (arg, to_len);
-
- while (to && from)
- {
- str_append (&to, &to_len, with, with_len);
- if (to)
- {
- match = strstr (from, str);
- if (match)
- {
- str_append (&to, &to_len, from, match - from);
- from = match + str_len;
- }
- else
- {
- str_append (&to, &to_len, from, strlen (from));
- from = 0;
- }
- }
- }
-
- if (to)
- {
- if (delayed_copy)
- /* We avoided copying SRC to DST until we found a match;
- now that we've done so, copy everything from the start
- of SRC. */
- {
- if (arg > src)
- err = argz_append (&dst, &dst_len, src, (arg - src));
- delayed_copy = 0;
- }
- if (! err)
- err = argz_add (&dst, &dst_len, to);
- free (to);
- }
- else
- err = ENOMEM;
-
- if (replace_count)
- (*replace_count)++;
- }
- else if (! delayed_copy)
- err = argz_add (&dst, &dst_len, arg);
- }
+ {
+ char *arg = 0;
+
+ while (!err && (arg = argz_next (src, src_len, arg)))
+ {
+ char *match = strstr (arg, str);
+ if (match)
+ {
+ char *from = match + str_len;
+ size_t to_len = match - arg;
+ char *to = strndup (arg, to_len);
+
+ while (to && from)
+ {
+ str_append (&to, &to_len, with, with_len);
+ if (to)
+ {
+ match = strstr (from, str);
+ if (match)
+ {
+ str_append (&to, &to_len, from, match - from);
+ from = match + str_len;
+ }
+ else
+ {
+ str_append (&to, &to_len, from, strlen (from));
+ from = 0;
+ }
+ }
+ }
+
+ if (to)
+ {
+ if (delayed_copy)
+ /* We avoided copying SRC to DST until we found a match;
+ now that we've done so, copy everything from the start
+ of SRC. */
+ {
+ if (arg > src)
+ err = argz_append (&dst, &dst_len, src, (arg - src));
+ delayed_copy = 0;
+ }
+ if (! err)
+ err = argz_add (&dst, &dst_len, to);
+ free (to);
+ }
+ else
+ err = ENOMEM;
+
+ if (replace_count)
+ (*replace_count)++;
+ }
+ else if (! delayed_copy)
+ err = argz_add (&dst, &dst_len, arg);
+ }
+ }
if (! err)
{
long double
asinl (long double x)
{
- long double y, t, p, q;
- int sign;
-
- sign = 1;
- y = x;
+ int sign = 1;
+ long double y = x;
if (x < 0.0L)
{
sign = -1;
return (x - x) / (x - x); /* asin(|x|>1) is NaN */
}
- else if (y < 0.5L) /* |x| < 0.5 */
+
+ long double t;
+ if (y < 0.5L) /* |x| < 0.5 */
{
if (y < 0.000000000000000006938893903907228377647697925567626953125L) /* |x| < 2**-57 */
if (huge + y > one)
return y; /* return x with inexact if x!=0 */
t = x * x;
- p = (((((((((pS9 * t
- + pS8) * t
- + pS7) * t
- + pS6) * t
- + pS5) * t
- + pS4) * t
- + pS3) * t
- + pS2) * t
- + pS1) * t
- + pS0) * t;
-
- q = (((((((( t
- + qS8) * t
- + qS7) * t
- + qS6) * t
- + qS5) * t
- + qS4) * t
- + qS3) * t
- + qS2) * t
- + qS1) * t
- + qS0;
+ long double p = (((((((((pS9 * t
+ + pS8) * t
+ + pS7) * t
+ + pS6) * t
+ + pS5) * t
+ + pS4) * t
+ + pS3) * t
+ + pS2) * t
+ + pS1) * t
+ + pS0) * t;
+
+ long double q = (((((((( t
+ + qS8) * t
+ + qS7) * t
+ + qS6) * t
+ + qS5) * t
+ + qS4) * t
+ + qS3) * t
+ + qS2) * t
+ + qS1) * t
+ + qS0;
return x + x * (p / q);
}
else if (y < 0.625) /* 0.625 */
{
t = y - 0.5625;
- p = ((((((((((rS10 * t
- + rS9) * t
- + rS8) * t
- + rS7) * t
- + rS6) * t
- + rS5) * t
- + rS4) * t
- + rS3) * t
- + rS2) * t
- + rS1) * t
- + rS0) * t;
-
- q = ((((((((( t
- + sS9) * t
- + sS8) * t
- + sS7) * t
- + sS6) * t
- + sS5) * t
- + sS4) * t
- + sS3) * t
- + sS2) * t
- + sS1) * t
- + sS0;
+ long double p = ((((((((((rS10 * t
+ + rS9) * t
+ + rS8) * t
+ + rS7) * t
+ + rS6) * t
+ + rS5) * t
+ + rS4) * t
+ + rS3) * t
+ + rS2) * t
+ + rS1) * t
+ + rS0) * t;
+
+ long double q = ((((((((( t
+ + sS9) * t
+ + sS8) * t
+ + sS7) * t
+ + sS6) * t
+ + sS5) * t
+ + sS4) * t
+ + sS3) * t
+ + sS2) * t
+ + sS1) * t
+ + sS0;
t = asinr5625 + p / q;
}
else
asnprintf (char *resultbuf, size_t *lengthp, const char *format, ...)
{
va_list args;
- char *result;
-
va_start (args, format);
- result = vasnprintf (resultbuf, lengthp, format, args);
+ char *result = vasnprintf (resultbuf, lengthp, format, args);
va_end (args);
return result;
}
asnwprintf (wchar_t *resultbuf, size_t *lengthp, const wchar_t *format, ...)
{
va_list args;
- wchar_t *result;
-
va_start (args, format);
- result = vasnwprintf (resultbuf, lengthp, format, args);
+ wchar_t *result = vasnwprintf (resultbuf, lengthp, format, args);
va_end (args);
return result;
}
asprintf (char **resultp, const char *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = vasprintf (resultp, format, args);
+ int result = vasprintf (resultp, format, args);
va_end (args);
return result;
}
char *result; /* either == resultbuf or == tmpbuf or freshly allocated
or NULL. */
size_t allocated; /* number of bytes allocated at result */
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
+ size_t length;
{
size_t l = strlen (s);
- size_t k;
/* A call to strxfrm costs about 20 times more than a call to strdup of
the result. Therefore it is worth to try to avoid calling strxfrm
}
else
{
- size_t new_allocated;
- char *new_result;
-
- new_allocated = 3 * l + 1;
+ size_t new_allocated = 3 * l + 1;
if (new_allocated < 2 * allocated)
new_allocated = 2 * allocated;
- new_result = (char *) malloc (new_allocated);
+ char *new_result = (char *) malloc (new_allocated);
if (new_result != NULL)
{
allocated = new_allocated;
}
errno = 0;
- k = strxfrm (result, s, allocated);
+ size_t k = strxfrm (result, s, allocated);
if (errno != 0)
goto fail;
if (k >= allocated)
}
else
{
- size_t new_allocated;
- char *new_result;
-
- new_allocated = k + 1;
- new_result = (char *) malloc (new_allocated);
+ size_t new_allocated = k + 1;
+ char *new_result = (char *) malloc (new_allocated);
if (new_result == NULL)
goto out_of_memory;
allocated = new_allocated;
else
{
char *memory = (char *) malloc (length);
-
if (memory == NULL)
goto out_of_memory;
memcpy (memory, result, length);
aszprintf (char **resultp, const char *format, ...)
{
va_list args;
- ptrdiff_t result;
-
va_start (args, format);
- result = vaszprintf (resultp, format, args);
+ ptrdiff_t result = vaszprintf (resultp, format, args);
va_end (args);
return result;
}
errno = ENOTSUP;
return FUNC_FAIL;
#else
- {
- /* Be careful to choose names unlikely to conflict with
+ /* Be careful to choose variable names unlikely to conflict with
AT_FUNC_POST_FILE_PARAM_DECLS. */
- struct saved_cwd saved_cwd;
- int saved_errno;
- FUNC_RESULT err;
{
char proc_buf[OPENAT_BUFFER_SIZE];
}
}
+ struct saved_cwd saved_cwd;
if (save_cwd (&saved_cwd) != 0)
openat_save_fail (errno);
if (0 <= fd && fd == saved_cwd.desc)
if (fchdir (fd) != 0)
{
- saved_errno = errno;
+ int saved_errno = errno;
free_cwd (&saved_cwd);
errno = saved_errno;
return FUNC_FAIL;
}
- err = CALL_FUNC (file);
- saved_errno = (err == FUNC_FAIL ? errno : 0);
+ FUNC_RESULT err = CALL_FUNC (file);
+ int saved_errno = (err == FUNC_FAIL ? errno : 0);
if (restore_cwd (&saved_cwd) != 0)
openat_restore_fail (errno);
if (saved_errno)
errno = saved_errno;
return err;
- }
#endif
}
#undef CALL_FUNC
int fd2, char const *file2,
int (*func) (char const *file1, char const *file2))
{
- struct saved_cwd saved_cwd;
- int saved_errno;
- int err;
- char *file1_alt;
- char *file2_alt;
- struct stat st1;
- struct stat st2;
-
/* There are 16 possible scenarios, based on whether an fd is
AT_FDCWD or real, and whether a file is absolute or relative:
if (fd1 == AT_FDCWD) /* Cases 3, 7. */
{
+ struct stat st1;
+ struct stat st2;
if (stat (".", &st1) == -1 || fstat (fd2, &st2) == -1)
return -1;
if (!S_ISDIR (st2.st_mode))
}
else if (fd2 == AT_FDCWD) /* Cases 12, 13. */
{
+ struct stat st1;
+ struct stat st2;
if (stat (".", &st2) == -1 || fstat (fd1, &st1) == -1)
return -1;
if (!S_ISDIR (st1.st_mode))
}
else if (fd1 != fd2) /* Case 15b. */
{
+ struct stat st1;
+ struct stat st2;
if (fstat (fd1, &st1) == -1 || fstat (fd2, &st2) == -1)
return -1;
if (!S_ISDIR (st1.st_mode) || !S_ISDIR (st2.st_mode))
}
else /* Case 15a. */
{
+ struct stat st1;
if (fstat (fd1, &st1) == -1)
return -1;
if (!S_ISDIR (st1.st_mode))
errno = ENOTDIR;
return -1;
}
+ struct stat st2;
if (stat (".", &st2) == 0 && psame_inode (&st1, &st2))
return func (file1, file2); /* Reduced to case 5. */
}
/* Cases 3, 7, 12, 13, 15a, 15b remain. With all reductions in
place, it is time to start changing directories. */
+ struct saved_cwd saved_cwd;
if (save_cwd (&saved_cwd) != 0)
openat_save_fail (errno);
{
if (fchdir (fd1) != 0)
{
- saved_errno = errno;
+ int saved_errno = errno;
free_cwd (&saved_cwd);
errno = saved_errno;
return -1;
/* Cases 3, 7, 12, 13, 15a remain. Convert one relative name to
absolute, if necessary. */
- file1_alt = (char *) file1;
- file2_alt = (char *) file2;
+ char *file1_alt = (char *) file1;
+ char *file2_alt = (char *) file2;
if (fd1 == AT_FDCWD && !IS_ABSOLUTE_FILE_NAME (file1)) /* Case 7. */
{
char *cwd = getcwd (NULL, 0);
if (!cwd)
{
- saved_errno = errno;
+ int saved_errno = errno;
free_cwd (&saved_cwd);
errno = saved_errno;
return -1;
file1_alt = mfile_name_concat (cwd, file1, NULL);
if (!file1_alt)
{
- saved_errno = errno;
+ int saved_errno = errno;
free (cwd);
free_cwd (&saved_cwd);
errno = saved_errno;
char *cwd = getcwd (NULL, 0);
if (!cwd)
{
- saved_errno = errno;
+ int saved_errno = errno;
free_cwd (&saved_cwd);
errno = saved_errno;
return -1;
file2_alt = mfile_name_concat (cwd, file2, NULL);
if (!file2_alt)
{
- saved_errno = errno;
+ int saved_errno = errno;
free (cwd);
free_cwd (&saved_cwd);
errno = saved_errno;
/* Cases 3, 12, 15a remain. Change to the correct directory. */
if (fchdir (fd1 == AT_FDCWD ? fd2 : fd1) != 0)
{
- saved_errno = errno;
+ int saved_errno = errno;
free_cwd (&saved_cwd);
if (file1 != file1_alt)
free (file1_alt);
/* Finally safe to perform the user's function, then clean up. */
- err = func (file1_alt, file2_alt);
- saved_errno = (err < 0 ? errno : 0);
+ int err = func (file1_alt, file2_alt);
+ int saved_errno = (err < 0 ? errno : 0);
if (file1 != file1_alt)
free (file1_alt);
long double
atanl (long double x)
{
- int k, sign;
- long double t, u, p, q;
-
/* Check for zero or NaN. */
if (isnanl (x) || x == 0.0)
return x + x;
- sign = x < 0.0;
+ int sign = x < 0.0;
if (x + x == x)
{
}
if (sign)
- x = -x;
+ x = -x;
+ int k;
+ long double t;
if (x >= 10.25)
{
k = 83;
Roundoff to integer is asymmetrical to avoid cancellation when t < 0
(cf. fdlibm). */
k = 8.0 * x + 0.25;
- u = 0.125 * k;
+ long double u = 0.125 * k;
/* Small arctan argument. */
t = (x - u) / (1.0 + x * u);
}
/* Arctan of small argument t. */
- u = t * t;
- p = ((((p4 * u) + p3) * u + p2) * u + p1) * u + p0;
- q = ((((u + q4) * u + q3) * u + q2) * u + q1) * u + q0;
+ long double u = t * t;
+ long double p = ((((p4 * u) + p3) * u + p2) * u + p1) * u + p0;
+ long double q = ((((u + q4) * u + q3) * u + q2) * u + q1) * u + q0;
u = t * u * p / q + t;
/* arctan x = arctan u + arctan t */
enum numbered_backup_result result = BACKUP_IS_NEW;
DIR *dirp = *dirpp;
char *buf = *buffer;
- idx_t versionlenmax = 1;
idx_t baselen = filelen - base_offset;
if (dirp)
*dirpp = dirp;
}
+ idx_t versionlenmax = 1;
+
for (struct dirent *dp; (dp = readdir (dirp)) != NULL; )
{
if (_D_EXACT_NAMLEN (dp) < baselen + 4)
decode_8 (char const *restrict in, idx_t inlen,
char *restrict *outp, idx_t *outleft)
{
- char *out = *outp;
if (inlen < 8)
return false;
if (!isbase32 (in[0]) || !isbase32 (in[1]))
return false;
+ char *out = *outp;
+
if (*outleft)
{
*out++ = ((base32_to_int[to_uchar (in[0])] << 3)
const char *restrict in, idx_t inlen,
char *restrict out, idx_t *outlen)
{
- idx_t outleft = *outlen;
bool ignore_newlines = ctx != NULL;
bool flush_ctx = false;
unsigned int ctx_i = 0;
flush_ctx = inlen == 0;
}
+ idx_t outleft = *outlen;
while (true)
{
{
char const *in_end = in + inlen;
- char const *non_nl;
+ char const *non_nl;
if (ignore_newlines)
non_nl = get_8 (ctx, &in, in_end, &inlen);
else
decode_4 (char const *restrict in, idx_t inlen,
char *restrict *outp, idx_t *outleft)
{
- char *out = *outp;
if (inlen < 2)
return false;
if (!isbase64 (in[0]) || !isbase64 (in[1]))
return false;
+ char *out = *outp;
+
if (*outleft)
{
*out++ = ((base64_to_int[to_uchar (in[0])] << 2)
const char *restrict in, idx_t inlen,
char *restrict out, idx_t *outlen)
{
- idx_t outleft = *outlen;
bool ignore_newlines = ctx != NULL;
bool flush_ctx = false;
unsigned int ctx_i = 0;
flush_ctx = inlen == 0;
}
+ idx_t outleft = *outlen;
while (true)
{
{
char const *in_end = in + inlen;
- char const *non_nl;
+ char const *non_nl;
if (ignore_newlines)
non_nl = get_4 (ctx, &in, in_end, &inlen);
else
last_component (char const *name)
{
char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
- bool last_was_slash = false;
-
while (ISSLASH (*base))
base++;
+ bool last_was_slash = false;
for (char const *p = base; *p; p++)
{
if (ISSLASH (*p))
base_len (char const *name)
{
size_t len;
- size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
-
for (len = strlen (name); 1 < len && ISSLASH (name[len - 1]); len--)
continue;
&& ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
return 2;
+ size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
&& len == prefix_len && ISSLASH (name[prefix_len]))
return prefix_len + 1;
bool
bitset_copy_ (bitset dst, bitset src)
{
- bitset_bindex i;
- bitset_iterator iter;
-
/* Convert bitset types. We assume that the DST bitset
is large enough to hold the SRC bitset. */
+
bitset_zero (dst);
+
+ bitset_bindex i;
+ bitset_iterator iter;
BITSET_FOR_EACH (iter, src, i, 0)
bitset_set (dst, i);
bset->b.csize = 0;
}
- lbitset_elt *next;
- for (; elt; elt = next)
+ for (; elt;)
{
- next = elt->next;
+ lbitset_elt *next = elt->next;
lbitset_elt_free (elt);
+ elt = next;
}
}
static inline void
lbitset_weed (bitset bset)
{
- lbitset_elt *next;
- for (lbitset_elt *elt = LBITSET_HEAD (bset); elt; elt = next)
+ for (lbitset_elt *elt = LBITSET_HEAD (bset); elt;)
{
- next = elt->next;
+ lbitset_elt *next = elt->next;
if (lbitset_elt_zero_p (elt))
lbitset_elt_unlink (bset, elt);
+ elt = next;
}
}
/* The coast is clear, plant boot! */
#if LBITSET_ELT_WORDS == 2
- bitset_word word = srcp[0];
- if (word)
- BITSET_FOR_EACH_BIT (pos, word)
- list[count++] = bitno + pos;
- windex++;
- bitno = windex * BITSET_WORD_BITS;
-
- word = srcp[1];
- if (word)
- BITSET_FOR_EACH_BIT (pos, word)
- list[count++] = bitno + pos;
- windex++;
- bitno = windex * BITSET_WORD_BITS;
+ {
+ bitset_word word = srcp[0];
+ if (word)
+ BITSET_FOR_EACH_BIT (pos, word)
+ list[count++] = bitno + pos;
+ windex++;
+ bitno = windex * BITSET_WORD_BITS;
+ }
+ {
+ bitset_word word = srcp[1];
+ if (word)
+ BITSET_FOR_EACH_BIT (pos, word)
+ list[count++] = bitno + pos;
+ windex++;
+ bitno = windex * BITSET_WORD_BITS;
+ }
#else
for (int i = 0; i < LBITSET_ELT_WORDS; i++)
{
/* The coast is clear, plant boot! */
#if TBITSET_ELT_WORDS == 2
- bitset_word word = srcp[0];
- if (word)
- BITSET_FOR_EACH_BIT (pos, word)
- list[count++] = bitno + pos;
- windex++;
- bitno = windex * BITSET_WORD_BITS;
-
- word = srcp[1];
- if (word)
- BITSET_FOR_EACH_BIT (pos, word)
- list[count++] = bitno + pos;
- windex++;
- bitno = windex * BITSET_WORD_BITS;
+ {
+ bitset_word word = srcp[0];
+ if (word)
+ BITSET_FOR_EACH_BIT (pos, word)
+ list[count++] = bitno + pos;
+ windex++;
+ bitno = windex * BITSET_WORD_BITS;
+ }
+ {
+ bitset_word word = srcp[1];
+ if (word)
+ BITSET_FOR_EACH_BIT (pos, word)
+ list[count++] = bitno + pos;
+ windex++;
+ bitno = windex * BITSET_WORD_BITS;
+ }
#else
for (int i = 0; i < TBITSET_ELT_WORDS; i++, windex++)
{
if (GetTickCount64Func != NULL)
{
ULONGLONG uptime_ms = GetTickCount64Func ();
- struct timespec uptime;
- struct timespec result;
+
struct timeval tv;
if (gettimeofday (&tv, NULL) >= 0)
{
+ struct timespec uptime;
uptime.tv_sec = uptime_ms / 1000;
uptime.tv_nsec = (uptime_ms % 1000) * 1000000;
+
+ struct timespec result;
result.tv_sec = tv.tv_sec;
result.tv_nsec = tv.tv_usec * 1000;
if (result.tv_nsec < uptime.tv_nsec)
}
result.tv_sec -= uptime.tv_sec;
result.tv_nsec -= uptime.tv_nsec;
+
*p_boot_time = result;
return 0;
}
if (c != EOF)
{
mbstate_t state;
- char s[1];
- char32_t wc;
-
mbszero (&state);
+ char s[1];
s[0] = (unsigned char) c;
+ char32_t wc;
if (mbrtoc32 (&wc, s, 1, &state) <= 1)
return wc;
}
c_asprintf (char **resultp, const char *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = c_vasprintf (resultp, format, args);
+ int result = c_vasprintf (resultp, format, args);
va_end (args);
+
return result;
}
c_aszprintf (char **resultp, const char *format, ...)
{
va_list args;
- ptrdiff_t result;
-
va_start (args, format);
- result = c_vaszprintf (resultp, format, args);
+ ptrdiff_t result = c_vaszprintf (resultp, format, args);
va_end (args);
+
return result;
}
c_snprintf (char *str, size_t size, const char *format, ...)
{
va_list args;
- ptrdiff_t ret;
-
va_start (args, format);
- ret = c_vsnzprintf (str, size, format, args);
+
+ ptrdiff_t ret = c_vsnzprintf (str, size, format, args);
+
va_end (args);
#if PTRDIFF_MAX > INT_MAX
ptrdiff_t
c_snzprintf (char *str, size_t size, const char *format, ...)
{
- char *output;
- size_t len;
- size_t lenbuf = size;
va_list args;
-
va_start (args, format);
- output = c_vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+
+ size_t lenbuf = size;
+ char *output = c_vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
+
va_end (args);
if (!output)
{
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
- unsigned char c1, c2;
if (p1 == p2)
return 0;
- do
+ for (;; p1++, p2++)
{
- c1 = c_tolower (*p1);
- c2 = c_tolower (*p2);
-
- if (c1 == '\0')
- break;
-
- ++p1;
- ++p2;
+ unsigned char c1 = c_tolower (*p1);
+ unsigned char c2 = c_tolower (*p2);
+
+ if (c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
}
char *
c_strcasestr (const char *haystack_start, const char *needle_start)
{
- const char *haystack = haystack_start;
const char *needle = needle_start;
- size_t needle_len; /* Length of NEEDLE. */
- size_t haystack_len; /* Known minimum length of HAYSTACK. */
- bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
- while (*haystack && *needle)
- ok &= (c_tolower ((unsigned char) *haystack++)
- == c_tolower ((unsigned char) *needle++));
- if (*needle)
- return NULL;
- if (ok)
- return (char *) haystack_start;
- needle_len = needle - needle_start;
- haystack = haystack_start + 1;
- haystack_len = needle_len - 1;
+ {
+ const char *haystack = haystack_start;
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+ while (*haystack && *needle)
+ ok &= (c_tolower ((unsigned char) *haystack++)
+ == c_tolower ((unsigned char) *needle++));
+ if (*needle)
+ return NULL;
+ if (ok)
+ return (char *) haystack_start;
+ }
+
+ size_t needle_len = /* Length of NEEDLE. */
+ needle - needle_start;
+ const char *haystack = haystack_start + 1;
+ size_t haystack_len = /* Known minimum length of HAYSTACK. */
+ needle_len - 1;
/* Perform the search. Abstract memory is considered to be an array
of 'unsigned char' values, not an array of 'char' values. See
{
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
- unsigned char c1, c2;
if (p1 == p2 || n == 0)
return 0;
- do
+ for (;; p1++, p2++)
{
- c1 = c_tolower (*p1);
- c2 = c_tolower (*p2);
-
- if (--n == 0 || c1 == '\0')
- break;
-
- ++p1;
- ++p2;
+ unsigned char c1 = c_tolower (*p1);
+ unsigned char c2 = c_tolower (*p2);
+
+ if (--n == 0 || c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
}
end = p + 1;
if (p[1] == 'x' || p[1] == 'X')
{
- size_t num_hex_digits = 0;
p += 2;
+
+ size_t num_hex_digits = 0;
/* Parse a non-empty sequence of hexadecimal digits optionally
containing the decimal point character '.'. */
while (*p != '\0')
/* Create a modified floating-point number, in which the character '.'
is replaced with the locale-dependent decimal_point. */
size_t len = end - start;
+
+ char stackbuf[1000];
char *buf;
char *buf_malloced = NULL;
- char stackbuf[1000];
- char *end_in_buf;
-
if (len < sizeof (stackbuf))
buf = stackbuf;
else
buf[decimal_point_p - start] = decimal_point;
buf[len] = '\0';
+ char *end_in_buf;
r = STRTOD (buf, &end_in_buf);
if (endptr != NULL)
*endptr = (char *) (start + (end_in_buf - buf));
ptrdiff_t
c_vsnzprintf (char *str, size_t size, const char *format, va_list args)
{
- char *output;
- size_t len;
size_t lenbuf = size;
-
- output = c_vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+ char *output = c_vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
return -1;
c_xasprintf (const char *format, ...)
{
va_list args;
- char *result;
-
va_start (args, format);
- result = c_xvasprintf (format, args);
+ char *result = c_xvasprintf (format, args);
va_end (args);
return result;
c32stombs (char *dest, const char32_t *src, size_t len)
{
mbstate_t state;
-
mbszero (&state);
+
return c32srtombs (dest, &src, len, &state);
}
if (wc != WEOF)
{
mbstate_t state;
- char buf[8];
-
mbszero (&state);
+
+ char buf[8];
if (c32rtomb (buf, wc, &state) == 1)
return (unsigned char) buf[0];
}
char *
canon_host_r (char const *host, int *cherror)
{
- char *retval = NULL;
static struct addrinfo hints;
+ hints.ai_flags = AI_CANONNAME;
+
struct addrinfo *res = NULL;
- int status;
+ int status = getaddrinfo (host, NULL, &hints, &res);
- hints.ai_flags = AI_CANONNAME;
- status = getaddrinfo (host, NULL, &hints, &res);
+ char *retval = NULL;
if (!status)
{
/* https://lists.gnu.org/r/bug-coreutils/2006-09/msg00300.html
static char *
realpath_stk (const char *name, char *resolved, struct realpath_bufs *bufs)
{
- char *dest;
- char const *start;
- char const *end;
- int num_links = 0;
-
if (name == NULL)
{
/* As per Single Unix Specification V2 we must return an error if
}
char *rname = bufs->rname.data;
- bool end_in_extra_buffer = false;
- bool failed = true;
/* This is always zero for Posix hosts, but can be 2 for MS-Windows
and MS-DOS X:/foo/bar file names. */
idx_t prefix_len;
+ char *dest;
+ char const *start;
+
if (!IS_ABSOLUTE_FILE_NAME (name))
{
while (!__getcwd (bufs->rname.data, bufs->rname.length))
start = name + prefix_len;
}
- for ( ; *start; start = end)
+ int num_links = 0;
+ bool end_in_extra_buffer = false;
+ bool failed = true;
+
+ for (; *start;)
{
/* Skip sequence of multiple file name separators. */
while (ISSLASH (*start))
++start;
/* Find end of component. */
+ char const *end;
for (end = start; *end && !ISSLASH (*end); ++end)
/* Nothing. */;
: errno == EINVAL))
goto error;
}
+
+ start = end;
}
if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
--dest;
canonicalize_filename_mode_stk (const char *name, canonicalize_mode_t can_mode,
struct realpath_bufs *bufs)
{
- char *dest;
- char const *start;
- char const *end;
- Hash_table *ht = NULL;
- bool logical = (can_mode & CAN_NOLINKS) != 0;
- int num_links = 0;
-
canonicalize_mode_t can_exist = can_mode & CAN_MODE_MASK;
if (multiple_bits_set (can_exist))
{
}
char *rname = bufs->rname.data;
- bool end_in_extra_buffer = false;
- bool failed = true;
/* This is always zero for Posix hosts, but can be 2 for MS-Windows
and MS-DOS X:/foo/bar file names. */
idx_t prefix_len;
+ char *dest;
+ char const *start;
+
if (!IS_ABSOLUTE_FILE_NAME (name))
{
while (!getcwd (bufs->rname.data, bufs->rname.length))
start = name + prefix_len;
}
- for ( ; *start; start = end)
+ bool logical = (can_mode & CAN_NOLINKS) != 0;
+
+ int num_links = 0;
+ Hash_table *ht = NULL;
+ bool end_in_extra_buffer = false;
+ bool failed = true;
+
+ for (; *start;)
{
/* Skip sequence of multiple file name separators. */
while (ISSLASH (*start))
++start;
/* Find end of component. */
+ char const *end;
for (end = start; *end && !ISSLASH (*end); ++end)
/* Nothing. */;
if (seen_triple (&ht, start, &st))
{
if (can_exist == CAN_MISSING)
- continue;
+ goto next_component;
errno = ELOOP;
goto error;
}
&& !end[strspn (end, SLASHES)])))
goto error;
}
+
+ next_component:
+ start = end;
}
if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
--dest;
scratch_buffer_init (&bufs.rname);
scratch_buffer_init (&bufs.extra);
scratch_buffer_init (&bufs.link);
+
char *result = canonicalize_filename_mode_stk (name, can_mode, &bufs);
+
scratch_buffer_free (&bufs.link);
scratch_buffer_free (&bufs.extra);
scratch_buffer_free (&bufs.rname);
+
return result;
}
{
if (isfinite (x) && x != 0.0)
{
- double xm, ym, u, t2;
+ /* Reduce X. XM now is in range 1.0 to 0.5. */
int xe;
-
- /* Reduce X. XM now is an range 1.0 to 0.5. */
- xm = frexp (fabs (x), &xe);
-
- u = (0.354895765043919860
- + ((1.50819193781584896
- + ((-2.11499494167371287
- + ((2.44693122563534430
- + ((-1.83469277483613086
- + (0.784932344976639262 - 0.145263899385486377 * xm)
- * xm)
- * xm))
- * xm))
- * xm))
- * xm));
-
- t2 = u * u * u;
-
- ym = u * (t2 + 2.0 * xm) / (2.0 * t2 + xm) * factor[2 + xe % 3];
+ double xm = frexp (fabs (x), &xe);
+
+ double u = (0.354895765043919860
+ + ((1.50819193781584896
+ + ((-2.11499494167371287
+ + ((2.44693122563534430
+ + ((-1.83469277483613086
+ + (0.784932344976639262 - 0.145263899385486377 * xm)
+ * xm)
+ * xm))
+ * xm))
+ * xm))
+ * xm));
+
+ double t2 = u * u * u;
+
+ double ym = u * (t2 + 2.0 * xm) / (2.0 * t2 + xm) * factor[2 + xe % 3];
return ldexp (x > 0.0 ? ym : -ym, xe / 3);
}
{
if (isfinite (x) && x != 0.0f)
{
- float xm, ym, u, t2;
+ /* Reduce X. XM now is in range 1.0 to 0.5. */
int xe;
+ float xm = frexpf (fabsf (x), &xe);
- /* Reduce X. XM now is an range 1.0 to 0.5. */
- xm = frexpf (fabsf (x), &xe);
+ float u = (0.492659620528969547
+ + (0.697570460207922770 - 0.191502161678719066 * xm) * xm);
- u = (0.492659620528969547
- + (0.697570460207922770 - 0.191502161678719066 * xm) * xm);
+ float t2 = u * u * u;
- t2 = u * u * u;
-
- ym = u * (t2 + 2.0 * xm) / (2.0 * t2 + xm) * factor[2 + xe % 3];
+ float ym = u * (t2 + 2.0 * xm) / (2.0 * t2 + xm) * factor[2 + xe % 3];
return ldexpf (x > 0.0 ? ym : -ym, xe / 3);
}
{
if (isfinite (x) && x != 0.0L)
{
- int e, rem, sign;
- long double z;
-
+ int sign;
if (x > 0)
sign = 1;
else
x = -x;
}
- z = x;
+ long double z = x;
/* extract power of 2, leaving mantissa between 0.5 and 1 */
+ int e;
x = frexpl (x, &e);
/* Approximate cube root of number between .5 and 1,
+ 1.3304961236013647092521e0L) * x + 3.7568280825958912391243e-1L;
/* exponent divided by 3 */
+ int rem;
if (e >= 0)
{
rem = e;
{
size_t len = strlen (dir);
char *dir_end = dir + len;
- struct cd_buf cdb;
- size_t n_leading_slash;
+ struct cd_buf cdb;
cdb_init (&cdb);
/* If DIR is the empty string, then the chdir above
assure (PATH_MAX <= len);
/* Count leading slashes. */
- n_leading_slash = strspn (dir, "/");
+ size_t n_leading_slash = strspn (dir, "/");
/* Handle any leading slashes as well as any name that matches
the regular expression, m!^//hostname[/]*! . Handling this
code in the following loop cleaner. */
if (n_leading_slash == 2)
{
- int err;
/* Find next slash.
We already know that dir[2] is neither a slash nor '\0'. */
char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
return -1;
}
*slash = '\0';
- err = cdb_advance_fd (&cdb, dir);
+ int err = cdb_advance_fd (&cdb, dir);
*slash = '/';
if (err != 0)
goto Fail;
while (PATH_MAX <= dir_end - dir)
{
- int err;
/* Find a slash that is PATH_MAX or fewer bytes away from dir.
I.e. see if there is a slash that will give us a name of
length PATH_MAX-1 or less. */
*slash = '\0';
assure (slash - dir < PATH_MAX);
- err = cdb_advance_fd (&cdb, dir);
+ int err = cdb_advance_fd (&cdb, dir);
*slash = '/';
if (err != 0)
goto Fail;
int
main (int argc, char *argv[])
{
- char *line = NULL;
- size_t n = 0;
- int len;
-
atexit (close_stdout);
- len = getline (&line, &n, stdin);
+ char *line = NULL;
+ size_t n = 0;
+ int len = getline (&line, &n, stdin);
if (len < 0)
{
int saved_errno = errno;
new_classpath (const char * const *classpaths, unsigned int classpaths_count,
bool use_minimal_classpath)
{
- const char *old_classpath;
- unsigned int length;
- char *result;
- char *p;
-
- old_classpath = (use_minimal_classpath ? NULL : getenv (CLASSPATHVAR));
+ const char *old_classpath = (use_minimal_classpath ? NULL : getenv (CLASSPATHVAR));
if (old_classpath == NULL)
old_classpath = "";
- length = 0;
+ unsigned int length = 0;
for (unsigned int i = 0; i < classpaths_count; i++)
length += strlen (classpaths[i]) + 1;
length += strlen (old_classpath);
if (classpaths_count > 0 && old_classpath[0] == '\0')
length--;
- result = XNMALLOC (length + 1, char);
- p = result;
- for (unsigned int i = 0; i < classpaths_count; i++)
- {
- memcpy (p, classpaths[i], strlen (classpaths[i]));
- p += strlen (classpaths[i]);
- *p++ = PATH_SEPARATOR;
- }
- if (old_classpath[0] != '\0')
- {
- memcpy (p, old_classpath, strlen (old_classpath));
- p += strlen (old_classpath);
- }
- else
- {
- if (classpaths_count > 0)
- p--;
- }
- *p = '\0';
+ char *result = XNMALLOC (length + 1, char);
+ {
+ char *p = result;
+ for (unsigned int i = 0; i < classpaths_count; i++)
+ {
+ memcpy (p, classpaths[i], strlen (classpaths[i]));
+ p += strlen (classpaths[i]);
+ *p++ = PATH_SEPARATOR;
+ }
+ if (old_classpath[0] != '\0')
+ {
+ memcpy (p, old_classpath, strlen (old_classpath));
+ p += strlen (old_classpath);
+ }
+ else
+ {
+ if (classpaths_count > 0)
+ p--;
+ }
+ *p = '\0';
+ }
return result;
}
if (fds != NULL)
{
- gl_list_iterator_t iter;
+ gl_list_iterator_t iter = gl_list_iterator (fds);
const void *element;
-
- iter = gl_list_iterator (fds);
while (gl_list_iterator_next (&iter, &element, NULL))
{
clean_temp_asyncsafe_close ((struct closeable_fd *) element);
if (files != NULL)
{
- gl_list_iterator_t iter;
+ gl_list_iterator_t iter = gl_list_iterator (files);
const void *element;
-
- iter = gl_list_iterator (files);
while (gl_list_iterator_next (&iter, &element, NULL))
{
const char *file = (const char *) element;
if (dir != NULL)
{
- gl_list_iterator_t iter;
- const void *element;
-
- /* First cleanup the files in the subdirectories. */
- iter = gl_list_iterator (dir->files);
- while (gl_list_iterator_next (&iter, &element, NULL))
- {
- const char *file = (const char *) element;
- unlink (file);
- }
- gl_list_iterator_free (&iter);
-
- /* Then cleanup the subdirectories. */
- iter = gl_list_iterator (dir->subdirs);
- while (gl_list_iterator_next (&iter, &element, NULL))
- {
- const char *subdir = (const char *) element;
- rmdir (subdir);
- }
- gl_list_iterator_free (&iter);
+ {
+ /* First cleanup the files in the subdirectories. */
+ gl_list_iterator_t iter = gl_list_iterator (dir->files);
+ const void *element;
+ while (gl_list_iterator_next (&iter, &element, NULL))
+ {
+ const char *file = (const char *) element;
+ unlink (file);
+ }
+ gl_list_iterator_free (&iter);
+ }
+ {
+ /* Then cleanup the subdirectories. */
+ gl_list_iterator_t iter = gl_list_iterator (dir->subdirs);
+ const void *element;
+ while (gl_list_iterator_next (&iter, &element, NULL))
+ {
+ const char *subdir = (const char *) element;
+ rmdir (subdir);
+ }
+ gl_list_iterator_free (&iter);
+ }
/* Then cleanup the temporary directory itself. */
rmdir (dir->dirname);
int
cleanup_temporary_file (const char *absolute_file_name, bool cleanup_verbose)
{
- int err;
-
- err = clean_temp_unlink (absolute_file_name, cleanup_verbose);
+ int err = clean_temp_unlink (absolute_file_name, cleanup_verbose);
unregister_temporary_file (absolute_file_name);
return err;
if (mt) gl_lock_lock (dir_cleanup_list_lock);
- struct tempdir * volatile *tmpdirp = NULL;
- struct tempdir *tmpdir;
- char *xtemplate;
- char *tmpdirname;
-
/* See whether it can take the slot of an earlier temporary directory
already cleaned up. */
+ struct tempdir * volatile *tmpdirp = NULL;
for (size_t i = 0; i < dir_cleanup_list.tempdir_count; i++)
if (dir_cleanup_list.tempdir_list[i] == NULL)
{
}
/* Initialize a 'struct tempdir'. */
- tmpdir = XMALLOC (struct tempdir);
+ struct tempdir *tmpdir = XMALLOC (struct tempdir);
tmpdir->dirname = NULL;
tmpdir->cleanup_verbose = cleanup_verbose;
tmpdir->subdirs =
NULL, false);
/* Create the temporary directory. */
- xtemplate = (char *) xmalloca (PATH_MAX);
+ char *xtemplate = (char *) xmalloca (PATH_MAX);
if (path_search (xtemplate, PATH_MAX, parentdir, prefix, parentdir == NULL))
{
error (0, errno,
goto quit;
}
block_fatal_signals ();
- tmpdirname = mkdtemp (xtemplate);
+ char *tmpdirname = mkdtemp (xtemplate);
int saved_errno = errno;
if (tmpdirname != NULL)
{
if (mt) gl_lock_lock (dir_cleanup_list_lock);
gl_list_t list = tmpdir->files;
- gl_list_node_t node;
- node = gl_list_search (list, absolute_file_name);
+ gl_list_node_t node = gl_list_search (list, absolute_file_name);
if (node != NULL)
{
char *old_string = (char *) gl_list_node_value (list, node);
if (mt) gl_lock_lock (dir_cleanup_list_lock);
gl_list_t list = tmpdir->subdirs;
- gl_list_node_t node;
- node = gl_list_search (list, absolute_dir_name);
+ gl_list_node_t node = gl_list_search (list, absolute_dir_name);
if (node != NULL)
{
char *old_string = (char *) gl_list_node_value (list, node);
cleanup_temp_file (struct temp_dir *dir,
const char *absolute_file_name)
{
- int err;
-
- err = clean_temp_unlink (absolute_file_name, dir->cleanup_verbose);
+ int err = clean_temp_unlink (absolute_file_name, dir->cleanup_verbose);
unregister_temp_file (dir, absolute_file_name);
return err;
cleanup_temp_subdir (struct temp_dir *dir,
const char *absolute_dir_name)
{
- int err;
-
- err = do_rmdir (absolute_dir_name, dir->cleanup_verbose);
+ int err = do_rmdir (absolute_dir_name, dir->cleanup_verbose);
unregister_temp_subdir (dir, absolute_dir_name);
return err;
{
struct tempdir *tmpdir = (struct tempdir *)dir;
int err = 0;
- gl_list_t list;
- gl_list_iterator_t iter;
- const void *element;
- gl_list_node_t node;
/* First cleanup the files in the subdirectories. */
- list = tmpdir->files;
- iter = gl_list_iterator (list);
- while (gl_list_iterator_next (&iter, &element, &node))
- {
- char *file = (char *) element;
+ {
+ gl_list_t list = tmpdir->files;
+ gl_list_iterator_t iter = gl_list_iterator (list);
+ const void *element;
+ gl_list_node_t node;
+ while (gl_list_iterator_next (&iter, &element, &node))
+ {
+ char *file = (char *) element;
- err |= clean_temp_unlink (file, dir->cleanup_verbose);
- gl_list_remove_node (list, node);
- /* Now only we can free file. */
- free (file);
- }
- gl_list_iterator_free (&iter);
+ err |= clean_temp_unlink (file, dir->cleanup_verbose);
+ gl_list_remove_node (list, node);
+ /* Now only we can free file. */
+ free (file);
+ }
+ gl_list_iterator_free (&iter);
+ }
/* Then cleanup the subdirectories. */
- list = tmpdir->subdirs;
- iter = gl_list_iterator (list);
- while (gl_list_iterator_next (&iter, &element, &node))
- {
- char *subdir = (char *) element;
+ {
+ gl_list_t list = tmpdir->subdirs;
+ gl_list_iterator_t iter = gl_list_iterator (list);
+ const void *element;
+ gl_list_node_t node;
+ while (gl_list_iterator_next (&iter, &element, &node))
+ {
+ char *subdir = (char *) element;
- err |= do_rmdir (subdir, dir->cleanup_verbose);
- gl_list_remove_node (list, node);
- /* Now only we can free subdir. */
- free (subdir);
- }
- gl_list_iterator_free (&iter);
+ err |= do_rmdir (subdir, dir->cleanup_verbose);
+ gl_list_remove_node (list, node);
+ /* Now only we can free subdir. */
+ free (subdir);
+ }
+ gl_list_iterator_free (&iter);
+ }
return err;
}
int
open_temp (const char *file_name, int flags, mode_t mode, bool delete_on_close)
{
- int fd;
- int saved_errno;
-
block_fatal_signals ();
+ int fd;
/* Note: 'open' here is actually open() or open_safer(). */
#if defined _WIN32 && ! defined __CYGWIN__
/* Use _O_TEMPORARY when possible, to increase the chances that the
else
#endif
fd = open (file_name, flags, mode);
- saved_errno = errno;
+ int saved_errno = errno;
if (fd >= 0)
register_fd (fd);
unblock_fatal_signals ();
FILE *
fopen_temp (const char *file_name, const char *mode, bool delete_on_close)
{
+ block_fatal_signals ();
FILE *fp;
int saved_errno;
-
- block_fatal_signals ();
/* Note: 'fopen' here is actually fopen() or fopen_safer(). */
#if defined _WIN32 && ! defined __CYGWIN__
/* Use _O_TEMPORARY when possible, to increase the chances that the
clean_temp_init_asyncsafe_close ();
- int result = 0;
- int saved_errno = 0;
-
bool mt = gl_multithreaded ();
if (mt) gl_lock_lock (descriptors_lock);
abort ();
/* Search through the list, and clean it up on the fly. */
+ int result = 0;
+ int saved_errno = 0;
bool found = false;
- gl_list_iterator_t iter = gl_list_iterator (list);
- const void *elt;
- gl_list_node_t node;
- if (gl_list_iterator_next (&iter, &elt, &node))
- for (;;)
- {
- struct closeable_fd *element = (struct closeable_fd *) elt;
+ {
+ gl_list_iterator_t iter = gl_list_iterator (list);
+ const void *elt;
+ gl_list_node_t node;
+ if (gl_list_iterator_next (&iter, &elt, &node))
+ for (;;)
+ {
+ struct closeable_fd *element = (struct closeable_fd *) elt;
- /* Close the file descriptor, avoiding races with the signal
- handler. */
- if (element->fd == fd)
- {
- found = true;
- result = clean_temp_asyncsafe_close (element);
- saved_errno = errno;
- }
+ /* Close the file descriptor, avoiding races with the signal
+ handler. */
+ if (element->fd == fd)
+ {
+ found = true;
+ result = clean_temp_asyncsafe_close (element);
+ saved_errno = errno;
+ }
- bool free_this_node = element->done;
- struct closeable_fd *element_to_free = element;
- gl_list_node_t node_to_free = node;
+ bool free_this_node = element->done;
+ struct closeable_fd *element_to_free = element;
+ gl_list_node_t node_to_free = node;
- bool have_next = gl_list_iterator_next (&iter, &elt, &node);
+ bool have_next = gl_list_iterator_next (&iter, &elt, &node);
- if (free_this_node)
- {
- free (element_to_free);
- gl_list_remove_node (list, node_to_free);
- }
+ if (free_this_node)
+ {
+ free (element_to_free);
+ gl_list_remove_node (list, node_to_free);
+ }
- if (!have_next)
- break;
- }
- gl_list_iterator_free (&iter);
+ if (!have_next)
+ break;
+ }
+ gl_list_iterator_free (&iter);
+ }
if (!found)
/* descriptors should already contain fd. */
abort ();
{
int fd = fileno (fp);
- int result = 0;
- int saved_errno = 0;
-
bool mt = gl_multithreaded ();
if (mt) gl_lock_lock (descriptors_lock);
abort ();
/* Search through the list, and clean it up on the fly. */
+ int result = 0;
+ int saved_errno = 0;
bool found = false;
- gl_list_iterator_t iter = gl_list_iterator (list);
- const void *elt;
- gl_list_node_t node;
- if (gl_list_iterator_next (&iter, &elt, &node))
- for (;;)
- {
- struct closeable_fd *element = (struct closeable_fd *) elt;
+ {
+ gl_list_iterator_t iter = gl_list_iterator (list);
+ const void *elt;
+ gl_list_node_t node;
+ if (gl_list_iterator_next (&iter, &elt, &node))
+ for (;;)
+ {
+ struct closeable_fd *element = (struct closeable_fd *) elt;
- /* Close the file descriptor and the stream, avoiding races with the
- signal handler. */
- if (element->fd == fd)
- {
- found = true;
- result = asyncsafe_fclose_variant (element, fp, fclose_variant);
- saved_errno = errno;
- }
+ /* Close the file descriptor and the stream, avoiding races with the
+ signal handler. */
+ if (element->fd == fd)
+ {
+ found = true;
+ result = asyncsafe_fclose_variant (element, fp, fclose_variant);
+ saved_errno = errno;
+ }
- bool free_this_node = element->done;
- struct closeable_fd *element_to_free = element;
- gl_list_node_t node_to_free = node;
+ bool free_this_node = element->done;
+ struct closeable_fd *element_to_free = element;
+ gl_list_node_t node_to_free = node;
- bool have_next = gl_list_iterator_next (&iter, &elt, &node);
+ bool have_next = gl_list_iterator_next (&iter, &elt, &node);
- if (free_this_node)
- {
- free (element_to_free);
- gl_list_remove_node (list, node_to_free);
- }
+ if (free_this_node)
+ {
+ free (element_to_free);
+ gl_list_remove_node (list, node_to_free);
+ }
- if (!have_next)
- break;
- }
- gl_list_iterator_free (&iter);
+ if (!have_next)
+ break;
+ }
+ gl_list_iterator_free (&iter);
+ }
if (!found)
/* descriptors should have contained fd. */
abort ();
bool preserve)
{
int err = 0;
- int src_fd;
- struct stat statbuf;
- int mode;
- int dest_fd;
- src_fd = open (src_filename, O_RDONLY | O_BINARY | O_CLOEXEC);
+ int src_fd = open (src_filename, O_RDONLY | O_BINARY | O_CLOEXEC);
if (src_fd < 0)
return GL_COPY_ERR_OPEN_READ;
+ struct stat statbuf;
if (fstat (src_fd, &statbuf) < 0)
{
err = GL_COPY_ERR_OPEN_READ;
goto error_src;
}
- mode = statbuf.st_mode & 07777;
+ int mode = statbuf.st_mode & 07777;
off_t inbytes = S_ISREG (statbuf.st_mode) ? statbuf.st_size : -1;
bool empty_regular_file = inbytes == 0;
- dest_fd = open (dest_filename,
- O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_CLOEXEC,
- /* If preserve is true, we must assume that the file may
- have confidential contents. Therefore open it with mode
- 0600 and assign the permissions at the end.
- If preserve is false, open it with mode 0666 & ~umask. */
- preserve ? 0600 : 0666);
+ int dest_fd = open (dest_filename,
+ O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_CLOEXEC,
+ /* If preserve is true, we must assume that the file may
+ have confidential contents. Therefore open it with
+ mode 0600 and assign the permissions at the end.
+ If preserve is false, open it with mode 0666 & ~umask. */
+ preserve ? 0600 : 0666);
if (dest_fd < 0)
{
err = GL_COPY_ERR_OPEN_BACKUP_WRITE;
int bufsize = IO_SIZE;
char *buf = malloc (bufsize);
if (!buf)
- buf = smallbuf, bufsize = sizeof smallbuf;
+ {
+ buf = smallbuf;
+ bufsize = sizeof smallbuf;
+ }
while (true)
{
/* Preserve the access and modification times. */
{
struct timespec ts[2];
-
ts[0] = get_stat_atime (&statbuf);
ts[1] = get_stat_mtime (&statbuf);
+
utimens (dest_filename, ts);
}
long double
cosl (long double x)
{
- long double y[2],z=0.0L;
- int n;
-
/* cosl(NaN) is NaN */
if (isnanl (x))
return x;
/* |x| ~< pi/4 */
if (x >= -0.7853981633974483096156608458198757210492
&& x <= 0.7853981633974483096156608458198757210492)
- return kernel_cosl(x, z);
+ {
+ long double z = 0.0L;
+ return kernel_cosl(x, z);
+ }
/* cosl(Inf) is NaN, cosl(0) is 1 */
else if (x + x == x && x != 0.0)
/* argument reduction needed */
else
{
- n = ieee754_rem_pio2l (x, y);
+ long double y[2];
+ int n = ieee754_rem_pio2l (x, y);
switch (n & 3)
{
case 0:
static void
make_crc_table (int bits)
{
- unsigned long c;
-
for (int n = 0; n < 256; n++)
{
- c = (unsigned long) n;
+ unsigned long c = (unsigned long) n;
for (int k = 0; k < bits; k++)
{
if (c & 1)
uint32_t
crc32_update_no_xor_pclmul (uint32_t crc, const void *buf, size_t len)
{
- const __m128i_u *data = buf;
- __m128i *datarw;
- size_t bytes_remaining = len;
- __m128i in256[4] = { 0 };
- __m128i xor_crc;
- __m128i in1 = _mm_setzero_si128 ();
- __m128i in2 = _mm_setzero_si128 ();
- __m128i in3 = _mm_setzero_si128 ();
- __m128i in4 = _mm_setzero_si128 ();
- __m128i in5 = _mm_setzero_si128 ();
- __m128i in6 = _mm_setzero_si128 ();
- __m128i in7 = _mm_setzero_si128 ();
- __m128i in8 = _mm_setzero_si128 ();
- __m128i final_buf[12] = { 0 };
- __m128i fold_high;
- __m128i fold_low;
-
/* These constants are calculated as T-1 mod P
0x8F352D95 = (544 - 1) mod P etc
This method is described in Fast CRC Computation for Generic Polynomials
P(x) is the generator polynomial for this CRC32 implementation */
__m128i mu_poly = _mm_set_epi64x (0x1DB710641, 0x1F7011641);
+ const __m128i_u *data = buf;
+ size_t bytes_remaining = len;
+ __m128i final_buf[12] = { 0 };
+ __m128i *datarw;
+
if (bytes_remaining >= 128)
{
/* Here we fold 4x 128bit words forward by 512 bits */
/* First load up our initial state */
- in1 = _mm_loadu_si128 (data);
- in2 = _mm_loadu_si128 (data + 1);
- in3 = _mm_loadu_si128 (data + 2);
- in4 = _mm_loadu_si128 (data + 3);
+ __m128i in1 = _mm_loadu_si128 (data);
+ __m128i in2 = _mm_loadu_si128 (data + 1);
+ __m128i in3 = _mm_loadu_si128 (data + 2);
+ __m128i in4 = _mm_loadu_si128 (data + 3);
/* Initialise with incoming CRC */
- xor_crc = _mm_set_epi32 (0, 0, 0, crc);
- in1 = _mm_xor_si128 (in1, xor_crc);
+ {
+ __m128i xor_crc = _mm_set_epi32 (0, 0, 0, crc);
+ in1 = _mm_xor_si128 (in1, xor_crc);
+ }
while (bytes_remaining >= 128)
{
/* Load up second set of 512 bits */
- in5 = _mm_loadu_si128 (data + 4);
- in6 = _mm_loadu_si128 (data + 5);
- in7 = _mm_loadu_si128 (data + 6);
- in8 = _mm_loadu_si128 (data + 7);
+ __m128i in5 = _mm_loadu_si128 (data + 4);
+ __m128i in6 = _mm_loadu_si128 (data + 5);
+ __m128i in7 = _mm_loadu_si128 (data + 6);
+ __m128i in8 = _mm_loadu_si128 (data + 7);
/* We shift the high QWORD forward 544 bits and the
low QWORD 480 bits */
- fold_high = _mm_clmulepi64_si128 (in1, shift544_shift480, 0x11);
- fold_low = _mm_clmulepi64_si128 (in1, shift544_shift480, 0x00);
- in1 = _mm_xor_si128 (in5, fold_high);
- in1 = _mm_xor_si128 (in1, fold_low);
- fold_high = _mm_clmulepi64_si128 (in2, shift544_shift480, 0x11);
- fold_low = _mm_clmulepi64_si128 (in2, shift544_shift480, 0x00);
- in2 = _mm_xor_si128 (in6, fold_high);
- in2 = _mm_xor_si128 (in2, fold_low);
- fold_high = _mm_clmulepi64_si128 (in3, shift544_shift480, 0x11);
- fold_low = _mm_clmulepi64_si128 (in3, shift544_shift480, 0x00);
- in3 = _mm_xor_si128 (in7, fold_high);
- in3 = _mm_xor_si128 (in3, fold_low);
- fold_high = _mm_clmulepi64_si128 (in4, shift544_shift480, 0x11);
- fold_low = _mm_clmulepi64_si128 (in4, shift544_shift480, 0x00);
- in4 = _mm_xor_si128 (in8, fold_high);
- in4 = _mm_xor_si128 (in4, fold_low);
+ {
+ __m128i fold_high = _mm_clmulepi64_si128 (in1, shift544_shift480, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in1, shift544_shift480, 0x00);
+ in1 = _mm_xor_si128 (in5, fold_high);
+ in1 = _mm_xor_si128 (in1, fold_low);
+ }
+ {
+ __m128i fold_high = _mm_clmulepi64_si128 (in2, shift544_shift480, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in2, shift544_shift480, 0x00);
+ in2 = _mm_xor_si128 (in6, fold_high);
+ in2 = _mm_xor_si128 (in2, fold_low);
+ }
+ {
+ __m128i fold_high = _mm_clmulepi64_si128 (in3, shift544_shift480, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in3, shift544_shift480, 0x00);
+ in3 = _mm_xor_si128 (in7, fold_high);
+ in3 = _mm_xor_si128 (in3, fold_low);
+ }
+ {
+ __m128i fold_high = _mm_clmulepi64_si128 (in4, shift544_shift480, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in4, shift544_shift480, 0x00);
+ in4 = _mm_xor_si128 (in8, fold_high);
+ in4 = _mm_xor_si128 (in4, fold_low);
+ }
bytes_remaining -= 64;
data += 4;
/* Move everything to final_buf because it is RW */
/* XOR in previous CRC value */
memcpy (final_buf, data, bytes_remaining);
- in1 = _mm_loadu_si128 (final_buf);
- xor_crc = _mm_set_epi32 (0, 0, 0, crc);
- in1 = _mm_xor_si128 (in1, xor_crc);
+ __m128i in1 = _mm_loadu_si128 (final_buf);
+ {
+ __m128i xor_crc = _mm_set_epi32 (0, 0, 0, crc);
+ in1 = _mm_xor_si128 (in1, xor_crc);
+ }
_mm_storeu_si128 (final_buf, in1);
datarw = final_buf;
}
while (bytes_remaining >= 32)
{
/* Do 128-bit folds as above */
- in1 = _mm_loadu_si128 (datarw);
- in2 = _mm_loadu_si128 (datarw + 1);
+ __m128i in1 = _mm_loadu_si128 (datarw);
+ __m128i in2 = _mm_loadu_si128 (datarw + 1);
/* We shift the high QWORD forward 160 bits and the
low QWORD 96 bits */
- fold_high = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x11);
- fold_low = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x00);
+ __m128i fold_high = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x00);
in2 = _mm_xor_si128 (in2, fold_high);
in2 = _mm_xor_si128 (in2, fold_low);
which means with little endian we're shifting the number higher
we'll also use this step to pick the <16 byte case */
+ __m128i in1;
+
if (bytes_remaining != 16)
{
/* Pad remainder and fold 128-bits
This is inefficient so we only actually want to hit this on the actual end of data
If we're reading a multiple of 32 bytes in the loop then this will never get hit */
+ __m128i in2;
+
/* Read in at an offset so we get the shift for free */
- memcpy (((char *) in256) + (32 - bytes_remaining), datarw,
- bytes_remaining);
- in1 = _mm_loadu_si128 (in256);
- in2 = _mm_loadu_si128 (in256 + 1);
+ {
+ __m128i in256[4] = { 0 };
+ memcpy (((char *) in256) + (32 - bytes_remaining), datarw,
+ bytes_remaining);
+ in1 = _mm_loadu_si128 (in256);
+ in2 = _mm_loadu_si128 (in256 + 1);
+ }
/* Now we fold in1 onto in2 */
shift160_shift96 = _mm_set_epi64x (0x0ccaa009e, 0x1751997d0);
- fold_high = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x11);
- fold_low = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x00);
+ __m128i fold_high = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x11);
+ __m128i fold_low = _mm_clmulepi64_si128 (in1, shift160_shift96, 0x00);
in2 = _mm_xor_si128 (in2, fold_high);
in1 = _mm_xor_si128 (in2, fold_low);
}
/* We now have 16 bytes and fold as normal */
- in2 =
- _mm_and_si128 (_mm_srli_si128 (in1, 8), _mm_set_epi64x (0, 0xffffffff));
- in3 =
- _mm_and_si128 (_mm_srli_si128 (in1, 12), _mm_set_epi64x (0, 0xffffffff));
- in1 = _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffffffffffff));
- /* Multiply first 64 bits against shift96 */
- in1 = _mm_clmulepi64_si128 (shift96_shift64, in1, 0x00);
- /* First 32 bits go on in2 */
- in2 =
- _mm_xor_si128 (in2, _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffff)));
- /* Next 64 bits go on in3 */
- in3 = _mm_xor_si128 (in3, _mm_srli_si128 (in1, 4));
- /* Then shift 64 bits from here */
- in1 = _mm_clmulepi64_si128 (shift96_shift64, in2, 0x01);
- in1 = _mm_xor_si128 (in1, in3);
-
- /* This is the Barrett reduction */
- /* Take the bottom 32 bits */
- in2 = _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffff));
- /* Multiply by mu */
- in2 = _mm_clmulepi64_si128 (mu_poly, in2, 0x00);
- /* Take the bottom 32 bits of the result */
- in2 = _mm_and_si128 (in2, _mm_set_epi64x (0, 0xffffffff));
- /* Multiply by P(x) */
- in2 = _mm_clmulepi64_si128 (mu_poly, in2, 0x01);
- /* XOR against input */
- in1 = _mm_xor_si128 (in1, in2);
- /* Take bits 32-63 as the CRC */
- in1 = _mm_srli_si128 (in1, 4);
- crc = _mm_cvtsi128_si32 (in1);
-
- return crc;
+ {
+ __m128i in2;
+ __m128i in3;
+
+ in2 =
+ _mm_and_si128 (_mm_srli_si128 (in1, 8), _mm_set_epi64x (0, 0xffffffff));
+ in3 =
+ _mm_and_si128 (_mm_srli_si128 (in1, 12), _mm_set_epi64x (0, 0xffffffff));
+ in1 = _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffffffffffff));
+ /* Multiply first 64 bits against shift96 */
+ in1 = _mm_clmulepi64_si128 (shift96_shift64, in1, 0x00);
+ /* First 32 bits go on in2 */
+ in2 =
+ _mm_xor_si128 (in2, _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffff)));
+ /* Next 64 bits go on in3 */
+ in3 = _mm_xor_si128 (in3, _mm_srli_si128 (in1, 4));
+ /* Then shift 64 bits from here */
+ in1 = _mm_clmulepi64_si128 (shift96_shift64, in2, 0x01);
+ in1 = _mm_xor_si128 (in1, in3);
+
+ /* This is the Barrett reduction */
+ /* Take the bottom 32 bits */
+ in2 = _mm_and_si128 (in1, _mm_set_epi64x (0, 0xffffffff));
+ /* Multiply by mu */
+ in2 = _mm_clmulepi64_si128 (mu_poly, in2, 0x00);
+ /* Take the bottom 32 bits of the result */
+ in2 = _mm_and_si128 (in2, _mm_set_epi64x (0, 0xffffffff));
+ /* Multiply by P(x) */
+ in2 = _mm_clmulepi64_si128 (mu_poly, in2, 0x01);
+ /* XOR against input */
+ in1 = _mm_xor_si128 (in1, in2);
+ /* Take bits 32-63 as the CRC */
+ in1 = _mm_srli_si128 (in1, 4);
+ }
+ uint32_t final_crc = _mm_cvtsi128_si32 (in1);
+
+ return final_crc;
}
#include <string.h>
#if GL_CRC_SLICE_BY_8
-#include "crc-sliceby8.h"
+# include "crc-sliceby8.h"
/*
* When we calculate the CRC32 byte-by-byte we take the checksum
uint64_t local_buf;
memcpy (&local_buf, buf, 8);
local_buf = le64toh (local_buf) ^ crc;
- crc = crc32_sliceby8_table[0][(local_buf >> 56) & 0xFF]
- ^ crc32_sliceby8_table[1][(local_buf >> 48) & 0xFF]
- ^ crc32_sliceby8_table[2][(local_buf >> 40) & 0xFF]
- ^ crc32_sliceby8_table[3][(local_buf >> 32) & 0xFF]
- ^ crc32_sliceby8_table[4][(local_buf >> 24) & 0xFF]
- ^ crc32_sliceby8_table[5][(local_buf >> 16) & 0xFF]
- ^ crc32_sliceby8_table[6][(local_buf >> 8) & 0xFF]
- ^ crc32_sliceby8_table[7][local_buf & 0xFF];
- return crc;
+ uint32_t final_crc = crc32_sliceby8_table[0][(local_buf >> 56) & 0xFF]
+ ^ crc32_sliceby8_table[1][(local_buf >> 48) & 0xFF]
+ ^ crc32_sliceby8_table[2][(local_buf >> 40) & 0xFF]
+ ^ crc32_sliceby8_table[3][(local_buf >> 32) & 0xFF]
+ ^ crc32_sliceby8_table[4][(local_buf >> 24) & 0xFF]
+ ^ crc32_sliceby8_table[5][(local_buf >> 16) & 0xFF]
+ ^ crc32_sliceby8_table[6][(local_buf >> 8) & 0xFF]
+ ^ crc32_sliceby8_table[7][local_buf & 0xFF];
+
+ return final_crc;
}
static uint32_t
size_t num_bytes)
{
uint64_t local_buf;
- size_t shift_amount;
-
memcpy (&local_buf, buf, num_bytes);
local_buf = le64toh (local_buf) ^ crc;
for (size_t i = 0; i < num_bytes; i++)
{
- shift_amount = ((num_bytes - i - 1) * 8);
+ size_t shift_amount = ((num_bytes - i - 1) * 8);
crc = crc ^ crc32_sliceby8_table[i][(local_buf >> shift_amount) & 0xFF];
}
uint32_t
crc32_update_no_xor (uint32_t crc, const char *buf, size_t len)
{
- size_t n, slice_alignment;
-#ifdef GL_CRC_X86_64_PCLMUL
+# ifdef GL_CRC_X86_64_PCLMUL
if (!pclmul_checked)
{
pclmul_enabled = (cpu_supports ("pclmul")
if (pclmul_enabled && len >= 16)
return crc32_update_no_xor_pclmul (crc, buf, len);
-#endif
+# endif
- slice_alignment = (len & (-8));
+ size_t slice_alignment = (len & (-8));
+ size_t n;
for (n = 0; n < slice_alignment; n += 8)
crc = crc32_update_no_xor_slice_by_8 (crc, buf + n);
return crc;
}
+
#else
/* Table of CRCs of all 8-bit messages. Generated by running code
uint32_t
crc32_update_no_xor (uint32_t crc, const char *buf, size_t len)
{
-#ifdef GL_CRC_X86_64_PCLMUL
+# ifdef GL_CRC_X86_64_PCLMUL
if (!pclmul_checked)
{
pclmul_enabled = (cpu_supports ("pclmul")
if (pclmul_enabled && len >= 16)
return crc32_update_no_xor_pclmul (crc, buf, len);
-#endif
+# endif
for (size_t n = 0; n < len; n++)
crc = crc32_table[(crc ^ buf[n]) & 0xff] ^ (crc >> 8);
and (to exclude an unrelated 'mcs' program on QNX 6)
"mcs --version 2>/dev/null | grep Mono >/dev/null" */
const char *argv[3];
- pid_t child;
- int fd[1];
- int exitstatus;
-
argv[0] = "mcs";
argv[1] = "--version";
argv[2] = NULL;
- child = create_pipe_in ("mcs", "mcs", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("mcs", "mcs", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
mcs_present = false;
if (child != -1)
{
/* Remove zombie process from process list, and retrieve exit
status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "mcs", false, true, true, false, NULL);
if (exitstatus != 0)
mcs_present = false;
if (mcs_present)
{
- unsigned int argc;
- const char **argv;
- const char **argp;
- pid_t child;
- int fd[1];
- FILE *fp;
- char *line[2];
- size_t linesize[2];
- size_t linelen[2];
- unsigned int l;
- int exitstatus;
-
- argc =
+ unsigned int argc =
1 + (output_is_library ? 1 : 0) + 1 + libdirs_count + libraries_count
+ (debug ? 1 : 0) + sources_count;
- argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
-
- argp = argv;
- *argp++ = "mcs";
- if (output_is_library)
- *argp++ = "-target:library";
+ const char **argv =
+ (const char **) xmalloca ((argc + 1) * sizeof (const char *));
{
- char *option = (char *) xmalloca (5 + strlen (output_file) + 1);
- memcpy (option, "-out:", 5);
- strcpy (option + 5, output_file);
- *argp++ = option;
- }
- for (unsigned int i = 0; i < libdirs_count; i++)
+ const char **argp = argv;
+ *argp++ = "mcs";
+ if (output_is_library)
+ *argp++ = "-target:library";
{
- char *option = (char *) xmalloca (5 + strlen (libdirs[i]) + 1);
- memcpy (option, "-lib:", 5);
- strcpy (option + 5, libdirs[i]);
+ char *option = (char *) xmalloca (5 + strlen (output_file) + 1);
+ memcpy (option, "-out:", 5);
+ strcpy (option + 5, output_file);
*argp++ = option;
}
- for (unsigned int i = 0; i < libraries_count; i++)
- {
- char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
- memcpy (option, "-reference:", 11);
- memcpy (option + 11, libraries[i], strlen (libraries[i]));
- strcpy (option + 11 + strlen (libraries[i]), ".dll");
- *argp++ = option;
- }
- if (debug)
- *argp++ = "-debug";
- for (unsigned int i = 0; i < sources_count; i++)
- {
- const char *source_file = sources[i];
- if (strlen (source_file) >= 10
- && memeq (source_file + strlen (source_file) - 10,
- ".resources", 10))
- {
- char *option = (char *) xmalloca (10 + strlen (source_file) + 1);
+ for (unsigned int i = 0; i < libdirs_count; i++)
+ {
+ char *option = (char *) xmalloca (5 + strlen (libdirs[i]) + 1);
+ memcpy (option, "-lib:", 5);
+ strcpy (option + 5, libdirs[i]);
+ *argp++ = option;
+ }
+ for (unsigned int i = 0; i < libraries_count; i++)
+ {
+ char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
+ memcpy (option, "-reference:", 11);
+ memcpy (option + 11, libraries[i], strlen (libraries[i]));
+ strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ *argp++ = option;
+ }
+ if (debug)
+ *argp++ = "-debug";
+ for (unsigned int i = 0; i < sources_count; i++)
+ {
+ const char *source_file = sources[i];
+ if (strlen (source_file) >= 10
+ && memeq (source_file + strlen (source_file) - 10,
+ ".resources", 10))
+ {
+ char *option = (char *) xmalloca (10 + strlen (source_file) + 1);
- memcpy (option, "-resource:", 10);
- strcpy (option + 10, source_file);
- *argp++ = option;
- }
- else
- *argp++ = source_file;
- }
- *argp = NULL;
- /* Ensure argv length was correctly calculated. */
- if (argp - argv != argc)
- abort ();
+ memcpy (option, "-resource:", 10);
+ strcpy (option + 10, source_file);
+ *argp++ = option;
+ }
+ else
+ *argp++ = source_file;
+ }
+ *argp = NULL;
+ /* Ensure argv length was correctly calculated. */
+ if (argp - argv != argc)
+ abort ();
+ }
if (verbose)
{
free (command);
}
- child = create_pipe_in ("mcs", "mcs", argv, NULL, NULL,
- NULL, false, true, true, fd);
+ int fd[1];
+ pid_t child = create_pipe_in ("mcs", "mcs", argv, NULL, NULL,
+ NULL, false, true, true, fd);
/* Read the subprocess output, copying it to stderr. Drop the last
line if it starts with "Compilation succeeded". */
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
+ char *line[2];
+ size_t linesize[2];
line[0] = NULL; linesize[0] = 0;
line[1] = NULL; linesize[1] = 0;
- l = 0;
+ unsigned int l = 0;
+ size_t linelen[2];
for (;;)
{
linelen[l] = getline (&line[l], &linesize[l], fp);
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "mcs", false, false, true, true, NULL);
for (unsigned int i = 1 + (output_is_library ? 1 : 0);
/* Test for presence of dotnet:
dotnet --list-runtimes >/dev/null 2>/dev/null
&& test -n "`dotnet --list-sdks 2>/dev/null`" */
- int exitstatus;
+ int exitstatus1;
{
const char *argv[3];
-
argv[0] = "dotnet";
argv[1] = "--list-runtimes";
argv[2] = NULL;
- exitstatus = execute ("dotnet", "dotnet", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ exitstatus1 = execute ("dotnet", "dotnet", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
}
- if (exitstatus == 0)
+ if (exitstatus1 == 0)
{
const char *argv[3];
- pid_t child;
- int fd[1];
-
argv[0] = "dotnet";
argv[1] = "--list-sdks";
argv[2] = NULL;
- child = create_pipe_in ("dotnet", "dotnet", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("dotnet", "dotnet", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child != -1)
{
/* Read the subprocess output, and test whether it is
/* Remove zombie process from process list, and retrieve exit
status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "dotnet", false, true, true, false,
NULL);
dotnet_present = (exitstatus == 0 && count > 0);
{
bool err = false;
- char *dotnet_runtime_dir;
- char *dotnet_sdk_dir;
-
/* Invoke 'dotnet --list-runtimes' and extract the .NET runtime dir
from its output. */
+ char *dotnet_runtime_dir;
{
dotnet_runtime_dir = NULL;
/* Invoke 'dotnet --list-sdks' and extract the .NET SDK dir
from its output. */
+ char *dotnet_sdk_dir;
{
dotnet_sdk_dir = NULL;
if (err)
return 1;
- struct dirent **dlls;
- int num_dlls;
- char *roslyn_dir;
- char *roslyn_bin_dir;
- char *csc;
- char *csc_converted;
- char **malloced;
- char **mallocedp;
- unsigned int argc;
- const char **argv;
- const char **argp;
- int exitstatus;
-
/* Get a list of all *.dll files in dotnet_runtime_dir. */
- num_dlls = scandir (dotnet_runtime_dir, &dlls, name_is_dll, alphasort);
+ struct dirent **dlls;
+ int num_dlls = scandir (dotnet_runtime_dir, &dlls, name_is_dll, alphasort);
if (num_dlls < 0 && errno == ENOMEM)
xalloc_die ();
if (num_dlls <= 0)
}
/* Construct the file name of the 'csc' compiler. */
- roslyn_dir = xconcatenated_filename (dotnet_sdk_dir, "Roslyn", NULL);
- roslyn_bin_dir = xconcatenated_filename (roslyn_dir, "bincore", NULL);
- csc = xconcatenated_filename (roslyn_bin_dir, "csc.dll", NULL);
- csc_converted = cygpath_w (csc);
+ char *roslyn_dir = xconcatenated_filename (dotnet_sdk_dir, "Roslyn", NULL);
+ char *roslyn_bin_dir = xconcatenated_filename (roslyn_dir, "bincore", NULL);
+ char *csc = xconcatenated_filename (roslyn_bin_dir, "csc.dll", NULL);
+ char *csc_converted = cygpath_w (csc);
/* Here, we assume that 'csc' is a native Windows program, therefore
we need to use cygpath_w. */
- malloced =
+ char **malloced =
(char **)
xmalloca ((1 + libdirs_count + sources_count * 2 + 1) * sizeof (char *));
- mallocedp = malloced;
+ char **mallocedp = malloced;
- argc =
+ unsigned int argc =
3 + 1 + 1 + libdirs_count + libraries_count
+ (optimize ? 1 : 0) + (debug ? 1 : 0) + sources_count + 1 + num_dlls;
- argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
-
- argp = argv;
- *argp++ = "dotnet";
- *argp++ = csc_converted;
- *argp++ = "-nologo";
- *argp++ = (output_is_library ? "-target:library" : "-target:exe");
+ const char **argv =
+ (const char **) xmalloca ((argc + 1) * sizeof (const char *));
{
- char *output_file_converted = cygpath_w (output_file);
- *mallocedp++ = output_file_converted;
- char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
- memcpy (option, "-out:", 5);
- strcpy (option + 5, output_file_converted);
- *argp++ = option;
- }
- for (unsigned int i = 0; i < libdirs_count; i++)
+ const char **argp = argv;
+ *argp++ = "dotnet";
+ *argp++ = csc_converted;
+ *argp++ = "-nologo";
+ *argp++ = (output_is_library ? "-target:library" : "-target:exe");
{
- const char *libdir = libdirs[i];
- char *libdir_converted = cygpath_w (libdir);
- *mallocedp++ = libdir_converted;
- char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
- memcpy (option, "-lib:", 5);
- strcpy (option + 5, libdir_converted);
+ char *output_file_converted = cygpath_w (output_file);
+ *mallocedp++ = output_file_converted;
+ char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
+ memcpy (option, "-out:", 5);
+ strcpy (option + 5, output_file_converted);
*argp++ = option;
}
- for (unsigned int i = 0; i < libraries_count; i++)
+ for (unsigned int i = 0; i < libdirs_count; i++)
+ {
+ const char *libdir = libdirs[i];
+ char *libdir_converted = cygpath_w (libdir);
+ *mallocedp++ = libdir_converted;
+ char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
+ memcpy (option, "-lib:", 5);
+ strcpy (option + 5, libdir_converted);
+ *argp++ = option;
+ }
+ for (unsigned int i = 0; i < libraries_count; i++)
+ {
+ char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
+ memcpy (option, "-reference:", 11);
+ memcpy (option + 11, libraries[i], strlen (libraries[i]));
+ strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ *argp++ = option;
+ }
+ if (optimize)
+ *argp++ = "-optimize+";
+ if (debug)
+ *argp++ = "-debug+";
+ for (unsigned int i = 0; i < sources_count; i++)
+ {
+ const char *source_file = sources[i];
+ char *source_file_converted = cygpath_w (source_file);
+ *mallocedp++ = source_file_converted;
+ if (strlen (source_file_converted) >= 10
+ && memeq ((source_file_converted
+ + strlen (source_file_converted) - 10),
+ ".resources", 10))
+ {
+ char *option =
+ (char *) xmalloc (10 + strlen (source_file_converted) + 1);
+ memcpy (option, "-resource:", 10);
+ strcpy (option + 10, source_file_converted);
+ *mallocedp++ = option;
+ *argp++ = option;
+ }
+ else
+ *argp++ = source_file_converted;
+ }
+ /* Add -lib and -reference options, so that the compiler finds
+ Object, Console, String, etc. */
{
- char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
- memcpy (option, "-reference:", 11);
- memcpy (option + 11, libraries[i], strlen (libraries[i]));
- strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ char *dotnet_runtime_dir_converted = cygpath_w (dotnet_runtime_dir);
+ *mallocedp++ = dotnet_runtime_dir_converted;
+ char *option =
+ (char *) xmalloca (5 + strlen (dotnet_runtime_dir_converted) + 1);
+ memcpy (option, "-lib:", 5);
+ strcpy (option + 5, dotnet_runtime_dir_converted);
*argp++ = option;
}
- if (optimize)
- *argp++ = "-optimize+";
- if (debug)
- *argp++ = "-debug+";
- for (unsigned int i = 0; i < sources_count; i++)
- {
- const char *source_file = sources[i];
- char *source_file_converted = cygpath_w (source_file);
- *mallocedp++ = source_file_converted;
- if (strlen (source_file_converted) >= 10
- && memeq ((source_file_converted
- + strlen (source_file_converted) - 10),
- ".resources", 10))
- {
- char *option =
- (char *) xmalloc (10 + strlen (source_file_converted) + 1);
- memcpy (option, "-resource:", 10);
- strcpy (option + 10, source_file_converted);
- *mallocedp++ = option;
- *argp++ = option;
- }
- else
- *argp++ = source_file_converted;
- }
- /* Add -lib and -reference options, so that the compiler finds
- Object, Console, String, etc. */
- {
- char *dotnet_runtime_dir_converted = cygpath_w (dotnet_runtime_dir);
- *mallocedp++ = dotnet_runtime_dir_converted;
- char *option =
- (char *) xmalloca (5 + strlen (dotnet_runtime_dir_converted) + 1);
- memcpy (option, "-lib:", 5);
- strcpy (option + 5, dotnet_runtime_dir_converted);
- *argp++ = option;
+ for (unsigned int i = 0; i < num_dlls; i++)
+ {
+ char *option = (char *) xmalloca (11 + strlen (dlls[i]->d_name) + 1);
+ memcpy (option, "-reference:", 11);
+ strcpy (option + 11, dlls[i]->d_name);
+ *argp++ = option;
+ }
+ *argp = NULL;
+ /* Ensure argv length was correctly calculated. */
+ if (argp - argv != argc)
+ abort ();
}
- for (unsigned int i = 0; i < num_dlls; i++)
- {
- char *option = (char *) xmalloca (11 + strlen (dlls[i]->d_name) + 1);
- memcpy (option, "-reference:", 11);
- strcpy (option + 11, dlls[i]->d_name);
- *argp++ = option;
- }
- *argp = NULL;
- /* Ensure argv length was correctly calculated. */
- if (argp - argv != argc)
- abort ();
if (verbose)
{
free (command);
}
- exitstatus = execute ("dotnet", "dotnet", argv, NULL, NULL,
- false, false, false, false,
- true, true, NULL);
+ int exitstatus = execute ("dotnet", "dotnet", argv, NULL, NULL,
+ false, false, false, false,
+ true, true, NULL);
for (unsigned int i = 4; i < 5 + libdirs_count + libraries_count; i++)
freea ((char *) argv[i]);
"csc -help 2>/dev/null | grep -i analyzer >/dev/null \
&& ! { csc -help 2>/dev/null | grep -i chicken > /dev/null; }" */
const char *argv[3];
- pid_t child;
- int fd[1];
- int exitstatus;
-
argv[0] = "csc";
argv[1] = "-help";
argv[2] = NULL;
- child = create_pipe_in ("csc", "csc", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("csc", "csc", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child != -1)
{
/* Read the subprocess output, and test whether it contains the
/* Remove zombie process from process list, and retrieve exit
status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "csc", false, true, true, false, NULL);
csc_present = (exitstatus == 0 && seen_analyzer && !seen_chicken);
}
if (csc_present)
{
- char **malloced;
- char **mallocedp;
- unsigned int argc;
- const char **argv;
- const char **argp;
- int exitstatus;
-
/* Here, we assume that 'csc' is a native Windows program, therefore
we need to use cygpath_w. */
- malloced =
+ char **malloced =
(char **)
xmalloca ((1 + libdirs_count + sources_count * 2) * sizeof (char *));
- mallocedp = malloced;
+ char **mallocedp = malloced;
- argc =
+ unsigned int argc =
2 + 1 + 1 + libdirs_count + libraries_count
+ (optimize ? 1 : 0) + (debug ? 1 : 0) + sources_count;
- argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
-
- argp = argv;
- *argp++ = "csc";
- *argp++ = "-nologo";
- *argp++ = (output_is_library ? "-target:library" : "-target:exe");
+ const char **argv =
+ (const char **) xmalloca ((argc + 1) * sizeof (const char *));
{
- char *output_file_converted = cygpath_w (output_file);
- *mallocedp++ = output_file_converted;
- char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
- memcpy (option, "-out:", 5);
- strcpy (option + 5, output_file_converted);
- *argp++ = option;
- }
- for (unsigned int i = 0; i < libdirs_count; i++)
+ const char **argp = argv;
+ *argp++ = "csc";
+ *argp++ = "-nologo";
+ *argp++ = (output_is_library ? "-target:library" : "-target:exe");
{
- const char *libdir = libdirs[i];
- char *libdir_converted = cygpath_w (libdir);
- *mallocedp++ = libdir_converted;
- char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
- memcpy (option, "-lib:", 5);
- strcpy (option + 5, libdir_converted);
+ char *output_file_converted = cygpath_w (output_file);
+ *mallocedp++ = output_file_converted;
+ char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
+ memcpy (option, "-out:", 5);
+ strcpy (option + 5, output_file_converted);
*argp++ = option;
}
- for (unsigned int i = 0; i < libraries_count; i++)
- {
- char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
- memcpy (option, "-reference:", 11);
- memcpy (option + 11, libraries[i], strlen (libraries[i]));
- strcpy (option + 11 + strlen (libraries[i]), ".dll");
- *argp++ = option;
- }
- if (optimize)
- *argp++ = "-optimize+";
- if (debug)
- *argp++ = "-debug+";
- for (unsigned int i = 0; i < sources_count; i++)
- {
- const char *source_file = sources[i];
- char *source_file_converted = cygpath_w (source_file);
- *mallocedp++ = source_file_converted;
- if (strlen (source_file_converted) >= 10
- && memeq ((source_file_converted
- + strlen (source_file_converted) - 10),
- ".resources", 10))
- {
- char *option =
- (char *) xmalloc (10 + strlen (source_file_converted) + 1);
- memcpy (option, "-resource:", 10);
- strcpy (option + 10, source_file_converted);
- *mallocedp++ = option;
- *argp++ = option;
- }
- else
- *argp++ = source_file_converted;
- }
- *argp = NULL;
- /* Ensure argv length was correctly calculated. */
- if (argp - argv != argc)
- abort ();
+ for (unsigned int i = 0; i < libdirs_count; i++)
+ {
+ const char *libdir = libdirs[i];
+ char *libdir_converted = cygpath_w (libdir);
+ *mallocedp++ = libdir_converted;
+ char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
+ memcpy (option, "-lib:", 5);
+ strcpy (option + 5, libdir_converted);
+ *argp++ = option;
+ }
+ for (unsigned int i = 0; i < libraries_count; i++)
+ {
+ char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
+ memcpy (option, "-reference:", 11);
+ memcpy (option + 11, libraries[i], strlen (libraries[i]));
+ strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ *argp++ = option;
+ }
+ if (optimize)
+ *argp++ = "-optimize+";
+ if (debug)
+ *argp++ = "-debug+";
+ for (unsigned int i = 0; i < sources_count; i++)
+ {
+ const char *source_file = sources[i];
+ char *source_file_converted = cygpath_w (source_file);
+ *mallocedp++ = source_file_converted;
+ if (strlen (source_file_converted) >= 10
+ && memeq ((source_file_converted
+ + strlen (source_file_converted) - 10),
+ ".resources", 10))
+ {
+ char *option =
+ (char *) xmalloc (10 + strlen (source_file_converted) + 1);
+ memcpy (option, "-resource:", 10);
+ strcpy (option + 10, source_file_converted);
+ *mallocedp++ = option;
+ *argp++ = option;
+ }
+ else
+ *argp++ = source_file_converted;
+ }
+ *argp = NULL;
+ /* Ensure argv length was correctly calculated. */
+ if (argp - argv != argc)
+ abort ();
+ }
if (verbose)
{
free (command);
}
- exitstatus = execute ("csc", "csc", argv, NULL, NULL,
- false, false, false, false,
- true, true, NULL);
+ int exitstatus = execute ("csc", "csc", argv, NULL, NULL,
+ false, false, false, false,
+ true, true, NULL);
for (unsigned int i = 3; i < 4 + libdirs_count + libraries_count; i++)
freea ((char *) argv[i]);
"csc -help >/dev/null 2>/dev/null \
&& ! { csc -help 2>/dev/null | grep -i chicken > /dev/null; }" */
const char *argv[3];
- pid_t child;
- int fd[1];
- int exitstatus;
-
argv[0] = "csc";
argv[1] = "-help";
argv[2] = NULL;
- child = create_pipe_in ("csc", "csc", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("csc", "csc", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
csc_present = false;
if (child != -1)
{
/* Remove zombie process from process list, and retrieve exit
status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "csc", false, true, true, false, NULL);
if (exitstatus != 0)
csc_present = false;
if (csc_present)
{
- char **malloced;
- char **mallocedp;
- unsigned int argc;
- const char **argv;
- const char **argp;
- int exitstatus;
-
/* Here, we assume that 'csc' is a native Windows program, therefore
we need to use cygpath_w. */
- malloced =
+ char **malloced =
(char **)
xmalloca ((1 + libdirs_count + sources_count * 2) * sizeof (char *));
- mallocedp = malloced;
+ char **mallocedp = malloced;
- argc =
+ unsigned int argc =
2 + 1 + 1 + libdirs_count + libraries_count
+ (optimize ? 1 : 0) + (debug ? 1 : 0) + sources_count;
- argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
-
- argp = argv;
- *argp++ = "csc";
- *argp++ = "-nologo";
- *argp++ = (output_is_library ? "-target:library" : "-target:exe");
+ const char **argv =
+ (const char **) xmalloca ((argc + 1) * sizeof (const char *));
{
- char *output_file_converted = cygpath_w (output_file);
- *mallocedp++ = output_file_converted;
- char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
- memcpy (option, "-out:", 5);
- strcpy (option + 5, output_file_converted);
- *argp++ = option;
- }
- for (unsigned int i = 0; i < libdirs_count; i++)
+ const char **argp = argv;
+ *argp++ = "csc";
+ *argp++ = "-nologo";
+ *argp++ = (output_is_library ? "-target:library" : "-target:exe");
{
- const char *libdir = libdirs[i];
- char *libdir_converted = cygpath_w (libdir);
- *mallocedp++ = libdir_converted;
- char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
- memcpy (option, "-lib:", 5);
- strcpy (option + 5, libdir_converted);
- *argp++ = option;
- }
- for (unsigned int i = 0; i < libraries_count; i++)
- {
- char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
- memcpy (option, "-reference:", 11);
- memcpy (option + 11, libraries[i], strlen (libraries[i]));
- strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ char *output_file_converted = cygpath_w (output_file);
+ *mallocedp++ = output_file_converted;
+ char *option = (char *) xmalloca (5 + strlen (output_file_converted) + 1);
+ memcpy (option, "-out:", 5);
+ strcpy (option + 5, output_file_converted);
*argp++ = option;
}
- if (optimize)
- *argp++ = "-optimize+";
- if (debug)
- *argp++ = "-debug+";
- for (unsigned int i = 0; i < sources_count; i++)
- {
- const char *source_file = sources[i];
- char *source_file_converted = cygpath_w (source_file);
- *mallocedp++ = source_file_converted;
- if (strlen (source_file_converted) >= 10
- && memeq ((source_file_converted
- + strlen (source_file_converted) - 10),
- ".resources", 10))
- {
- char *option =
- (char *) xmalloc (10 + strlen (source_file_converted) + 1);
- memcpy (option, "-resource:", 10);
- strcpy (option + 10, source_file_converted);
- *mallocedp++ = option;
- *argp++ = option;
- }
- else
- *argp++ = source_file_converted;
- }
- *argp = NULL;
- /* Ensure argv length was correctly calculated. */
- if (argp - argv != argc)
- abort ();
+ for (unsigned int i = 0; i < libdirs_count; i++)
+ {
+ const char *libdir = libdirs[i];
+ char *libdir_converted = cygpath_w (libdir);
+ *mallocedp++ = libdir_converted;
+ char *option = (char *) xmalloca (5 + strlen (libdir_converted) + 1);
+ memcpy (option, "-lib:", 5);
+ strcpy (option + 5, libdir_converted);
+ *argp++ = option;
+ }
+ for (unsigned int i = 0; i < libraries_count; i++)
+ {
+ char *option = (char *) xmalloca (11 + strlen (libraries[i]) + 4 + 1);
+ memcpy (option, "-reference:", 11);
+ memcpy (option + 11, libraries[i], strlen (libraries[i]));
+ strcpy (option + 11 + strlen (libraries[i]), ".dll");
+ *argp++ = option;
+ }
+ if (optimize)
+ *argp++ = "-optimize+";
+ if (debug)
+ *argp++ = "-debug+";
+ for (unsigned int i = 0; i < sources_count; i++)
+ {
+ const char *source_file = sources[i];
+ char *source_file_converted = cygpath_w (source_file);
+ *mallocedp++ = source_file_converted;
+ if (strlen (source_file_converted) >= 10
+ && memeq ((source_file_converted
+ + strlen (source_file_converted) - 10),
+ ".resources", 10))
+ {
+ char *option =
+ (char *) xmalloc (10 + strlen (source_file_converted) + 1);
+ memcpy (option, "-resource:", 10);
+ strcpy (option + 10, source_file_converted);
+ *mallocedp++ = option;
+ *argp++ = option;
+ }
+ else
+ *argp++ = source_file_converted;
+ }
+ *argp = NULL;
+ /* Ensure argv length was correctly calculated. */
+ if (argp - argv != argc)
+ abort ();
+ }
if (verbose)
{
free (command);
}
- exitstatus = execute ("csc", "csc", argv, NULL, NULL,
- false, false, false, false,
- true, true, NULL);
+ int exitstatus = execute ("csc", "csc", argv, NULL, NULL,
+ false, false, false, false,
+ true, true, NULL);
for (unsigned int i = 3; i < 4 + libdirs_count + libraries_count; i++)
freea ((char *) argv[i]);
bool output_is_library =
(strlen (output_file) >= 4
&& memeq (output_file + strlen (output_file) - 4, ".dll", 4));
+
int result;
/* First try the C# implementation specified through --enable-csharp. */
/* Test for presence of mono:
"mono --version >/dev/null 2>/dev/null" */
const char *argv[3];
- int exitstatus;
-
argv[0] = "mono";
argv[1] = "--version";
argv[2] = NULL;
- exitstatus = execute ("mono", "mono", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("mono", "mono", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
mono_present = (exitstatus == 0);
mono_tested = true;
}
if (mono_present)
{
- char *old_monopath;
- const char **argv =
- (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
- bool err;
-
/* Set MONO_PATH. */
- old_monopath = set_monopath (libdirs, libdirs_count, false, verbose);
+ char *old_monopath = set_monopath (libdirs, libdirs_count, false, verbose);
+ const char **argv =
+ (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
argv[0] = "mono";
argv[1] = assembly_path;
for (unsigned int i = 0; i <= nargs; i++)
free (command);
}
- err = executer ("mono", "mono", argv, private_data);
+ bool err = executer ("mono", "mono", argv, private_data);
+
+ freea (argv);
/* Reset MONO_PATH. */
reset_monopath (old_monopath);
- freea (argv);
-
return err;
}
else
/* Test for presence of dotnet:
"dotnet --list-runtimes >/dev/null 2>/dev/null" */
const char *argv[3];
- int exitstatus;
-
argv[0] = "dotnet";
argv[1] = "--list-runtimes";
argv[2] = NULL;
- exitstatus = execute ("dotnet", "dotnet", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("dotnet", "dotnet", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
dotnet_present = (exitstatus == 0);
dotnet_tested = true;
}
if (dotnet_present)
{
- bool err = false;
-
- char *assembly_path_converted = cygpath_w (assembly_path);
-
/* Handle the -L options.
The way this works is that we have to copy (or symlink) the DLLs into
the directory where FOO.exe resides.
{
const char *libdir = libdirs[l];
- struct dirent **dlls;
- int num_dlls;
-
/* Get a list of all *.dll files in libdir. */
- num_dlls = scandir (libdir, &dlls, name_is_dll, alphasort);
+ struct dirent **dlls;
+ int num_dlls = scandir (libdir, &dlls, name_is_dll, alphasort);
if (num_dlls < 0 && errno == ENOMEM)
xalloc_die ();
if (num_dlls <= 0)
free (assembly_dir);
}
+ bool err = false;
+
+ char *assembly_path_converted = cygpath_w (assembly_path);
+
/* Test whether alongside FOO.exe, a file FOO.runtimeconfig.json already
exists. */
char *runtimeconfig_filename =
{
const char **argv =
(const char **) xmalloca ((3 + nargs + 1) * sizeof (const char *));
-
argv[0] = "dotnet";
argv[1] = "exec";
argv[2] = assembly_path_converted;
{
char *runtimeconfig_converted =
cygpath_w (runtimeconfig);
+
const char **argv =
(const char **)
xmalloca ((5 + nargs + 1) * sizeof (const char *));
-
argv[0] = "dotnet";
argv[1] = "exec";
argv[2] = "--runtimeconfig";
/* Test for presence of clix:
"clix >/dev/null 2>/dev/null ; test $? = 1" */
const char *argv[2];
- int exitstatus;
-
argv[0] = "clix";
argv[1] = NULL;
- exitstatus = execute ("clix", "clix", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("clix", "clix", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
clix_present = (exitstatus == 0 || exitstatus == 1);
clix_tested = true;
}
/* Here, we assume that 'clix' is a native Windows program, therefore
we need to use cygpath_w. */
char *assembly_path_converted = cygpath_w (assembly_path);
- char *old_clixpath;
- const char **argv =
- (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
- bool err;
/* Set clix' PATH variable. */
- old_clixpath = set_clixpath (libdirs, libdirs_count, false, verbose);
+ char *old_clixpath = set_clixpath (libdirs, libdirs_count, false, verbose);
+ const char **argv =
+ (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
argv[0] = "clix";
argv[1] = assembly_path_converted;
for (unsigned int i = 0; i <= nargs; i++)
free (command);
}
- err = executer ("clix", "clix", argv, private_data);
+ bool err = executer ("clix", "clix", argv, private_data);
+
+ freea (argv);
/* Reset clix' PATH variable. */
reset_clixpath (old_clixpath);
- freea (argv);
free (assembly_path_converted);
return err;
bool verbose, bool quiet,
execute_fn *executer, void *private_data)
{
- unsigned int nargs;
- int result;
-
/* Count args. */
+ unsigned int nargs;
{
const char * const *arg;
;
}
+ int result;
+
/* First try the C# implementation specified through --enable-csharp. */
#if CSHARP_CHOICE_MONO
result = execute_csharp_using_mono (assembly_path, libdirs, libdirs_count,
execute_and_read_line (const char *progname,
const char *prog_path, const char * const *prog_argv)
{
- pid_t child;
- int fd[1];
- FILE *fp;
- char *line;
- size_t linesize;
- size_t linelen;
-
/* Open a pipe to the program. */
- child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
- DEV_NULL, false, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
+ DEV_NULL, false, true, false, fd);
if (child == -1)
return NULL;
/* Retrieve its result. */
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
- line = NULL; linesize = 0;
- linelen = getline (&line, &linesize, fp);
+ char *line = NULL;
+ size_t linesize = 0;
+ size_t linelen = getline (&line, &linesize, fp);
if (linelen == (size_t)(-1))
{
error (0, 0, _("%s subprocess I/O error"), progname);
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, progname, true, false, true, false, NULL);
if (exitstatus == 0)
return line;
cygpath_w (const char *filename)
{
const char *argv[4];
-
argv[0] = "cygpath";
argv[1] = "-w";
argv[2] = filename;
gl_des_is_weak_key (const char * key)
{
char work[8];
- int left, right, middle, cmp_result;
/* clear parity bits */
for (int i = 0; i < 8; ++i)
work[i] = ((unsigned char)key[i]) & 0xfe;
/* binary search in the weak key table */
- left = 0;
- right = 63;
+ int left = 0;
+ int right = 63;
while (left <= right)
{
- middle = (left + right) / 2;
+ int middle = (left + right) / 2;
- if (!(cmp_result = memcmp (work, weak_keys[middle], 8)))
+ int cmp_result = memcmp (work, weak_keys[middle], 8);
+ if (!cmp_result)
return -1;
if (cmp_result > 0)
{
const unsigned char *from = (const unsigned char *) _from;
unsigned char *to = (unsigned char *) _to;
+ uint32_t *keys = mode ? ctx->decrypt_subkeys : ctx->encrypt_subkeys;
uint32_t left, right, work;
- uint32_t *keys;
-
- keys = mode ? ctx->decrypt_subkeys : ctx->encrypt_subkeys;
READ_64BIT_DATA (from, left, right)
INITIAL_PERMUTATION (left, work, right)
addtok (dfa, PLUS);
if (dfa->lex.minrep == 0)
addtok (dfa, QMARK);
- int i;
- for (i = 1; i < dfa->lex.minrep; i++)
- {
- copytoks (dfa, tindex, ntokens);
- addtok (dfa, CAT);
- }
- for (; i < dfa->lex.maxrep; i++)
- {
- copytoks (dfa, tindex, ntokens);
- addtok (dfa, QMARK);
- addtok (dfa, CAT);
- }
+ {
+ int i;
+ for (i = 1; i < dfa->lex.minrep; i++)
+ {
+ copytoks (dfa, tindex, ntokens);
+ addtok (dfa, CAT);
+ }
+ for (; i < dfa->lex.maxrep; i++)
+ {
+ copytoks (dfa, tindex, ntokens);
+ addtok (dfa, QMARK);
+ addtok (dfa, CAT);
+ }
+ }
dfa->parse.tok = lex (dfa);
}
else if (dfa->parse.tok == REPMN)
case OR:
{
- char **new;
must *rmp = mp;
assume_nonnull (rmp);
must *lmp = mp = mp->prev;
assume_nonnull (lmp);
- idx_t j, ln, rn, n;
+ idx_t ln, rn, n;
/* Guaranteed to be. Unlikely, but ... */
if (streq (lmp->is, rmp->is))
lmp->endline = false;
}
/* Left side--easy */
- idx_t i = 0;
- while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
- ++i;
- lmp->left[i] = '\0';
+ {
+ idx_t i = 0;
+ while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
+ ++i;
+ lmp->left[i] = '\0';
+ }
/* Right side */
ln = strlen (lmp->right);
rn = strlen (rmp->right);
n = ln;
if (n > rn)
n = rn;
- for (i = 0; i < n; ++i)
- if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
- break;
- for (j = 0; j < i; ++j)
- lmp->right[j] = lmp->right[(ln - i) + j];
- lmp->right[j] = '\0';
- new = inboth (lmp->in, rmp->in);
+ {
+ idx_t i, j;
+ for (i = 0; i < n; ++i)
+ if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
+ break;
+ for (j = 0; j < i; ++j)
+ lmp->right[j] = lmp->right[(ln - i) + j];
+ lmp->right[j] = '\0';
+ }
+ char **new = inboth (lmp->in, rmp->in);
freelist (lmp->in);
free (lmp->in);
lmp->in = new;
map_device (struct di_set *dis, dev_t dev)
{
/* Find space for the probe, reusing the cache if available. */
- struct di_ent *ent;
struct di_ent *probe = dis->probe;
if (probe)
{
/* Probe for the device. */
probe->dev = dev;
- ent = hash_insert (dis->dev_map, probe);
+ struct di_ent *ent = hash_insert (dis->dev_map, probe);
if (! ent)
return NULL;
int
di_set_insert (struct di_set *dis, dev_t dev, ino_t ino)
{
- hashint i;
-
/* Map the device number to a set of inodes. */
struct hash_table *ino_set = map_device (dis, dev);
if (! ino_set)
return -1;
/* Map the inode number to a small representative I. */
- i = map_inode_number (dis, ino);
+ hashint i = map_inode_number (dis, ino);
if (i == INO_MAP_INSERT_FAILURE)
return -1;
int
di_set_lookup (struct di_set *dis, dev_t dev, ino_t ino)
{
- hashint i;
-
/* Map the device number to a set of inodes. */
struct hash_table *ino_set = map_device (dis, dev);
if (! ino_set)
return -1;
/* Map the inode number to a small representative I. */
- i = map_inode_number (dis, ino);
+ hashint i = map_inode_number (dis, ino);
if (i == INO_MAP_INSERT_FAILURE)
return -1;
dir_len (char const *file)
{
size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
- size_t length;
/* Advance prefix_length beyond important leading slashes. */
prefix_length += (prefix_length != 0
: 0));
/* Strip the basename and any redundant slashes before it. */
+ size_t length;
for (length = last_component (file) - file;
- prefix_length < length; length--)
+ prefix_length < length;
+ length--)
if (! ISSLASH (file[length - 1]))
break;
return length;
dprintf (int fd, const char *format, ...)
{
va_list args;
- off64_t ret;
-
va_start (args, format);
- ret = vdzprintf (fd, format, args);
+ off64_t ret = vdzprintf (fd, format, args);
va_end (args);
if (TYPE_MAXIMUM (off64_t) > INT_MAX && ret > INT_MAX)
dup_nothrow (int fd)
{
int dupfd;
- struct stat sbuf;
dupfd = dup (fd);
- if (dupfd == -1 && errno == ENOTSUP \
- && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ if (dupfd == -1 && errno == ENOTSUP)
{
- char path[_MAX_PATH];
-
- /* Get a path from fd */
- if (!__libc_Back_ioFHToPath (fd, path, sizeof (path)))
- dupfd = open (path, O_RDONLY);
+ struct stat sbuf;
+ if (!fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ {
+ char path[_MAX_PATH];
+
+ /* Get a path from fd */
+ if (!__libc_Back_ioFHToPath (fd, path, sizeof (path)))
+ dupfd = open (path, O_RDONLY);
+ }
}
return dupfd;
static int
ms_windows_dup2 (int fd, int desired_fd)
{
- int result;
-
/* If fd is closed, mingw hangs on dup2 (fd, fd). If fd is open,
dup2 (fd, fd) returns 0, but all further attempts to use fd in
future dup2 calls will hang. */
return -1;
}
- result = dup2_nothrow (fd, desired_fd);
+ int result = dup2_nothrow (fd, desired_fd);
if (result == 0)
result = desired_fd;
static int
klibc_dup2dirfd (int fd, int desired_fd)
{
- int tempfd;
- int dupfd;
-
- tempfd = open ("NUL", O_RDONLY);
+ int tempfd = open ("NUL", O_RDONLY);
if (tempfd < 0)
return tempfd;
{
close (desired_fd);
- dupfd = open (path, O_RDONLY);
+ int dupfd = open (path, O_RDONLY);
if (dupfd < 0)
return dupfd;
}
}
- dupfd = klibc_dup2dirfd (fd, desired_fd);
+ int dupfd = klibc_dup2dirfd (fd, desired_fd);
close (tempfd);
static int
klibc_dup2 (int fd, int desired_fd)
{
- int dupfd;
- struct stat sbuf;
+ int dupfd = dup2 (fd, desired_fd);
+ if (dupfd < 0 && errno == ENOTSUP)
+ {
+ struct stat sbuf;
+ if (!fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ {
+ close (desired_fd);
- dupfd = dup2 (fd, desired_fd);
- if (dupfd < 0 && errno == ENOTSUP \
- && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
- return klibc_dup2dirfd (fd, desired_fd);
+ return klibc_dup2dirfd (fd, desired_fd);
+ }
+ }
return dupfd;
}
int
rpl_dup2 (int fd, int desired_fd)
{
- int result;
-
#ifdef F_GETFL
/* On Linux kernels 2.6.26-2.6.29, dup2 (fd, fd) returns -EBADF.
On Cygwin 1.5.x, dup2 (1, 1) returns 0.
return fcntl (fd, F_GETFL) == -1 ? -1 : fd;
#endif
- result = dup2 (fd, desired_fd);
+ int result = dup2 (fd, desired_fd);
/* Correct an errno value on FreeBSD 6.1 and Cygwin 1.5.x. */
if (result < 0 && errno == EMFILE)
if (flags & O_CLOEXEC)
{
- int result;
close (newfd);
- result = fcntl (oldfd, F_DUPFD_CLOEXEC, newfd);
+ int result = fcntl (oldfd, F_DUPFD_CLOEXEC, newfd);
if (newfd < result)
{
close (result);
#endif
};
char base_name[SETLOCALE_NULL_MAX];
- int err;
- locale_t base_copy;
- err = setlocale_null_r (LC_CTYPE, base_name, sizeof (base_name));
- if (err)
- {
- errno = err;
- return NULL;
- }
- base_copy = newlocale (LC_ALL_MASK, base_name, NULL);
+ {
+ int err = setlocale_null_r (LC_CTYPE, base_name, sizeof (base_name));
+ if (err)
+ {
+ errno = err;
+ return NULL;
+ }
+ }
+ locale_t base_copy = newlocale (LC_ALL_MASK, base_name, NULL);
if (base_copy == NULL)
return NULL;
int category_mask = categories[i].mask;
char name[SETLOCALE_NULL_MAX];
- err = setlocale_null_r (category, name, sizeof (name));
- if (err)
- {
- errno = err;
- return NULL;
- }
+ {
+ int err = setlocale_null_r (category, name, sizeof (name));
+ if (err)
+ {
+ errno = err;
+ return NULL;
+ }
+ }
if (!streq (name, base_name))
{
locale_t copy = newlocale (category_mask, name, base_copy);
return NULL;
}
- int i;
- int err;
- for (i = 0; i < 6; i++)
+ for (int i = 0; i < 6; i++)
{
int log2_lcmask = gl_index_to_log2_lcmask (i);
+ int err;
result->category[i].name = strdup (locale->category[i].name);
if (result->category[i].name == NULL)
}
}
# endif
+
+ if (0)
+ fail_with_err:
+ {
+ while (--i >= 0)
+ {
+# if HAVE_WINDOWS_LOCALE_T
+ if (!(i == gl_log2_lcmask_to_index (gl_log2_lc_mask (LC_MESSAGES))
+ || result->category[i].is_c_locale))
+ /* Documentation:
+ <https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/free-locale> */
+ _free_locale (result->category[i].system_locale);
+# endif
+ free (result->category[i].name);
+ }
+ free (result);
+ errno = err;
+ return NULL;
+ }
}
/* Success. */
return result;
- fail_with_err:
- while (--i >= 0)
- {
-# if HAVE_WINDOWS_LOCALE_T
- if (!(i == gl_log2_lcmask_to_index (gl_log2_lc_mask (LC_MESSAGES))
- || result->category[i].is_c_locale))
- /* Documentation:
- <https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/free-locale> */
- _free_locale (result->category[i].system_locale);
-# endif
- free (result->category[i].name);
- }
- free (result);
- errno = err;
- return NULL;
#else
dzprintf (int fd, const char *format, ...)
{
va_list args;
+ va_start (args, format);
+
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
+ char *output = vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
- va_start (args, format);
- output = vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
va_end (args);
if (!output)
}
else
{
- int result;
- int saved_errno;
-
if (uid != euid)
setreuid (euid, uid);
if (gid != egid)
setregid (egid, gid);
- result = access (file, mode);
- saved_errno = errno;
+ int result = access (file, mode);
+ int saved_errno = errno;
/* Restore them. */
if (uid != euid)
correct on systems that have ACLs or the like. However, it's
better than nothing, and it is reentrant. */
- unsigned int granted;
if (uid == euid && gid == egid)
/* If we are not set-uid or set-gid, access does the same. */
return access (file, mode);
return 0; /* The file exists. */
/* Convert the file's permission bits to traditional form. */
+ unsigned int granted;
if (S_IRUSR == (4 << 6) && S_IWUSR == (2 << 6) && S_IXUSR == (1 << 6)
&& S_IRGRP == (4 << 3) && S_IWGRP == (2 << 3) && S_IXGRP == (1 << 3)
&& S_IROTH == (4 << 0) && S_IWOTH == (2 << 0) && S_IXOTH == (1 << 0))
int
main (int argc, char **argv)
{
- char *file;
- int mode;
- int err;
-
if (argc < 3)
abort ();
- file = argv[1];
- mode = atoi (argv[2]);
+ char *file = argv[1];
+ int mode = atoi (argv[2]);
- err = euidaccess (file, mode);
+ int err = euidaccess (file, mode);
printf ("%d\n", err);
if (err != 0)
error (0, errno, "%s", file);
patopts->options = options;
if (options & EXCLUDE_REGEX)
{
- int rc;
int cflags = (REG_NOSUB | REG_EXTENDED
| (options & FNM_CASEFOLD ? REG_ICASE : 0));
+ int rc;
if (! (options & FNM_LEADING_DIR))
rc = regcomp (&patopts->v.re, pattern, cflags);
else
int
execl (const char *program, const char *arg0, ...)
{
- va_list args;
-
/* The callee is not expecting a NULL argv[0]. */
if (arg0 == NULL)
{
/* Count the number of arguments (including arg0 and the trailing NULL). */
size_t count = 1;
- va_start (args, arg0);
- for (;;)
- {
- count++;
- if (va_arg (args, const char *) == NULL)
- break;
- }
- va_end (args);
+ {
+ va_list args;
+ va_start (args, arg0);
+ for (;;)
+ {
+ count++;
+ if (va_arg (args, const char *) == NULL)
+ break;
+ }
+ va_end (args);
+ }
/* Allocate the argument vector. */
const char **argv = (const char **) malloca (count * sizeof (const char *));
{
size_t i = 0;
argv[i++] = arg0;
+ va_list args;
va_start (args, arg0);
for (; i < count;)
argv[i++] = va_arg (args, const char *);
int
execle (const char *program, const char *arg0, ...)
{
- va_list args;
/* The callee is not expecting a NULL argv[0]. */
if (arg0 == NULL)
/* Count the number of arguments (including arg0 and the trailing NULL). */
size_t count = 1;
- va_start (args, arg0);
- for (;;)
- {
- count++;
- if (va_arg (args, const char *) == NULL)
- break;
- }
- va_end (args);
+ {
+ va_list args;
+ va_start (args, arg0);
+ for (;;)
+ {
+ count++;
+ if (va_arg (args, const char *) == NULL)
+ break;
+ }
+ va_end (args);
+ }
/* Allocate the argument vector. */
const char **argv = (const char **) malloca (count * sizeof (const char *));
}
/* Copy the arguments into the argument vector. */
+ va_list args;
{
size_t i = 0;
argv[i++] = arg0;
int
execlp (const char *program, const char *arg0, ...)
{
- va_list args;
-
/* The callee is not expecting a NULL argv[0]. */
if (arg0 == NULL)
{
/* Count the number of arguments (including arg0 and the trailing NULL). */
size_t count = 1;
- va_start (args, arg0);
- for (;;)
- {
- count++;
- if (va_arg (args, const char *) == NULL)
- break;
- }
- va_end (args);
+ {
+ va_list args;
+ va_start (args, arg0);
+ for (;;)
+ {
+ count++;
+ if (va_arg (args, const char *) == NULL)
+ break;
+ }
+ va_end (args);
+ }
/* Allocate the argument vector. */
const char **argv = (const char **) malloca (count * sizeof (const char *));
{
size_t i = 0;
argv[i++] = arg0;
+ va_list args;
va_start (args, arg0);
for (; i < count;)
argv[i++] = va_arg (args, const char *);
bool slave_process, bool exit_on_error,
int *termsigp)
{
- int saved_errno;
char *prog_path_to_free = NULL;
if (directory != NULL)
}
}
+ int saved_errno;
+
#if (defined _WIN32 && !defined __CYGWIN__) && EXECUTE_IMPL_AVOID_POSIX_SPAWN
/* Native Windows API. */
free (dirs[fd].name);
else
{
- size_t new_allocated;
- dir_info_t *new_dirs;
-
- new_allocated = 2 * dirs_allocated + 1;
+ size_t new_allocated = 2 * dirs_allocated + 1;
if (new_allocated <= fd)
new_allocated = fd + 1;
- new_dirs =
+ dir_info_t *new_dirs =
(dirs != NULL
? (dir_info_t *) realloc (dirs, new_allocated * sizeof *dirs)
: (dir_info_t *) malloc (new_allocated * sizeof *dirs));
static char *
get_name (char const *dir)
{
- char *cwd;
- char *result;
-
if (IS_ABSOLUTE_FILE_NAME (dir))
return strdup (dir);
/* We often encounter "."; treat it as a special case. */
- cwd = getcwd (NULL, 0);
+ char *cwd = getcwd (NULL, 0);
if (!cwd || (dir[0] == '.' && dir[1] == '\0'))
return cwd;
- result = mfile_name_concat (cwd, dir, NULL);
+ char *result = mfile_name_concat (cwd, dir, NULL);
free (cwd);
return result;
}
int
_gl_register_fd (int fd, const char *filename)
{
- struct stat statbuf;
-
assure (0 <= fd);
+
+ struct stat statbuf;
if (REPLACE_OPEN_DIRECTORY
|| (fstat (fd, &statbuf) == 0 && S_ISDIR (statbuf.st_mode)))
{
rpl_fclose (FILE *fp)
{
int saved_errno = 0;
- int fd;
- int result = 0;
/* Don't change behavior on memstreams. */
- fd = fileno (fp);
+ int fd = fileno (fp);
if (fd < 0)
return fclose_nothrow (fp);
&& fflush (fp))
saved_errno = errno;
+ int result = 0;
+
/* fclose() calls close(), but we need to also invoke all hooks that our
overridden close() function invokes. See lib/close.c. */
#if WINDOWS_SOCKETS
{
/* Mingw has no way to create an arbitrary fd. Iterate until all
file descriptors less than newfd are filled up. */
- HANDLE curr_process = GetCurrentProcess ();
- HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
- unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
- unsigned int fds_to_close_bound = 0;
- int result;
- BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
- int mode;
if (newfd < 0 || getdtablesize () <= newfd)
{
errno = EINVAL;
return -1;
}
+
+ HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
+ int mode;
if (old_handle == INVALID_HANDLE_VALUE
|| (mode = _setmode (oldfd, O_BINARY)) == -1)
{
_setmode (oldfd, mode);
flags |= mode;
+ HANDLE curr_process = GetCurrentProcess ();
+ BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
+ unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
+ unsigned int fds_to_close_bound = 0;
+ int result;
for (;;)
{
HANDLE new_handle;
#endif
{
va_list arg;
- int result = -1;
va_start (arg, action);
+
+ int result = -1;
switch (action)
{
case F_DUPFD:
break;
}
}
+
va_end (arg);
+
return result;
}
static int
klibc_dupdirfd (int fd, int minfd)
{
- int tempfd;
- int dupfd;
-
- tempfd = open ("NUL", O_RDONLY);
+ int tempfd = open ("NUL", O_RDONLY);
if (tempfd == -1)
return -1;
if (__libc_Back_ioFHToPath (fd, path, sizeof (path)))
return -1;
- dupfd = open (path, O_RDONLY);
+ int dupfd = open (path, O_RDONLY);
if (dupfd == -1)
return -1;
tempfd = dupfd;
}
- dupfd = klibc_dupdirfd (fd, minfd);
+ int dupfd = klibc_dupdirfd (fd, minfd);
close (tempfd);
klibc_fcntl (int fd, int action, /* arg */...)
{
va_list arg_ptr;
- int arg;
- struct stat sbuf;
- int result;
-
va_start (arg_ptr, action);
- arg = va_arg (arg_ptr, int);
- result = fcntl (fd, action, arg);
+
+ int arg = va_arg (arg_ptr, int);
+ int result = fcntl (fd, action, arg);
/* EPERM for F_DUPFD, ENOTSUP for others */
- if (result == -1 && (errno == EPERM || errno == ENOTSUP)
- && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
+ if (result == -1 && (errno == EPERM || errno == ENOTSUP))
{
- PLIBCFH pFH;
- unsigned fFlags;
-
- switch (action)
+ struct stat sbuf;
+ if (!fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
{
- case F_DUPFD:
- result = klibc_dupdirfd (fd, arg);
- break;
-
- case F_GETFD:
- pFH = __libc_FH (fd);
- if (!pFH)
+ switch (action)
{
- errno = EBADF;
+ case F_DUPFD:
+ result = klibc_dupdirfd (fd, arg);
break;
- }
-
- result = (pFH->fFlags & ((FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT )
- | O_NOINHERIT)) ? FD_CLOEXEC : 0;
- break;
- case F_SETFD:
- if (arg & ~FD_CLOEXEC)
- break;
-
- pFH = __libc_FH (fd);
- if (!pFH)
- {
- errno = EBADF;
+ case F_GETFD:
+ {
+ PLIBCFH pFH = __libc_FH (fd);
+ if (!pFH)
+ {
+ errno = EBADF;
+ break;
+ }
+
+ result = (pFH->fFlags & ((FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT )
+ | O_NOINHERIT)) ? FD_CLOEXEC : 0;
+ }
break;
- }
-
- fFlags = pFH->fFlags;
- if (arg & FD_CLOEXEC)
- fFlags |= (FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT) | O_NOINHERIT;
- else
- fFlags &= ~((FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT) | O_NOINHERIT);
- result = __libc_FHSetFlags (pFH, fd, fFlags);
- if (result < 0)
- {
- errno = -result;
- result = -1;
- }
- break;
+ case F_SETFD:
+ {
+ if (arg & ~FD_CLOEXEC)
+ break;
+
+ PLIBCFH pFH = __libc_FH (fd);
+ if (!pFH)
+ {
+ errno = EBADF;
+ break;
+ }
+
+ unsigned fFlags = pFH->fFlags;
+ if (arg & FD_CLOEXEC)
+ fFlags |= (FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT) | O_NOINHERIT;
+ else
+ fFlags &= ~((FD_CLOEXEC << __LIBC_FH_FDFLAGS_SHIFT) | O_NOINHERIT);
+
+ result = __libc_FHSetFlags (pFH, fd, fFlags);
+ if (result < 0)
+ {
+ errno = -result;
+ result = -1;
+ }
+ }
+ break;
- case F_GETFL:
- result = 0;
- break;
+ case F_GETFL:
+ result = 0;
+ break;
- case F_SETFL:
- if (arg != 0)
- break;
+ case F_SETFL:
+ if (arg != 0)
+ break;
- result = 0;
- break;
+ result = 0;
+ break;
- default:
- errno = EINVAL;
- break;
+ default:
+ errno = EINVAL;
+ break;
+ }
}
}
rpl_fdopen (int fd, const char *mode)
{
int saved_errno = errno;
- FILE *fp;
errno = 0;
- fp = fdopen_nothrow (fd, mode);
+ FILE *fp = fdopen_nothrow (fd, mode);
if (fp == NULL)
{
if (errno == 0)
static void
get_aclinfo (int fd, char const *name, struct aclinfo *ai, int flags)
{
- int scontext_err = ENOTSUP;
ai->buf = ai->u.__gl_acl_ch;
ssize_t acl_alloc = sizeof ai->u.__gl_acl_ch;
}
/* A security context can exist only if extended attributes do. */
+ int scontext_err = ENOTSUP;
if (flags & ACL_GET_SCONTEXT
&& (0 < ai->size || aclinfo_may_indicate_xattr (ai)))
{
{
struct acl_entry entries[NACLENTRIES];
- int count;
-
- count = (fd < 0
- ? getacl (name, NACLENTRIES, entries)
- : fgetacl (fd, NACLENTRIES, entries));
+ int count = (fd < 0
+ ? getacl (name, NACLENTRIES, entries)
+ : fgetacl (fd, NACLENTRIES, entries));
if (count < 0)
{
{
struct acl entries[NACLVENTRIES];
- int count;
/* Ignore FD, unfortunately. */
- count = acl ((char *) name, ACL_GET, NACLVENTRIES, entries);
+ int count = acl ((char *) name, ACL_GET, NACLVENTRIES, entries);
if (count < 0)
{
char aclbuf[1024];
void *acl = aclbuf;
size_t aclsize = sizeof (aclbuf);
- mode_t mode;
for (;;)
{
/* The docs say that type being 0 is equivalent to ACL_ANY, but it
is not true, in AIX 5.3. */
type.u64 = ACL_ANY;
+ mode_t mode;
if (0 <= (fd < 0
? aclx_get (name, 0, &type, aclbuf, &aclsize, &mode)
: aclx_fget (fd, 0, &type, aclbuf, &aclsize, &mode)))
{
struct acl entries[NACLENTRIES];
- int count;
/* Ignore FD, unfortunately. */
- count = acl ((char *) name, ACL_GET, NACLENTRIES, entries);
+ int count = acl ((char *) name, ACL_GET, NACLENTRIES, entries);
if (count < 0)
{
int
main (int argc, char *argv[])
{
- int i;
-
- for (i = 1; i < argc; i++)
+ for (int i = 1; i < argc; i++)
{
const char *file = argv[i];
int ret = file_is_remote (file);
void
record_file (Hash_table *ht, char const *file, struct stat const *stats)
{
- struct F_triple *ent;
-
if (ht == NULL)
return;
- ent = xmalloc (sizeof *ent);
+ struct F_triple *ent = xmalloc (sizeof *ent);
ent->name = xstrdup (file);
ent->st_ino = stats->st_ino;
ent->st_dev = stats->st_dev;
seen_file (Hash_table const *ht, char const *file,
struct stat const *stats)
{
- struct F_triple new_ent;
if (ht == NULL)
return false;
+ struct F_triple new_ent;
new_ent.name = (char *) file;
new_ent.st_ino = stats->st_ino;
new_ent.st_dev = stats->st_dev;
{
/* Try the various suffixes and see whether one of the files
with such a suffix is actually executable. */
- int failure_errno;
-
const char *directory_as_prefix =
(directory != NULL && IS_RELATIVE_FILE_NAME (progname)
? directory
: "");
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
- const char *progbasename;
-
- progbasename = progname;
+ const char *progbasename = progname;
for (const char *p = progname; *p != '\0'; p++)
if (ISSLASH (*p))
progbasename = p + 1;
#endif
/* Try all platform-dependent suffixes. */
- failure_errno = ENOENT;
+ int failure_errno = ENOENT;
for (size_t i = 0; i < sizeof (suffixes) / sizeof (suffixes[0]); i++)
{
const char *suffix = suffixes[i];
if (path_copy == NULL)
return NULL; /* errno is set here */
- int failure_errno;
- char *cp;
-
#if defined _WIN32 && !defined __CYGWIN__ /* Native Windows */
bool progname_has_dot = (strchr (progname, '.') != NULL);
#endif
- failure_errno = ENOENT;
- for (char *path_rest = path_copy; ; path_rest = cp + 1)
+ int failure_errno = ENOENT;
+ for (char *path_rest = path_copy; ; )
{
- const char *dir;
- bool last;
- char *dir_as_prefix_to_free;
- const char *dir_as_prefix;
-
/* Extract next directory in PATH. */
- dir = path_rest;
+ const char *dir = path_rest;
+ char *cp;
for (cp = path_rest; *cp != '\0' && *cp != PATH_SEPARATOR; cp++)
;
- last = (*cp == '\0');
+ bool last = (*cp == '\0');
*cp = '\0';
/* Empty PATH components designate the current directory. */
dir = ".";
/* Concatenate directory and dir. */
+ char *dir_as_prefix_to_free;
+ const char *dir_as_prefix;
if (directory != NULL && IS_RELATIVE_FILE_NAME (dir))
{
dir_as_prefix_to_free =
if (last)
break;
+
+ path_rest = cp + 1;
}
failed:
return progname;
#else
/* Unix */
- char *path;
- char *cp;
-
if (strchr (progname, '/') != NULL)
/* If progname contains a slash, it is either absolute or relative to
the current directory. PATH is not used. */
return progname;
- path = getenv ("PATH");
+ char *path = getenv ("PATH");
if (path == NULL || *path == '\0')
/* If PATH is not set, the default search path is implementation
dependent. */
/* Out of memory. */
return progname;
# endif
- for (char *path_rest = path; ; path_rest = cp + 1)
+ for (char *path_rest = path; ; )
{
- const char *dir;
- bool last;
- char *progpathname;
-
/* Extract next directory in PATH. */
- dir = path_rest;
+ const char *dir = path_rest;
+ char *cp;
for (cp = path_rest; *cp != '\0' && *cp != ':'; cp++)
;
- last = (*cp == '\0');
+ bool last = (*cp == '\0');
*cp = '\0';
/* Empty PATH components designate the current directory. */
dir = ".";
/* Concatenate dir and progname. */
+ char *progpathname;
# if !IN_FINDPROG_LGPL
progpathname = xconcatenated_filename (dir, progname, NULL);
# else
if (last)
break;
+
+ path_rest = cp + 1;
}
/* Not found in PATH. An error will be signalled at the first call. */
static BOOL
do_lock (HANDLE h, int non_blocking, int exclusive)
{
- BOOL res;
- DWORD size_lower, size_upper;
- OVERLAPPED ovlp;
- int flags = 0;
-
/* We're going to lock the whole file, so get the file size. */
- res = file_size (h, &size_lower, &size_upper);
+ DWORD size_lower, size_upper;
+ BOOL res = file_size (h, &size_lower, &size_upper);
if (!res)
return 0;
/* Start offset is 0, and also zero the remaining members of this struct. */
+ OVERLAPPED ovlp;
memset (&ovlp, 0, sizeof ovlp);
+ int flags = 0;
if (non_blocking)
flags |= LOCKFILE_FAIL_IMMEDIATELY;
if (exclusive)
static BOOL
do_unlock (HANDLE h)
{
- int res;
DWORD size_lower, size_upper;
-
- res = file_size (h, &size_lower, &size_upper);
+ int res = file_size (h, &size_lower, &size_upper);
if (!res)
return 0;
flock (int fd, int operation)
{
HANDLE h = (HANDLE) _get_osfhandle (fd);
- DWORD res;
- int non_blocking;
-
if (h == INVALID_HANDLE_VALUE)
{
errno = EBADF;
return -1;
}
- non_blocking = operation & LOCK_NB;
+ int non_blocking = operation & LOCK_NB;
operation &= ~LOCK_NB;
+ DWORD res;
switch (operation)
{
case LOCK_SH:
int
flock (int fd, int operation)
{
- int cmd, r;
- struct flock fl;
-
+ int cmd;
if (operation & LOCK_NB)
cmd = F_SETLK;
else
cmd = F_SETLKW;
operation &= ~LOCK_NB;
+ struct flock fl;
memset (&fl, 0, sizeof fl);
fl.l_whence = SEEK_SET;
/* l_start & l_len are 0, which as a special case means "whole file". */
return -1;
}
- r = fcntl (fd, cmd, &fl);
+ int r = fcntl (fd, cmd, &fl);
if (r == -1 && errno == EACCES)
errno = EAGAIN;
{
/* Here we still have MANT_BIT-0*31 bits to extract from x. */
enum { chunk_bits = MIN (31, MANT_BIT - 0 * 31) }; /* > 0, <= 31 */
- mp_limb_t d;
x *= (mp_limb_t) 1 << chunk_bits;
- d = (int) x; /* 0 <= d < 2^chunk_bits. */
+ mp_limb_t d = (int) x; /* 0 <= d < 2^chunk_bits. */
x -= d;
if (!(x >= L_(0.0) && x < L_(1.0)))
abort ();
{
/* Here we still have MANT_BIT-1*31 bits to extract from x. */
enum { chunk_bits = MIN (31, MAX (MANT_BIT - 1 * 31, 0)) }; /* > 0, <= 31 */
- mp_limb_t d;
x *= (mp_limb_t) 1 << chunk_bits;
- d = (int) x; /* 0 <= d < 2^chunk_bits. */
+ mp_limb_t d = (int) x; /* 0 <= d < 2^chunk_bits. */
x -= d;
if (!(x >= L_(0.0) && x < L_(1.0)))
abort ();
{
/* Here we still have MANT_BIT-2*31 bits to extract from x. */
enum { chunk_bits = MIN (31, MAX (MANT_BIT - 2 * 31, 0)) }; /* > 0, <= 31 */
- mp_limb_t d;
x *= (mp_limb_t) 1 << chunk_bits;
- d = (int) x; /* 0 <= d < 2^chunk_bits. */
+ mp_limb_t d = (int) x; /* 0 <= d < 2^chunk_bits. */
x -= d;
if (!(x >= L_(0.0) && x < L_(1.0)))
abort ();
{
/* Here we still have MANT_BIT-3*31 bits to extract from x. */
enum { chunk_bits = MIN (31, MAX (MANT_BIT - 3 * 31, 0)) }; /* > 0, <= 31 */
- mp_limb_t d;
x *= (mp_limb_t) 1 << chunk_bits;
- d = (int) x; /* 0 <= d < 2^chunk_bits. */
+ mp_limb_t d = (int) x; /* 0 <= d < 2^chunk_bits. */
x -= d;
if (!(x >= L_(0.0) && x < L_(1.0)))
abort ();
for (size_t k = 4; k < chunk_count; k++)
{
size_t chunk_bits = MIN (31, MANT_BIT - k * 31); /* > 0, <= 31 */
- mp_limb_t d;
x *= (mp_limb_t) 1 << chunk_bits;
- d = (int) x; /* 0 <= d < 2^chunk_bits. */
+ mp_limb_t d = (int) x; /* 0 <= d < 2^chunk_bits. */
x -= d;
if (!(x >= L_(0.0) && x < L_(1.0)))
abort ();
FILE *
rpl_fopen (const char *filename, const char *mode)
{
- int open_direction;
- int open_flags;
-#if GNULIB_FOPEN_GNU
- bool open_flags_gnu;
-# define BUF_SIZE 80
- char fdopen_mode_buf[BUF_SIZE + 1];
-#endif
-
#if defined _WIN32 && ! defined __CYGWIN__
if (streq (filename, "/dev/null"))
filename = "NUL";
#endif
/* Parse the mode. */
- open_direction = 0;
- open_flags = 0;
+ int open_direction = 0;
+ int open_flags = 0;
#if GNULIB_FOPEN_GNU
- open_flags_gnu = false;
+ bool open_flags_gnu = false;
+# define BUF_SIZE 80
+ char fdopen_mode_buf[BUF_SIZE + 1];
#endif
{
const char *p = mode;
size_t len = strlen (filename);
if (len > 0 && filename[len - 1] == '/')
{
- int fd;
- struct stat statbuf;
- FILE *fp;
-
if (open_direction != O_RDONLY)
{
errno = EISDIR;
return NULL;
}
- fd = open (filename, open_direction | open_flags,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
+ int fd = open (filename, open_direction | open_flags,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd < 0)
return NULL;
+ struct stat statbuf;
if (fstat (fd, &statbuf) >= 0 && !S_ISDIR (statbuf.st_mode))
{
close (fd);
return NULL;
}
+ FILE *fp;
# if GNULIB_FOPEN_GNU
fp = fdopen (fd, fdopen_mode_buf);
# else
#if GNULIB_FOPEN_GNU
if (open_flags_gnu)
{
- int fd;
- FILE *fp;
-
- fd = open (filename, open_direction | open_flags,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
+ int fd = open (filename, open_direction | open_flags,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd < 0)
return NULL;
- fp = fdopen (fd, fdopen_mode_buf);
+ FILE *fp = fdopen (fd, fdopen_mode_buf);
if (fp == NULL)
{
int saved_errno = errno;
forkpty (int *amaster, char *name,
const struct termios *termp, const struct winsize *winp)
{
- int master, slave, pid;
+ int master, slave;
if (openpty (&master, &slave, name, termp, winp) == -1)
return -1;
- switch (pid = fork ())
+ int pid = fork ();
+ switch (pid)
{
case -1:
close (master);
fprintf (FILE *fp, const char *format, ...)
{
va_list args;
- off64_t ret;
-
va_start (args, format);
- ret = vfzprintf (fp, format, args);
+ off64_t ret = vfzprintf (fp, format, args);
va_end (args);
if (TYPE_MAXIMUM (off64_t) > INT_MAX && ret > INT_MAX)
int
freadseek (FILE *fp, size_t offset)
{
- size_t total_buffered;
- int fd;
-
if (offset == 0)
return 0;
/* Seek over the already read and buffered input as quickly as possible,
without doing any system calls. */
- total_buffered = freadahead (fp);
+ size_t total_buffered = freadahead (fp);
/* This loop is usually executed at most twice: once for ungetc buffer (if
present) and once for the main buffer. */
while (total_buffered > 0)
}
/* Test whether the stream is seekable or not. */
- fd = fileno (fp);
+ int fd = fileno (fp);
if (fd >= 0 && lseek (fd, 0, SEEK_CUR) >= 0)
{
/* FP refers to a regular file. fseek is most efficient in this case. */
{
/* FP is a non-seekable stream, possibly not even referring to a file
descriptor. Read OFFSET bytes explicitly and discard them. */
- char buf[4096];
-
do
{
+ char buf[4096];
size_t count = (sizeof (buf) < offset ? sizeof (buf) : offset);
if (fread (buf, 1, count, fp) < count)
goto eof;
bool protect_in = false;
bool protect_out = false;
bool protect_err = false;
- int saved_errno;
switch (fileno (f))
{
f = NULL;
else
f = freopen (name, mode, f);
- saved_errno = errno;
+ int saved_errno = errno;
if (protect_err)
close (STDERR_FILENO);
if (protect_out)
FILE *
rpl_freopen (const char *filename, const char *mode, FILE *stream)
{
- FILE *result;
#if defined _WIN32 && ! defined __CYGWIN__
char const *null_device = "NUL";
if (filename && streq (filename, "/dev/null"))
errno = 0;
#endif
- result = orig_freopen (filename, mode, stream);
+ FILE *result = orig_freopen (filename, mode, stream);
if (!result)
{
DOUBLE
FUNC (DOUBLE x, int *expptr)
{
- int sign;
- int exponent;
DECL_ROUNDING
/* Test for NaN, infinity, and zero. */
return x;
}
- sign = 0;
+ int sign = 0;
if (x < 0)
{
x = - x;
BEGIN_ROUNDING ();
+ int exponent;
+
{
/* Since the exponent is an 'int', it fits in 64 bits. Therefore the
loops are executed no more than 64 times. */
Not activated on any system, because there is no way to repair FP when
the sequence of system calls fails, and library code should not call
abort(). */
- int saved_errno;
- int fd;
- int fd2;
-
- saved_errno = errno;
+ int saved_errno = errno;
fflush (fp);
- fd = fileno (fp);
- fd2 = dup (fd);
+ int fd = fileno (fp);
+ int fd2 = dup (fd);
if (fd2 >= 0)
{
close (fd);
rpl_fstatat (int fd, char const *file, struct stat *st, int flag)
{
int result = normal_fstatat (fd, file, st, flag);
- size_t len;
-
if (LSTAT_FOLLOWS_SLASHED_SYMLINK || result != 0)
return result;
- len = strlen (file);
+
+ size_t len = strlen (file);
if (flag & AT_SYMLINK_NOFOLLOW)
{
/* Fix lstat behavior. */
void
fstrcmp_free_resources (void)
{
- ptrdiff_t *buffer;
-
gl_once (keys_init_once, keys_init);
- buffer = gl_tls_get (buffer_key);
+ ptrdiff_t *buffer = gl_tls_get (buffer_key);
if (buffer != NULL)
{
gl_tls_set (buffer_key, NULL);
double
fstrcmp_bounded (const char *string1, const char *string2, double lower_bound)
{
- struct context ctxt;
size_t xvec_length = strlen (string1);
size_t yvec_length = strlen (string2);
size_t length_sum = xvec_length + yvec_length;
- ptrdiff_t fdiag_len;
- ptrdiff_t *buffer;
- uintptr_t bufmax;
-
/* short-circuit obvious comparisons */
if (xvec_length == 0 || yvec_length == 0) /* Prob: 1% */
return length_sum == 0;
/ (xvec_length + yvec_length).
*/
ptrdiff_t occ_diff[UCHAR_MAX + 1]; /* array C -> OCC(X,C) - OCC(Y,C) */
- ptrdiff_t sum;
- double dsum;
/* Determine the occurrence counts in X. */
memset (occ_diff, 0, sizeof (occ_diff));
for (ptrdiff_t i = yvec_length - 1; i >= 0; i--)
occ_diff[(unsigned char) string2[i]]--;
/* Sum up the absolute values. */
- sum = 0;
+ ptrdiff_t sum = 0;
for (ptrdiff_t i = 0; i <= UCHAR_MAX; i++)
{
ptrdiff_t d = occ_diff[i];
sum += (d >= 0 ? d : -d);
}
- dsum = sum;
+ double dsum = sum;
upper_bound = 1.0 - dsum / length_sum;
if (upper_bound < lower_bound) /* Prob: 66% */
}
/* set the info for each string. */
+ struct context ctxt;
ctxt.xvec = string1;
ctxt.yvec = string2;
ctxt.too_expensive = 4096;
/* Allocate memory for fdiag and bdiag from a thread-local pool. */
- fdiag_len = length_sum + 3;
+ ptrdiff_t fdiag_len = length_sum + 3;
gl_once (keys_init_once, keys_init);
- buffer = gl_tls_get (buffer_key);
- bufmax = (uintptr_t) gl_tls_get (bufmax_key);
+ ptrdiff_t *buffer = gl_tls_get (buffer_key);
+ uintptr_t bufmax = (uintptr_t) gl_tls_get (bufmax_key);
if (fdiag_len > bufmax)
{
/* Need more memory. */
statvfs_works (void)
{
static int statvfs_works_cache = -1;
- struct utsname name;
if (statvfs_works_cache < 0)
- statvfs_works_cache = (uname (&name) == 0
- && 0 <= strverscmp (name.release, "2.6.36"));
+ {
+ struct utsname name;
+ statvfs_works_cache = (uname (&name) == 0
+ && 0 <= strverscmp (name.release, "2.6.36"));
+ }
return statvfs_works_cache;
}
# endif
fsync (int fd)
{
HANDLE h = (HANDLE) _get_osfhandle (fd);
- DWORD err;
if (h == INVALID_HANDLE_VALUE)
{
* errors. MSDN is useless as usual - in this case it doesn't
* document the full range of errors.
*/
- err = GetLastError ();
+ DWORD err = GetLastError ();
switch (err)
{
case ERROR_ACCESS_DENIED:
gets confused by this. */
if (fp_->_flag & _IOWRT)
{
- off_t pos;
-
/* Call ftello nevertheless, for the side effects that it does on fp. */
ftello (fp);
/* Compute the file position ourselves. */
- pos = lseek (fileno (fp), (off_t) 0, SEEK_CUR);
+ off_t pos = lseek (fileno (fp), (off_t) 0, SEEK_CUR);
if (pos >= 0)
{
if ((fp_->_flag & _IONBF) == 0 && fp_->_base != NULL)
static char zero_bytes[1024];
LONG pos_hi = 0;
LONG pos_lo = SetFilePointer (tmph, (LONG) 0, &pos_hi, FILE_END);
- LONGLONG pos;
if (pos_lo == INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR)
{
CloseHandle (tmph);
return FALSE;
}
- pos = ((LONGLONG) pos_hi << 32) | (ULONGLONG) (ULONG) pos_lo;
+ LONGLONG pos = ((LONGLONG) pos_hi << 32) | (ULONGLONG) (ULONG) pos_lo;
while (pos < size)
{
DWORD written;
{
if (fts->fts_options & (FTS_TIGHT_CYCLE_CHECK | FTS_LOGICAL))
{
- struct stat const *st = ent->fts_statp;
struct Active_dir *ad = malloc (sizeof *ad);
- struct Active_dir *ad_from_table;
-
if (!ad)
return false;
+ struct stat const *st = ent->fts_statp;
ad->dev = st->st_dev;
ad->ino = st->st_ino;
ad->fts_ent = ent;
/* See if we've already encountered this directory.
This can happen when following symlinks as well as
with a corrupted directory hierarchy. */
- ad_from_table = hash_insert (fts->fts_cycle.ht, ad);
+ struct Active_dir *ad_from_table = hash_insert (fts->fts_cycle.ht, ad);
if (ad_from_table != ad)
{
if (fts->fts_options & (FTS_TIGHT_CYCLE_CHECK | FTS_LOGICAL))
{
struct Active_dir obj;
- void *found;
obj.dev = st->st_dev;
obj.ino = st->st_ino;
- found = hash_remove (fts->fts_cycle.ht, &obj);
+ void *found = hash_remove (fts->fts_cycle.ht, &obj);
if (!found)
abort ();
free (found);
register int options,
int (*compar) (FTSENT const **, FTSENT const **))
{
- register FTS *sp;
- register FTSENT *p, *root;
- register size_t nitems;
- FTSENT *parent = NULL;
- FTSENT *tmp = NULL; /* pacify gcc */
- bool defer_stat;
-
/* Options check. */
if (options & ~FTS_OPTIONMASK) {
__set_errno (EINVAL);
}
/* Allocate/initialize the stream */
- sp = calloc (1, sizeof *sp);
+ register FTS *sp = calloc (1, sizeof *sp);
if (sp == NULL)
return (NULL);
sp->fts_compar = compar;
}
/* Allocate/initialize root's parent. */
+ FTSENT *parent = NULL;
if (*argv != NULL) {
if ((parent = fts_alloc(sp, "", 0)) == NULL)
goto mem2;
without genuine i-nodes. If you specify FTS_DEFER_STAT along
with a comparison function, that function must not access any
data via the fts_statp pointer. */
- defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
+ bool defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
/* Allocate/initialize root(s). */
+ register FTSENT *root;
+ register size_t nitems;
+ FTSENT *tmp = NULL; /* pacify gcc */
for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
/* *Do* allow zero-length file names. */
size_t len = strlen(*argv);
--len;
}
- if ((p = fts_alloc(sp, *argv, len)) == NULL)
+ register FTSENT *p = fts_alloc(sp, *argv, len);
+ if (p == NULL)
goto mem3;
p->fts_level = FTS_ROOTLEVEL;
p->fts_parent = parent;
internal_function
fts_load (FTS *sp, register FTSENT *p)
{
- register size_t len;
- register char *cp;
-
/*
* Load the stream structure for the next traversal. Since we don't
* actually enter the directory until after the preorder visit, set
* place and the user can access the first node. From fts_open it's
* known that the file name will fit.
*/
- len = p->fts_pathlen = p->fts_namelen;
+ register size_t len = p->fts_pathlen = p->fts_namelen;
memmove(sp->fts_path, p->fts_name, len + 1);
- if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
+ register char *cp = strrchr(p->fts_name, '/');
+ if (cp && (cp != p->fts_name || cp[1])) {
len = strlen(++cp);
memmove(p->fts_name, cp, len + 1);
p->fts_namelen = len;
int
fts_close (FTS *sp)
{
- register FTSENT *freep, *p;
- int saved_errno = 0;
-
/*
* This still works if we haven't read anything -- the dummy structure
* points to the root list, so we step through to the end of the root
* list which has a valid parent pointer.
*/
if (sp->fts_cur) {
+ register FTSENT *p;
for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
- freep = p;
+ register FTSENT *freep = p;
p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
free(freep);
}
free(sp->fts_array);
free(sp->fts_path);
+ int saved_errno = 0;
if (ISSET(FTS_CWDFD))
{
if (0 <= sp->fts_cwd_fd)
filesystem_type (FTSENT const *p, int fd)
{
FTS *sp = p->fts_fts;
- Hash_table *h = sp->fts_leaf_optimization_works_ht;
- struct dev_type *ent;
- struct statfs fs_buf;
/* If we're not in CWDFD mode, don't bother with this optimization,
since the caller is not serious about performance. */
if (!ISSET (FTS_CWDFD))
return 0;
+ Hash_table *h = sp->fts_leaf_optimization_works_ht;
if (! h)
h = sp->fts_leaf_optimization_works_ht
= hash_initialize (DEV_TYPE_HT_INITIAL_SIZE, NULL, dev_type_hash,
dev_type_compare, free);
+
if (h)
{
struct dev_type tmp;
tmp.st_dev = p->fts_statp->st_dev;
- ent = hash_lookup (h, &tmp);
+ struct dev_type *ent = hash_lookup (h, &tmp);
if (ent)
return ent->f_type;
}
/* Look-up failed. Query directly and cache the result. */
+ struct statfs fs_buf;
if (fd < 0 || fstatfs (fd, &fs_buf) != 0)
return 0;
t2->st_dev = p->fts_statp->st_dev;
t2->f_type = fs_buf.f_type;
- ent = hash_insert (h, t2);
+ struct dev_type *ent = hash_insert (h, t2);
if (ent)
fts_assert (ent == t2);
else
FTSENT *
fts_read (register FTS *sp)
{
- register FTSENT *p, *tmp;
- register unsigned short int instr;
- register char *t;
-
/* If finished or unrecoverable error, return NULL. */
if (sp->fts_cur == NULL || ISSET(FTS_STOP))
return (NULL);
/* Set current node pointer. */
- p = sp->fts_cur;
+ register FTSENT *p = sp->fts_cur;
/* Save and zero out user instructions. */
- instr = p->fts_instr;
+ register unsigned short int instr = p->fts_instr;
p->fts_instr = FTS_NOINSTR;
/* Any type of file may be re-visited; re-stat and re-turn. */
}
/* Move to the next node on this level. */
-next: tmp = p;
+next: ;
+ register FTSENT *tmp = p;
/* If we have so many directory entries that we're reading them
in batches, and we've reached the end of the current batch,
p->fts_instr = FTS_NOINSTR;
}
-name: t = sp->fts_path + NAPPEND(p->fts_parent);
- *t++ = '/';
- memmove(t, p->fts_name, p->fts_namelen + 1);
+name: {
+ register char *t = sp->fts_path + NAPPEND(p->fts_parent);
+ *t++ = '/';
+ memmove(t, p->fts_name, p->fts_namelen + 1);
+ }
check_for_dir:
sp->fts_cur = p;
if (p->fts_info == FTS_NSOK)
FTSENT *
fts_children (register FTS *sp, int instr)
{
- register FTSENT *p;
- int fd;
-
if (instr != 0 && instr != FTS_NAMEONLY) {
__set_errno (EINVAL);
return (NULL);
}
/* Set current node pointer. */
- p = sp->fts_cur;
+ register FTSENT *p = sp->fts_cur;
/*
* Errno set to 0 so user can distinguish empty directory from
ISSET(FTS_NOCHDIR))
return (sp->fts_child = fts_build(sp, instr));
- if ((fd = diropen (sp, ".")) < 0)
+ int fd = diropen (sp, ".");
+ if (fd < 0)
return (sp->fts_child = NULL);
sp->fts_child = fts_build(sp, instr);
if (ISSET(FTS_CWDFD))
internal_function
fts_build (register FTS *sp, int type)
{
- register FTSENT *p, *head;
- register size_t nitems;
- FTSENT *tail;
- int saved_errno;
- bool descend;
- bool doadjust;
- ptrdiff_t level;
- size_t len, maxlen, new_len;
- char *cp;
- int dir_fd;
FTSENT *cur = sp->fts_cur;
bool continue_readdir = !!cur->fts_dirp;
- bool sort_by_inode = false;
- size_t max_entries;
/* When cur->fts_dirp is non-NULL, that means we should
continue calling readdir on that existing DIR* pointer
rather than opening a new one. */
+ int dir_fd;
if (continue_readdir)
{
DIR *dp = cur->fts_dirp;
function. But when no such function is specified, we can read
entries in batches that are large enough to help us with inode-
sorting, yet not so large that we risk exhausting memory. */
- max_entries = sp->fts_compar ? SIZE_MAX : FTS_MAX_READDIR_ENTRIES;
+ size_t max_entries = sp->fts_compar ? SIZE_MAX : FTS_MAX_READDIR_ENTRIES;
/*
* If we're going to need to stat anything or we want to descend
* needed sorted entries or stat information, they had better be
* checking FTS_NS on the returned nodes.
*/
+ bool descend;
if (continue_readdir)
{
/* When resuming a short readdir run, we already have
* If not changing directories set a pointer so that can just append
* each new component into the file name.
*/
- len = NAPPEND(cur);
+ size_t len = NAPPEND(cur);
+ char *cp;
if (ISSET(FTS_NOCHDIR)) {
cp = sp->fts_path + len;
*cp++ = '/';
cp = NULL;
}
len++;
- maxlen = sp->fts_pathlen - len;
+ size_t maxlen = sp->fts_pathlen - len;
- level = cur->fts_level + 1;
+ ptrdiff_t level = cur->fts_level + 1;
/* Read the directory, attaching each entry to the "link" pointer. */
- doadjust = false;
- head = NULL;
- tail = NULL;
- nitems = 0;
+ bool doadjust = false;
+ register FTSENT *head = NULL;
+ FTSENT *tail = NULL;
+ register size_t nitems = 0;
+ bool sort_by_inode = false;
while (cur->fts_dirp) {
- size_t d_namelen;
__set_errno (0);
struct dirent *dp = readdir(cur->fts_dirp);
if (dp == NULL) {
if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
continue;
- d_namelen = _D_EXACT_NAMLEN (dp);
- p = fts_alloc (sp, dp->d_name, d_namelen);
+ size_t d_namelen = _D_EXACT_NAMLEN (dp);
+ register FTSENT *p = fts_alloc (sp, dp->d_name, d_namelen);
if (!p)
goto mem1;
if (d_namelen >= maxlen) {
* errno, free up the current structure and the
* structures already allocated.
*/
-mem1: saved_errno = errno;
+mem1: ;
+ int saved_errno = errno;
free(p);
fts_lfree(head);
closedir_and_clear(cur->fts_dirp);
maxlen = sp->fts_pathlen - len;
}
- new_len = len + d_namelen;
+ size_t new_len = len + d_namelen;
if (new_len < len) {
/*
* In the unlikely event that we would end up
void
fts_cross_check (FTS const *sp)
{
- FTSENT const *ent = sp->fts_cur;
if ( ! ISSET (FTS_TIGHT_CYCLE_CHECK))
return;
+ FTSENT const *ent = sp->fts_cur;
+
Dprintf (("fts-cross-check cur=%s\n", ent->fts_path));
/* Make sure every parent dir is in the tree. */
for (FTSENT const *t = ent->fts_parent;
if (!fts_debug)
return;
I_ring const *fd_ring = &sp->fts_fd_ring;
- unsigned int i = fd_ring->ir_front;
struct devino cwd = getdevino (sp->fts_cwd_fd);
fprintf (stream, "=== %s ========== "PRINT_DEVINO"\n", msg, cwd.dev, cwd.ino);
if (i_ring_empty (fd_ring))
return;
+ unsigned int i = fd_ring->ir_front;
while (true)
{
int fd = fd_ring->ir_data[i];
internal_function
fts_stat(FTS *sp, register FTSENT *p, bool follow)
{
- struct stat *sbp = p->fts_statp;
-
if (ISSET (FTS_LOGICAL)
|| (ISSET (FTS_COMFOLLOW) && p->fts_level == FTS_ROOTLEVEL))
follow = true;
+ struct stat *sbp = p->fts_statp;
+
/*
* If doing a logical walk, or application requested FTS_FOLLOW, do
* a stat(2). If that fails, check for a nonexistent symlink. If
* 40 so don't realloc one entry at a time.
*/
if (nitems > sp->fts_nitems) {
- FTSENT **a;
-
sp->fts_nitems = nitems + 40;
+ FTSENT **a;
if (SIZE_MAX / sizeof *a < sp->fts_nitems
|| ! (a = realloc (sp->fts_array,
sp->fts_nitems * sizeof *a))) {
internal_function
fts_alloc (FTS *sp, const char *name, register size_t namelen)
{
- register FTSENT *p;
- size_t len;
-
/*
* The file name is a variable length array. Allocate the FTSENT
* structure and the file name in one chunk.
*/
- len = FLEXSIZEOF(FTSENT, fts_name, namelen + 1);
- if ((p = malloc(len)) == NULL)
+ size_t len = FLEXSIZEOF(FTSENT, fts_name, namelen + 1);
+ register FTSENT *p = malloc(len);
+ if (p == NULL)
return (NULL);
/* Copy the name and guarantee NUL termination. */
internal_function
fts_lfree (register FTSENT *head)
{
- register FTSENT *p;
int saved_errno = errno;
/* Free a linked list of structures. */
+ register FTSENT *p;
while ((p = head)) {
head = head->fts_link;
if (p->fts_dirp)
internal_function
fts_palloc (FTS *sp, size_t more)
{
- char *p;
size_t new_len = sp->fts_pathlen + more + 256;
/*
return false;
}
sp->fts_pathlen = new_len;
- p = realloc(sp->fts_path, sp->fts_pathlen);
+ char *p = realloc(sp->fts_path, sp->fts_pathlen);
if (p == NULL) {
free(sp->fts_path);
sp->fts_path = NULL;
internal_function
fts_padjust (FTS *sp, FTSENT *head)
{
- FTSENT *p;
char *addr = sp->fts_path;
/* This code looks at bit-patterns of freed pointers to
(p)->fts_path = addr; \
} while (0)
/* Adjust the current set of children. */
- for (p = sp->fts_child; p; p = p->fts_link)
+ for (FTSENT *p = sp->fts_child; p; p = p->fts_link)
ADJUST(p);
/* Adjust the rest of the tree, including the current level. */
- for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
+ for (FTSENT *p = head; p->fts_level >= FTS_ROOTLEVEL;) {
ADJUST(p);
p = p->fts_link ? p->fts_link : p->fts_parent;
}
internal_function _GL_ATTRIBUTE_PURE
fts_maxarglen (char * const *argv)
{
- size_t len, max;
+ size_t max;
- for (max = 0; *argv; ++argv)
- if ((len = strlen(*argv)) > max)
+ for (max = 0; *argv; ++argv) {
+ size_t len = strlen(*argv);
+ if (len > max)
max = len;
+ }
return (max + 1);
}
fts_safe_changedir (FTS *sp, FTSENT *p, int fd, char const *dir)
{
fts_assert (0 <= fd || dir != NULL);
- int ret;
bool is_dotdot = dir && streq (dir, "..");
- int newfd;
/* This clause handles the unusual case in which FTS_NOCHDIR
is specified, along with FTS_CWDFD. In that case, there is
}
}
- newfd = fd;
+ int newfd = fd;
if (fd < 0 && (newfd = diropen (sp, dir)) < 0)
return -1;
name "..", O_NOFOLLOW can't help. In general, when the target is
not "..", diropen's use of O_NOFOLLOW ensures we don't mistakenly
follow a symlink, so we can avoid the expense of this fstat. */
+ int ret;
if (ISSET(FTS_LOGICAL) || ! HAVE_WORKING_O_NOFOLLOW
|| (dir && streq (dir, "..")))
{
fzprintf (FILE *fp, const char *format, ...)
{
va_list args;
+ va_start (args, format);
+
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
+ char *output = vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
- va_start (args, format);
- output = vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
va_end (args);
if (!output)
gc_cipher_open (Gc_cipher alg, Gc_cipher_mode mode,
gc_cipher_handle * outhandle)
{
- _gc_cipher_ctx *ctx;
- Gc_rc rc = GC_OK;
-
- ctx = calloc (1, sizeof (*ctx));
+ _gc_cipher_ctx *ctx = calloc (1, sizeof (*ctx));
if (!ctx)
return GC_MALLOC_ERROR;
ctx->alg = alg;
ctx->mode = mode;
+ Gc_rc rc = GC_OK;
switch (alg)
{
#if GNULIB_GC_ARCTWO
case GC_AES192:
case GC_AES256:
{
- rijndael_rc rc;
char keyMaterial[RIJNDAEL_MAX_KEY_SIZE + 1];
for (size_t i = 0; i < keylen; i++)
sprintf (&keyMaterial[2 * i], "%02x", key[i] & 0xFFU);
- rc = rijndaelMakeKey (&ctx->aesEncKey, RIJNDAEL_DIR_ENCRYPT,
- keylen * 8, keyMaterial);
- if (rc < 0)
- return GC_INVALID_CIPHER;
-
- rc = rijndaelMakeKey (&ctx->aesDecKey, RIJNDAEL_DIR_DECRYPT,
- keylen * 8, keyMaterial);
- if (rc < 0)
- return GC_INVALID_CIPHER;
-
- rc = rijndaelCipherInit (&ctx->aesContext, RIJNDAEL_MODE_ECB, NULL);
- if (rc < 0)
- return GC_INVALID_CIPHER;
+ {
+ rijndael_rc rc =
+ rijndaelMakeKey (&ctx->aesEncKey, RIJNDAEL_DIR_ENCRYPT,
+ keylen * 8, keyMaterial);
+ if (rc < 0)
+ return GC_INVALID_CIPHER;
+ }
+ {
+ rijndael_rc rc =
+ rijndaelMakeKey (&ctx->aesDecKey, RIJNDAEL_DIR_DECRYPT,
+ keylen * 8, keyMaterial);
+ if (rc < 0)
+ return GC_INVALID_CIPHER;
+ }
+ {
+ rijndael_rc rc =
+ rijndaelCipherInit (&ctx->aesContext, RIJNDAEL_MODE_ECB, NULL);
+ if (rc < 0)
+ return GC_INVALID_CIPHER;
+ }
}
break;
#endif
case GC_CBC:
{
- rijndael_rc rc;
char ivMaterial[2 * RIJNDAEL_MAX_IV_SIZE + 1];
-
for (size_t i = 0; i < ivlen; i++)
sprintf (&ivMaterial[2 * i], "%02x", iv[i] & 0xFFU);
- rc = rijndaelCipherInit (&ctx->aesContext, RIJNDAEL_MODE_CBC,
- ivMaterial);
+ rijndael_rc rc =
+ rijndaelCipherInit (&ctx->aesContext, RIJNDAEL_MODE_CBC,
+ ivMaterial);
if (rc < 0)
return GC_INVALID_CIPHER;
}
case GC_AES192:
case GC_AES256:
{
- int nblocks;
-
- nblocks = rijndaelBlockEncrypt (&ctx->aesContext, &ctx->aesEncKey,
- data, 8 * len, data);
+ int nblocks =
+ rijndaelBlockEncrypt (&ctx->aesContext, &ctx->aesEncKey,
+ data, 8 * len, data);
if (nblocks < 0)
return GC_INVALID_CIPHER;
}
case GC_AES192:
case GC_AES256:
{
- int nblocks;
-
- nblocks = rijndaelBlockDecrypt (&ctx->aesContext, &ctx->aesDecKey,
- data, 8 * len, data);
+ int nblocks =
+ rijndaelBlockDecrypt (&ctx->aesContext, &ctx->aesDecKey,
+ data, 8 * len, data);
if (nblocks < 0)
return GC_INVALID_CIPHER;
}
Gc_rc
gc_hash_open (Gc_hash hash, Gc_hash_mode mode, gc_hash_handle * outhandle)
{
- _gc_hash_ctx *ctx;
- Gc_rc rc = GC_OK;
-
if (mode != 0)
return GC_INVALID_HASH;
- ctx = calloc (1, sizeof (*ctx));
+ _gc_hash_ctx *ctx = calloc (1, sizeof (*ctx));
if (!ctx)
return GC_MALLOC_ERROR;
ctx->alg = hash;
ctx->mode = mode;
+ Gc_rc rc = GC_OK;
switch (hash)
{
#if GNULIB_GC_MD2
gc_hash_clone (gc_hash_handle handle, gc_hash_handle * outhandle)
{
_gc_hash_ctx *in = handle;
- _gc_hash_ctx *out;
-
- out = calloc (1, sizeof (*out));
+ _gc_hash_ctx *out = calloc (1, sizeof (*out));
if (!out)
return GC_MALLOC_ERROR;
Gc_rc
gc_init (void)
{
- gcry_error_t err;
-
- err = gcry_control (GCRYCTL_ANY_INITIALIZATION_P);
- if (err == GPG_ERR_NO_ERROR)
+ if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P) == GPG_ERR_NO_ERROR)
{
if (gcry_control (GCRYCTL_DISABLE_SECMEM, NULL, 0))
return GC_INIT_ERROR;
if (gcry_check_version (MIN_GCRYPT_VERSION) == NULL)
return GC_INIT_ERROR;
- err = gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL, 0);
- if (err != GPG_ERR_NO_ERROR)
+ if (gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL, 0)
+ != GPG_ERR_NO_ERROR)
return GC_INIT_ERROR;
}
gc_cipher_open (Gc_cipher alg, Gc_cipher_mode mode,
gc_cipher_handle * outhandle)
{
- int gcryalg, gcrymode;
- gcry_error_t err;
-
+ int gcryalg;
switch (alg)
{
case GC_AES128:
return GC_INVALID_CIPHER;
}
+ int gcrymode;
switch (mode)
{
case GC_ECB:
return GC_INVALID_CIPHER;
}
- err = gcry_cipher_open ((gcry_cipher_hd_t *) outhandle,
- gcryalg, gcrymode, 0);
+ gcry_error_t err = gcry_cipher_open ((gcry_cipher_hd_t *) outhandle,
+ gcryalg, gcrymode, 0);
if (gcry_err_code (err))
return GC_INVALID_CIPHER;
Gc_rc
gc_cipher_setkey (gc_cipher_handle handle, size_t keylen, const char *key)
{
- gcry_error_t err;
-
- err = gcry_cipher_setkey ((gcry_cipher_hd_t) handle, key, keylen);
+ gcry_error_t err = gcry_cipher_setkey ((gcry_cipher_hd_t) handle, key, keylen);
if (gcry_err_code (err))
return GC_INVALID_CIPHER;
Gc_rc
gc_cipher_setiv (gc_cipher_handle handle, size_t ivlen, const char *iv)
{
- gcry_error_t err;
-
- err = gcry_cipher_setiv ((gcry_cipher_hd_t) handle, iv, ivlen);
+ gcry_error_t err = gcry_cipher_setiv ((gcry_cipher_hd_t) handle, iv, ivlen);
if (gcry_err_code (err))
return GC_INVALID_CIPHER;
Gc_rc
gc_hash_open (Gc_hash hash, Gc_hash_mode mode, gc_hash_handle * outhandle)
{
- _gc_hash_ctx *ctx;
- int gcryalg = 0, gcrymode = 0;
- gcry_error_t err;
- Gc_rc rc = GC_OK;
-
- ctx = calloc (1, sizeof (*ctx));
+ _gc_hash_ctx *ctx = calloc (1, sizeof (*ctx));
if (!ctx)
return GC_MALLOC_ERROR;
ctx->alg = hash;
ctx->mode = mode;
+ Gc_rc rc = GC_OK;
+
+ int gcryalg = 0;
switch (hash)
{
#if GNULIB_GC_MD2
rc = GC_INVALID_HASH;
}
+ int gcrymode = 0;
switch (mode)
{
case GC_NULL:
if (rc == GC_OK && gcryalg != GCRY_MD_NONE)
{
- err = gcry_md_open (&ctx->gch, gcryalg, gcrymode);
+ gcry_error_t err = gcry_md_open (&ctx->gch, gcryalg, gcrymode);
if (gcry_err_code (err))
rc = GC_INVALID_HASH;
}
gc_hash_clone (gc_hash_handle handle, gc_hash_handle * outhandle)
{
_gc_hash_ctx *in = handle;
- _gc_hash_ctx *out;
- int err;
+ _gc_hash_ctx *out = calloc (1, sizeof (*out));
- out = calloc (1, sizeof (*out));
if (!out)
return GC_MALLOC_ERROR;
memcpy (out, in, sizeof (*out));
- err = gcry_md_copy (&out->gch, in->gch);
+ int err = gcry_md_copy (&out->gch, in->gch);
if (err)
{
free (out);
gc_hash_read (gc_hash_handle handle)
{
_gc_hash_ctx *ctx = handle;
- const char *digest;
+ const char *digest;
#if GNULIB_GC_MD2
if (ctx->alg == GC_MD2)
{
gc_md4 (const void *in, size_t inlen, void *resbuf)
{
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_MD4);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_MD4_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_MD4, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_MD4, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_MD4);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_MD4);
if (p == NULL)
{
gcry_md_close (hd);
gc_md5 (const void *in, size_t inlen, void *resbuf)
{
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_MD5);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_MD5_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_MD5, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_MD5, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_MD5);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_MD5);
if (p == NULL)
{
gcry_md_close (hd);
gc_sha1 (const void *in, size_t inlen, void *resbuf)
{
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_SHA1);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_SHA1_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_SHA1, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_SHA1, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_SHA1);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_SHA1);
if (p == NULL)
{
gcry_md_close (hd);
gc_sha256 (const void *in, size_t inlen, void *resbuf)
{
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_SHA256);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_SHA256_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_SHA256, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_SHA256, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_SHA256);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_SHA256);
if (p == NULL)
{
gcry_md_close (hd);
gc_sha512 (const void *in, size_t inlen, void *resbuf)
{
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_SHA512);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_SHA512_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_SHA512, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_SHA512, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_SHA512);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_SHA512);
if (p == NULL)
{
gcry_md_close (hd);
return GC_OK;
# else
size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_SM3);
- gcry_md_hd_t hd;
- gpg_error_t err;
- unsigned char *p;
-
assert (outlen == GC_SM3_DIGEST_SIZE);
- err = gcry_md_open (&hd, GCRY_MD_SM3, 0);
+ gcry_md_hd_t hd;
+ gpg_error_t err = gcry_md_open (&hd, GCRY_MD_SM3, 0);
if (err != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
gcry_md_write (hd, in, inlen);
- p = gcry_md_read (hd, GCRY_MD_SM3);
+ unsigned char *p = gcry_md_read (hd, GCRY_MD_SM3);
if (p == NULL)
{
gcry_md_close (hd);
const void *in, size_t inlen, char *resbuf)
{
size_t hlen = gcry_md_get_algo_dlen (GCRY_MD_MD5);
- gcry_md_hd_t mdh;
- unsigned char *hash;
- gpg_error_t err;
-
assert (hlen == GC_MD5_DIGEST_SIZE);
- err = gcry_md_open (&mdh, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC);
- if (err != GPG_ERR_NO_ERROR)
+ gcry_md_hd_t mdh;
+ if (gcry_md_open (&mdh, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC) != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
- err = gcry_md_setkey (mdh, key, keylen);
- if (err != GPG_ERR_NO_ERROR)
+ if (gcry_md_setkey (mdh, key, keylen) != GPG_ERR_NO_ERROR)
{
gcry_md_close (mdh);
return GC_INVALID_HASH;
gcry_md_write (mdh, in, inlen);
- hash = gcry_md_read (mdh, GCRY_MD_MD5);
+ unsigned char *hash = gcry_md_read (mdh, GCRY_MD_MD5);
if (hash == NULL)
{
gcry_md_close (mdh);
const void *in, size_t inlen, char *resbuf)
{
size_t hlen = gcry_md_get_algo_dlen (GCRY_MD_SHA1);
- gcry_md_hd_t mdh;
- unsigned char *hash;
- gpg_error_t err;
-
assert (hlen == GC_SHA1_DIGEST_SIZE);
- err = gcry_md_open (&mdh, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
- if (err != GPG_ERR_NO_ERROR)
+ gcry_md_hd_t mdh;
+ if (gcry_md_open (&mdh, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC) != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
- err = gcry_md_setkey (mdh, key, keylen);
- if (err != GPG_ERR_NO_ERROR)
+ if (gcry_md_setkey (mdh, key, keylen) != GPG_ERR_NO_ERROR)
{
gcry_md_close (mdh);
return GC_INVALID_HASH;
gcry_md_write (mdh, in, inlen);
- hash = gcry_md_read (mdh, GCRY_MD_SHA1);
+ unsigned char *hash = gcry_md_read (mdh, GCRY_MD_SHA1);
if (hash == NULL)
{
gcry_md_close (mdh);
const void *in, size_t inlen, char *resbuf)
{
size_t hlen = gcry_md_get_algo_dlen (GCRY_MD_SHA256);
- gcry_md_hd_t mdh;
- unsigned char *hash;
- gpg_error_t err;
-
assert (hlen == GC_SHA256_DIGEST_SIZE);
- err = gcry_md_open (&mdh, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
- if (err != GPG_ERR_NO_ERROR)
+ gcry_md_hd_t mdh;
+ if (gcry_md_open (&mdh, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC) != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
- err = gcry_md_setkey (mdh, key, keylen);
- if (err != GPG_ERR_NO_ERROR)
+ if (gcry_md_setkey (mdh, key, keylen) != GPG_ERR_NO_ERROR)
{
gcry_md_close (mdh);
return GC_INVALID_HASH;
gcry_md_write (mdh, in, inlen);
- hash = gcry_md_read (mdh, GCRY_MD_SHA256);
+ unsigned char *hash = gcry_md_read (mdh, GCRY_MD_SHA256);
if (hash == NULL)
{
gcry_md_close (mdh);
const void *in, size_t inlen, char *resbuf)
{
size_t hlen = gcry_md_get_algo_dlen (GCRY_MD_SHA512);
- gcry_md_hd_t mdh;
- unsigned char *hash;
- gpg_error_t err;
-
assert (hlen == GC_SHA512_DIGEST_SIZE);
- err = gcry_md_open (&mdh, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC);
- if (err != GPG_ERR_NO_ERROR)
+ gcry_md_hd_t mdh;
+ if (gcry_md_open (&mdh, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC) != GPG_ERR_NO_ERROR)
return GC_INVALID_HASH;
- err = gcry_md_setkey (mdh, key, keylen);
- if (err != GPG_ERR_NO_ERROR)
+ if (gcry_md_setkey (mdh, key, keylen) != GPG_ERR_NO_ERROR)
{
gcry_md_close (mdh);
return GC_INVALID_HASH;
gcry_md_write (mdh, in, inlen);
- hash = gcry_md_read (mdh, GCRY_MD_SHA512);
+ unsigned char *hash = gcry_md_read (mdh, GCRY_MD_SHA512);
if (hash == NULL)
{
gcry_md_close (mdh);
unsigned int c,
char *DK, size_t dkLen)
{
- char U[GC_MAX_DIGEST_SIZE];
- char T[GC_MAX_DIGEST_SIZE];
- unsigned int l;
- unsigned int r;
- int rc;
- char *tmp;
- size_t tmplen = Slen + 4;
-
if (c == 0)
return GC_PKCS5_INVALID_ITERATION_COUNT;
if (dkLen > 4294967295U)
return GC_PKCS5_DERIVED_KEY_TOO_LONG;
- l = ((dkLen - 1) / hLen) + 1;
- r = dkLen - (l - 1) * hLen;
+ unsigned int l = ((dkLen - 1) / hLen) + 1;
+ unsigned int r = dkLen - (l - 1) * hLen;
- tmp = malloc (tmplen);
+ size_t tmplen = Slen + 4;
+ char *tmp = malloc (tmplen);
if (tmp == NULL)
return GC_MALLOC_ERROR;
memcpy (tmp, S, Slen);
+ char U[GC_MAX_DIGEST_SIZE];
+ char T[GC_MAX_DIGEST_SIZE];
+ int rc;
for (unsigned int i = 1; i <= l; i++)
{
memset (T, 0, hLen);
static void
fill_attributes (const char *unicodedata_filename)
{
- unsigned int j;
- FILE *stream;
char field0[FIELDLEN];
char field1[FIELDLEN];
char field2[FIELDLEN];
for (unsigned int i = 0; i < 0x110000; i++)
unicode_attributes[i].name = NULL;
- stream = fopen (unicodedata_filename, "r");
+ FILE *stream = fopen (unicodedata_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", unicodedata_filename);
exit (1);
}
field1[strlen (field1) - 7] = '\0';
- j = strtoul (field0, NULL, 16);
+ unsigned int j = strtoul (field0, NULL, 16);
for (; i <= j; i++)
fill_attribute (i, field1+1, field2, field3, field4, field5,
field6, field7, field8, field9, field10,
static void
debug_output_predicate (const char *filename, bool (*predicate) (unsigned int))
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
if (predicate (ch))
{
unsigned int first = ch;
- unsigned int last;
while (ch + 1 < 0x110000 && predicate (ch + 1))
ch++;
- last = ch;
+ unsigned int last = ch;
if (first < last)
fprintf (stream, "0x%04X..0x%04X\n", first, last);
else
static void
output_predicate_test (const char *filename, bool (*predicate) (unsigned int), const char *expression)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "#include \"test-predicate-part1.h\"\n");
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
if (predicate (ch))
{
unsigned int first = ch;
- unsigned int last;
while (ch + 1 < 0x110000 && predicate (ch + 1))
ch++;
- last = ch;
+ unsigned int last = ch;
if (need_comma)
fprintf (stream, ",\n");
fprintf (stream, " { 0x%04X, 0x%04X }", first, last);
static void
output_predicate (const char *filename, bool (*predicate) (unsigned int), const char *name, const char *comment, const char *version)
{
- FILE *stream;
- struct predicate_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
|| streq (filename, "uniwidth/width2.h"));
fprintf (stream, "\n");
+ struct predicate_table t;
t.p = 4; /* or: 5 */
t.q = 7; /* or: 6 */
predicate_table_init (&t);
predicate_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 1) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 1) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
output_category (const char *filename, const char *version)
{
- FILE *stream;
- struct category_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
- uint16_t *level3_packed;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, true);
fprintf (stream, "\n");
+ struct category_table t;
t.p = 7;
t.q = 9;
category_table_init (&t);
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value;
- unsigned int log2_value;
-
if (is_category_Cs (ch))
value = UC_CATEGORY_MASK_Cs;
else if (unicode_attributes[ch].name != NULL)
/* Now value should contain exactly one bit. */
assert (value != 0 && (value & (value - 1)) == 0);
+ unsigned int log2_value;
for (log2_value = 0; value > 1; value >>= 1, log2_value++);
assert (log2_value <= 0x1f);
category_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
/* To make the level2 values fit in 16 bits, we use 'unsigned short'
instead of 'short' and add 1 to each value. */
if (offset == 0)
fprintf (stream, " },\n");
/* Pack the level3 array. Each entry needs 5 bits only. Use 16-bit units,
not 32-bit units, in order to make the lookup function easier. */
- level3_packed =
+ uint16_t *level3_packed =
(uint16_t *)
calloc ((t.level3_size << t.p) * 5 / 16 + 1, sizeof (uint16_t));
for (unsigned int i = 0; i < t.level3_size << t.p; i++)
static void
output_combclass (const char *filename, const char *version)
{
- FILE *stream;
- struct combclass_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, true);
fprintf (stream, "\n");
+ struct combclass_table t;
t.p = 7;
t.q = 9;
combclass_table_init (&t);
combclass_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
output_bidi_category (const char *filename, const char *version)
{
- FILE *stream;
- struct bidi_category_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
- uint16_t *level3_packed;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, true);
fprintf (stream, "\n");
+ struct bidi_category_table t;
t.p = 7;
t.q = 9;
bidi_category_table_init (&t);
bidi_category_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, " },\n");
/* Pack the level3 array. Each entry needs 5 bits only. Use 16-bit units,
not 32-bit units, in order to make the lookup function easier. */
- level3_packed =
+ uint16_t *level3_packed =
(uint16_t *)
calloc ((t.level3_size << t.p) * 5 / 16 + 1, sizeof (uint16_t));
for (unsigned int i = 0; i < t.level3_size << t.p; i++)
static void
output_decimal_digit_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value = get_decdigit_value (ch);
static void
output_decimal_digit (const char *filename, const char *version)
{
- FILE *stream;
- struct decdigit_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct decdigit_table t;
t.p = 7;
t.q = 9;
decdigit_table_init (&t);
decdigit_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
output_digit_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value = get_digit_value (ch);
static void
output_digit (const char *filename, const char *version)
{
- FILE *stream;
- struct decdigit_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct decdigit_table t;
t.p = 7;
t.q = 9;
decdigit_table_init (&t);
decdigit_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
output_numeric_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
uc_fraction_t value = get_numeric_value (ch);
static void
output_numeric (const char *filename, const char *version)
{
- FILE *stream;
- uc_fraction_t fractions[160];
- unsigned int nfractions;
- struct numeric_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
- uint16_t *level3_packed;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "\n");
/* Create table of occurring fractions. */
- nfractions = 0;
+ uc_fraction_t fractions[160];
+ unsigned int nfractions = 0;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
uc_fraction_t value = get_numeric_value (ch);
}
fprintf (stream, "};\n");
+ struct numeric_table t;
t.p = 7;
t.q = 9;
numeric_table_init (&t);
numeric_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, " },\n");
/* Pack the level3 array. Each entry needs 8 bits only. Use 16-bit units,
not 32-bit units, in order to make the lookup function easier. */
- level3_packed =
+ uint16_t *level3_packed =
(uint16_t *)
calloc ((t.level3_size << t.p) * 8 / 16 + 1, sizeof (uint16_t));
for (unsigned int i = 0; i < t.level3_size << t.p; i++)
static void
fill_mirror (const char *bidimirroring_filename)
{
- FILE *stream;
- char field0[FIELDLEN];
- char field1[FIELDLEN];
- char field2[FIELDLEN];
- int lineno = 0;
-
- stream = fopen (bidimirroring_filename, "r");
+ FILE *stream = fopen (bidimirroring_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", bidimirroring_filename);
exit (1);
}
+ char field0[FIELDLEN];
+ char field1[FIELDLEN];
+ char field2[FIELDLEN];
+ int lineno = 0;
+
mirror_pairs_count = 0;
for (;;)
{
- int n;
- int c;
- unsigned int uc1;
- unsigned int uc2;
-
lineno++;
- c = getc (stream);
+ int c = getc (stream);
if (c == EOF)
break;
if (c == '\n')
continue;
}
ungetc (c, stream);
- n = getfield (stream, field0, ';');
+ int n = getfield (stream, field0, ';');
do c = getc (stream); while (c == ' ');
ungetc (c, stream);
n += getfield (stream, field1, '#');
while (strlen (field1) > 0 && field1[strlen (field1) - 1] == ' ')
field1[strlen (field1) - 1] = '\0';
/* The line should contain two characters. */
- uc1 = strtoul (field0, NULL, 16);
- uc2 = strtoul (field1, NULL, 16);
+ unsigned int uc1 = strtoul (field0, NULL, 16);
+ unsigned int uc2 = strtoul (field1, NULL, 16);
if (uc1 == 0 || uc2 == 0 || uc1 == uc2)
{
fprintf (stderr, "parse error at '%s':%d\n",
static int
get_mirror_value (unsigned int ch)
{
- bool mirrored;
- unsigned int mirror_char;
+ bool mirrored = (unicode_attributes[ch].name != NULL
+ && unicode_attributes[ch].mirrored);
- mirrored = (unicode_attributes[ch].name != NULL
- && unicode_attributes[ch].mirrored);
- mirror_char = 0xfffd;
+ unsigned int mirror_char = 0xfffd;
for (unsigned int i = 0; i < mirror_pairs_count; i++)
if (ch == mirror_pairs[i].uc[0])
{
static void
output_mirror (const char *filename, const char *version)
{
- FILE *stream;
- struct mirror_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct mirror_table t;
t.p = 7;
t.q = 9;
mirror_table_init (&t);
mirror_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
fill_properties (const char *proplist_filename)
{
- FILE *stream;
-
- stream = fopen (proplist_filename, "r");
+ FILE *stream = fopen (proplist_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", proplist_filename);
for (;;)
{
char buf[200+1];
- unsigned int i1, i2;
- char padding[200+1];
- char propname[200+1];
- char rest_of_line[200+1];
- unsigned int propcode;
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i1, i2;
+ char padding[200+1];
+ char propname[200+1];
+ char rest_of_line[200+1];
if (sscanf (buf, "%X..%X%[ ;]%[^ #]%200s", &i1, &i2, padding, propname, rest_of_line) != 5)
{
if (sscanf (buf, "%X%[ ;]%[^ #]%200s", &i1, padding, propname, rest_of_line) != 4)
}
i2 = i1;
}
+ unsigned int propcode;
#define PROP(name,code) \
if (streq (propname, name)) propcode = code; else
/* PropList.txt */
if (streq (propname, "InCB;"))
{
char valuename[200+1];
- unsigned int valuecode;
if (sscanf (rest_of_line, "%[^ #]", valuename) != 1)
{
exit (1);
}
+ unsigned int valuecode;
if (streq (valuename, "None"))
valuecode = UC_INDIC_CONJUNCT_BREAK_NONE;
else if (streq (valuename, "Consonant"))
static void
fill_property30 (char array[0x110000], const char *proplist_filename, const char *property_name)
{
- FILE *stream;
- char buf[100+1];
for (unsigned int i = 0; i < 0x110000; i++)
array[i] = 0;
- stream = fopen (proplist_filename, "r");
+ FILE *stream = fopen (proplist_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", proplist_filename);
}
/* Search for the "Property dump for: ..." line. */
+ char buf[100+1];
do
{
if (fscanf (stream, "%100[^\n]\n", buf) < 1)
for (;;)
{
- unsigned int i1, i2;
-
if (fscanf (stream, "%100[^\n]\n", buf) < 1)
break;
if (buf[0] == '*')
break;
+ unsigned int i1, i2;
if (strlen (buf) >= 10 && buf[4] == '.' && buf[5] == '.')
{
if (sscanf (buf, "%4X..%4X", &i1, &i2) < 2)
static void
output_indic_conjunct_break_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value = unicode_indic_conjunct_break[ch];
static void
output_indic_conjunct_break (const char *filename, const char *version)
{
- FILE *stream;
- struct indic_conjunct_break_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct indic_conjunct_break_table t;
t.p = 6; /* or 5 */
t.q = 4; /* or 5 */
indic_conjunct_break_table_init (&t);
indic_conjunct_break_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
fill_arabicshaping (const char *arabicshaping_filename)
{
- FILE *stream;
- int lineno;
-
- stream = fopen (arabicshaping_filename, "r");
+ FILE *stream = fopen (arabicshaping_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", arabicshaping_filename);
unicode_joining_group[i] = UC_JOINING_GROUP_NONE;
}
- lineno = 0;
+ int lineno = 0;
for (;;)
{
- char buf[200+1];
- char separator1[200+1];
- char schematic_name[200+1];
- char separator2[200+1];
- char joining_type_name[200+1];
- char separator3[200+1];
- char joining_group_name[200+1];
- int joining_type;
- int joining_group;
-
lineno++;
+ char buf[200+1];
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
continue;
unsigned int i;
+ char separator1[200+1];
+ char schematic_name[200+1];
+ char separator2[200+1];
+ char joining_type_name[200+1];
+ char separator3[200+1];
+ char joining_group_name[200+1];
if (sscanf (buf, "%X%[; ]%[^;]%[; ]%[^;]%[; ]%100[^\n]",
&i, separator1, schematic_name, separator2, joining_type_name,
separator3, joining_group_name) != 7)
}
assert (i < 0x110000);
+ int joining_type;
#define TRY(name) else if (streq (joining_type_name, #name + 16)) joining_type = name;
if (false) {}
TRY(UC_JOINING_TYPE_U)
&& joining_group_name[strlen (joining_group_name) - 1] == ' ')
joining_group_name[strlen (joining_group_name) - 1] = '\0';
+ int joining_group;
#define TRY(value,name) else if (streq (joining_group_name, name)) joining_group = value;
if (false) {}
TRY(UC_JOINING_GROUP_NONE, "No_Joining_Group")
static void
output_joining_type_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value = unicode_joining_type[ch];
static void
output_joining_type (const char *filename, const char *version)
{
- FILE *stream;
- struct joining_type_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
- uint8_t *level3_packed;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, true);
fprintf (stream, "\n");
+ struct joining_type_table t;
t.p = 7;
t.q = 9;
joining_type_table_init (&t);
joining_type_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
fprintf (stream, " },\n");
/* Pack the level3 array. Each entry needs 4 bits only. */
- level3_packed =
+ uint8_t *level3_packed =
(uint8_t *) calloc ((t.level3_size << t.p) * 4 / 8, sizeof (uint8_t));
for (unsigned int i = 0; i < t.level3_size << t.p; i++)
{
static void
output_joining_group_test (const char *filename, const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int value = unicode_joining_group[ch];
static void
output_joining_group (const char *filename, const char *version)
{
- FILE *stream;
- struct joining_group_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
- uint16_t *level3_packed;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct joining_group_table t;
t.p = 7;
t.q = 9;
joining_group_table_init (&t);
joining_group_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, " },\n");
/* Pack the level3 array. Each entry needs 7 bits only. Use 16-bit units,
not 32-bit units, in order to make the lookup function easier. */
- level3_packed =
+ uint16_t *level3_packed =
(uint16_t *)
calloc ((t.level3_size << t.p) * 7 / 16 + 1, sizeof (uint16_t));
for (unsigned int i = 0; i < t.level3_size << t.p; i++)
static void
fill_scripts (const char *scripts_filename)
{
- FILE *stream;
-
- stream = fopen (scripts_filename, "r");
+ FILE *stream = fopen (scripts_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", scripts_filename);
for (;;)
{
char buf[200+1];
- unsigned int i1, i2;
- char padding[200+1];
- char scriptname[200+1];
- int script;
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i1, i2;
+ char padding[200+1];
+ char scriptname[200+1];
if (sscanf (buf, "%X..%X%[ ;]%[^ ]", &i1, &i2, padding, scriptname) != 4)
{
if (sscanf (buf, "%X%[ ;]%[^ ]", &i1, padding, scriptname) != 3)
assert (i2 >= i1);
assert (i2 < 0x110000);
+ int script;
for (script = numscripts - 1; script >= 0; script--)
if (streq (scripts[script], scriptname))
break;
output_scripts (const char *version)
{
const char *filename = "unictype/scripts.h";
- FILE *stream;
- struct script_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
typedef struct
{
scriptinfo_t;
scriptinfo_t scriptinfo[256];
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
for (unsigned int ch = 0; ch < 0x110000; ch++)
if (unicode_scripts[ch] == s)
{
- unsigned int start;
- unsigned int end;
-
- start = ch;
+ unsigned int start = ch;
while (ch + 1 < 0x110000 && unicode_scripts[ch + 1] == s)
ch++;
- end = ch;
+ unsigned int end = ch;
if (i > 0)
fprintf (stream, ",\n");
}
fprintf (stream, "};\n");
+ struct script_table t;
t.p = 7;
t.q = 9;
script_table_init (&t);
script_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
/* To make the level2 values fit in 16 bits, we use 'unsigned short'
instead of 'short' and add 1 to each value. */
if (offset == 0)
output_scripts_byname (const char *version)
{
const char *filename = "unictype/scripts_byname.gperf";
- FILE *stream;
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
fill_blocks (const char *blocks_filename)
{
- FILE *stream;
-
- stream = fopen (blocks_filename, "r");
+ FILE *stream = fopen (blocks_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", blocks_filename);
for (;;)
{
char buf[200+1];
- unsigned int i1, i2;
- char padding[200+1];
- char blockname[200+1];
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i1, i2;
+ char padding[200+1];
+ char blockname[200+1];
if (sscanf (buf, "%X..%X%[ ;]%[^\r]", &i1, &i2, padding, blockname) != 4)
{
fprintf (stderr, "parse error in '%s'\n", blocks_filename);
const char *filename = "unictype/blocks.h";
const unsigned int shift = 8; /* bits to shift away for array access */
const unsigned int threshold = 0x28000; /* cut-off table here to save space */
- FILE *stream;
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
output_ident_category (const char *filename, int (*predicate) (unsigned int), const char *name, const char *version)
{
- FILE *stream;
- struct identsyntax_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct identsyntax_table t;
t.p = 7; /* or 8 */
t.q = 5; /* or 4 */
identsyntax_table_init (&t);
identsyntax_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
bool (*func) (unsigned int))
{
char table[0x110000];
- bool need_semicolon;
- const int max_column = 75;
- int column;
for (unsigned int i = 0; i < 0x110000; i++)
table[i] = (int) func (i);
fprintf (stream, "%s ", classname);
- need_semicolon = false;
- column = 1000;
+ const int max_column = 75;
+ bool need_semicolon = false;
+ int column = 1000;
for (unsigned int i = 0; i < 0x110000; )
{
if (!table[i])
i++;
else
{
- unsigned int low, high;
- char buf[25];
-
- low = i;
+ unsigned int low = i;
do
i++;
while (i < 0x110000 && table[i]);
- high = i - 1;
+ unsigned int high = i - 1;
+ char buf[25];
if (low == high)
strcpy (buf, ucs_symbol (low));
else
unsigned int (*func) (unsigned int))
{
char table[0x110000];
- bool need_semicolon;
- const int max_column = 75;
- int column;
for (unsigned int i = 0; i < 0x110000; i++)
table[i] = (func (i) != i);
fprintf (stream, "%s ", mapname);
- need_semicolon = false;
- column = 1000;
+ const int max_column = 75;
+ bool need_semicolon = false;
+ int column = 1000;
for (unsigned int i = 0; i < 0x110000; i++)
if (table[i])
{
static void
output_tables (const char *filename, const char *version)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "territory \"Earth\"\n");
fprintf (stream, "revision \"%s\"\n", version);
{
- time_t now;
+ time_t now = time (NULL);
char date[11];
- now = time (NULL);
strftime (date, sizeof (date), "%Y-%m-%d", gmtime (&now));
fprintf (stream, "date \"%s\"\n", date);
}
static void
fill_width (const char *width_filename)
{
- FILE *stream;
- char field0[FIELDLEN];
- char field1[FIELDLEN];
- char field2[FIELDLEN];
- int lineno = 0;
-
for (unsigned int i = 0; i < 0x110000; i++)
unicode_width[i] = (unicode_attributes[i].name != NULL ? "N" : NULL);
- stream = fopen (width_filename, "r");
+ FILE *stream = fopen (width_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", width_filename);
exit (1);
}
+ char field0[FIELDLEN];
+ char field1[FIELDLEN];
+ char field2[FIELDLEN];
+ int lineno = 0;
for (;;)
{
- int n;
- int c;
-
lineno++;
- c = getc (stream);
+ int c = getc (stream);
if (c == EOF)
break;
if (c == '\n')
continue;
}
ungetc (c, stream);
- n = getfield (stream, field0, ';');
+ int n = getfield (stream, field0, ';');
do c = getc (stream); while (c == ' ');
ungetc (c, stream);
n += getfield (stream, field1, '#');
static void
output_nonspacing_property (const char *filename, const char *version)
{
- FILE *stream;
- int ind[0x110000 / 0x200];
- unsigned int i_max;
- int next_ind;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, true);
fprintf (stream, "\n");
- next_ind = 0;
+ int ind[0x110000 / 0x200];
+ int next_ind = 0;
for (unsigned int i = 0; i < 0x110000 / 0x200; i++)
{
bool nontrivial = false;
fprintf (stream, "static const unsigned char nonspacing_table_data[%d*64] = {\n",
next_ind);
- i_max = 0;
+ unsigned int i_max = 0;
for (unsigned int i = 0; i < 0x110000 / 0x200; i++)
{
bool nontrivial = (ind[i] >= 0);
static void
output_width_property_test (const char *filename)
{
- FILE *stream;
- unsigned int interval_start, interval_end;
- char interval_value;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
exit (1);
}
- interval_value = 0;
+ unsigned int interval_start, interval_end;
+ char interval_value = 0;
interval_start = interval_end = 0; /* avoid GCC warning */
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
static void
debug_output_lbrk_tables (const char *filename)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
fill_org_lbp (const char *linebreak_filename)
{
- FILE *stream;
- char field0[FIELDLEN];
- char field1[FIELDLEN];
- char field2[FIELDLEN];
- int lineno = 0;
-
/* For unassigned characters (General Category "Cn") that have property
Extended_Pictographic, the LineBreak.txt files is inconsistent:
For some of them, such as U+1F02C, it specifies LBP_ID, which then triggers
unicode_org_lbp[i] =
(is_property_extended_pictographic (i) ? LBP_EBF : LBP_XX);
- stream = fopen (linebreak_filename, "r");
+ FILE *stream = fopen (linebreak_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", linebreak_filename);
exit (1);
}
+ char field0[FIELDLEN];
+ char field1[FIELDLEN];
+ char field2[FIELDLEN];
+ int lineno = 0;
for (;;)
{
- int n;
- int c;
- int value;
-
lineno++;
- c = getc (stream);
+ int c = getc (stream);
if (c == EOF)
break;
if (c == '\n')
continue;
}
ungetc (c, stream);
- n = getfield (stream, field0, ';');
+ int n = getfield (stream, field0, ';');
do c = getc (stream); while (c == ' ');
ungetc (c, stream);
n += getfield (stream, field1, '#');
/* Remove trailing spaces from field1. */
while (strlen (field1) > 0 && field1[strlen (field1) - 1] == ' ')
field1[strlen (field1) - 1] = '\0';
+ int value;
#define TRY(bit) else if (streq (field1, #bit + 4)) value = bit;
if (false) {}
TRY(LBP_BK)
static void
debug_output_org_lbrk_tables (const char *filename)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_lbpea (FILE *stream1, FILE *stream2)
{
struct lbpea_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
t.p = 7;
t.q = 9;
lbpea_table_init (&t);
lbpea_table_finalize (&t);
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream2, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream2, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream2, " %5d", -1);
else
fprintf (stream2, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream2, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream2, " %5d", -1);
else
output_lbrk_tables (const char *filename1, const char *filename2, const char *version)
{
const char *filenames[2];
- FILE *streams[2];
-
filenames[0] = filename1;
filenames[1] = filename2;
+ FILE *streams[2];
for (size_t i = 0; i < 2; i++)
{
streams[i] = fopen (filenames[i], "w");
static void
output_lbrk_rules_as_tables (const char *filename, const char *version)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
debug_output_wbrk_tables (const char *filename)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
fill_org_wbp (const char *wordbreakproperty_filename)
{
- FILE *stream;
-
for (unsigned int i = 0; i < 0x110000; i++)
unicode_org_wbp[i] = WBP_OTHER;
- stream = fopen (wordbreakproperty_filename, "r");
+ FILE *stream = fopen (wordbreakproperty_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", wordbreakproperty_filename);
for (;;)
{
char buf[200+1];
- unsigned int i1, i2;
- char padding[200+1];
- char propname[200+1];
- int propvalue;
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i1, i2;
+ char padding[200+1];
+ char propname[200+1];
if (sscanf (buf, "%X..%X%[ ;]%[^ ]", &i1, &i2, padding, propname) != 4)
{
if (sscanf (buf, "%X%[ ;]%[^ ]", &i1, padding, propname) != 3)
}
i2 = i1;
}
+ int propvalue;
#define PROP(name,value) \
if (streq (propname, name)) propvalue = value; else
PROP ("CR", WBP_CR)
static void
debug_output_org_wbrk_tables (const char *filename)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_wbp (FILE *stream)
{
struct wbp_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
t.p = 7;
t.q = 9;
wbp_table_init (&t);
wbp_table_finalize (&t);
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
output_wbrk_tables (const char *filename, const char *version)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
static void
output_gbp_test (const char *filename)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_tests_license (stream);
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
int gbp = unicode_org_gbp[ch];
- const char *gbp_string;
while (ch + 1 < 0x110000 && unicode_org_gbp[ch + 1] == gbp)
ch++;
+ const char *gbp_string;
switch (gbp)
{
#define CASE(x) case x: gbp_string = #x; break;
static void
output_gbp_table (const char *filename, const char *version)
{
- FILE *stream;
- struct gbp_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
output_library_license (stream, false);
fprintf (stream, "\n");
+ struct gbp_table t;
t.p = 7;
t.q = 9;
gbp_table_init (&t);
gbp_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
fill_org_gbp (const char *graphemebreakproperty_filename)
{
- FILE *stream;
- int lineno = 0;
-
for (unsigned int i = 0; i < 0x110000; i++)
unicode_org_gbp[i] = GBP_OTHER;
- stream = fopen (graphemebreakproperty_filename, "r");
+ FILE *stream = fopen (graphemebreakproperty_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n",
exit (1);
}
+ int lineno = 0;
for (;;)
{
- char buf[200+1];
- unsigned int i1, i2;
- char padding[200+1];
- char propname[200+1];
- int propvalue;
-
lineno++;
+ char buf[200+1];
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i1, i2;
+ char padding[200+1];
+ char propname[200+1];
if (sscanf (buf, "%X..%X%[ ;]%[^ ]", &i1, &i2, padding, propname) != 4)
{
if (sscanf (buf, "%X%[ ;]%[^ ]", &i1, padding, propname) != 3)
}
i2 = i1;
}
+ int propvalue;
#define PROP(name,value) \
if (streq (propname, name)) propvalue = value; else
PROP ("CR", GBP_CR)
if (decomposition != NULL && decomposition[0] != '\0')
{
int type = UC_DECOMP_CANONICAL;
- unsigned int length;
- char *endptr;
if (decomposition[0] == '<')
{
- const char *rangle;
- size_t typelen;
-
- rangle = strchr (decomposition + 1, '>');
+ const char *rangle = strchr (decomposition + 1, '>');
assert (rangle != NULL);
- typelen = rangle + 1 - decomposition;
+ size_t typelen = rangle + 1 - decomposition;
#define TYPE(t1,t2) \
if (typelen == (sizeof (t1) - 1) && memeq (decomposition, t1, typelen)) \
type = t2; \
if (decomposition[0] == ' ')
decomposition++;
}
+ unsigned int length;
for (length = 0; length < MAX_DECOMP_LENGTH; length++)
{
+ char *endptr;
decomposed[length] = strtoul (decomposition, &endptr, 16);
if (endptr == decomposition)
break;
output_decomposition (FILE *stream1, FILE *stream2)
{
struct decomp_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
t.p = 5;
t.q = 5;
decomp_table_init (&t);
decomp_table_finalize (&t);
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream2, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream2, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream2, " %5d", -1);
else
fprintf (stream2, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream2, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream2, " %5d", -1);
else
output_decomposition_tables (const char *filename1, const char *filename2, const char *version)
{
const char *filenames[2];
- FILE *streams[2];
-
filenames[0] = filename1;
filenames[1] = filename2;
+ FILE *streams[2];
for (size_t i = 0; i < 2; i++)
{
streams[i] = fopen (filenames[i], "w");
static void
fill_composition_exclusions (const char *compositionexclusions_filename)
{
- FILE *stream;
-
- stream = fopen (compositionexclusions_filename, "r");
+ FILE *stream = fopen (compositionexclusions_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", compositionexclusions_filename);
for (;;)
{
char buf[200+1];
- unsigned int i;
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ unsigned int i;
if (sscanf (buf, "%X", &i) != 1)
{
fprintf (stderr, "parse error in '%s'\n", compositionexclusions_filename);
static void
debug_output_composition_tables (const char *filename)
{
- FILE *stream;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
{
unsigned int max_code1;
unsigned int max_code2;
- FILE *stream;
-
- max_code1 = 0;
- max_code2 = 0;
-
- stream = fopen (filename, "w");
- if (stream == NULL)
- {
- fprintf (stderr, "cannot open '%s' for writing\n", filename);
- exit (1);
- }
- fprintf (stream, "/* DO NOT EDIT! GENERATED AUTOMATICALLY! */\n");
- fprintf (stream, "/* Canonical composition of Unicode characters. */\n");
- fprintf (stream, "/* Generated automatically by gen-uni-tables.c for Unicode %s. */\n",
- version);
- fprintf (stream, "\n");
-
- fprintf (stream, "/* Copyright (C) 2009-2025 Free Software Foundation, Inc.\n");
- fprintf (stream, "\n");
- output_library_license (stream, true);
- fprintf (stream, "\n");
-
- /* The composition table is a set of mappings (code1, code2) -> combined,
- with 928 entries,
- 367 values for code1 (from 0x003C to 0x30FD),
- 54 values for code2 (from 0x0300 to 0x309A).
- For a fixed code1, there are from 1 to 19 possible values for code2.
- For a fixed code2, there are from 1 to 117 possible values for code1.
- This is a very sparse matrix.
-
- We want an O(1) hash lookup.
-
- We could implement the hash lookup by mapping (code1, code2) to a linear
- combination mul1*code1 + mul2*code2, which is then used as an index into
- a 3-level table. But this leads to a table of size 37 KB.
-
- We use gperf to implement the hash lookup, giving it the 928 sets of
- 4 bytes (code1, code2) as input. gperf generates a hash table of size
- 1527, which is quite good (60% filled). It requires an auxiliary table
- lookup in a table of size 0.5 KB. The total tables size is 11 KB. */
-
- fprintf (stream, "struct composition_rule { char codes[6] _GL_ATTRIBUTE_NONSTRING; unsigned int combined; };\n");
- fprintf (stream, "%%struct-type\n");
- fprintf (stream, "%%language=ANSI-C\n");
- fprintf (stream, "%%define slot-name codes\n");
- fprintf (stream, "%%define hash-function-name gl_uninorm_compose_hash\n");
- fprintf (stream, "%%define lookup-function-name gl_uninorm_compose_lookup\n");
- fprintf (stream, "%%compare-lengths\n");
- fprintf (stream, "%%compare-strncmp\n");
- fprintf (stream, "%%readonly-tables\n");
- fprintf (stream, "%%omit-struct-type\n");
- fprintf (stream, "%%%%\n");
-
- for (unsigned int ch = 0; ch < 0x110000; ch++)
- {
- unsigned int length;
- unsigned int decomposed[MAX_DECOMP_LENGTH];
- int type = get_decomposition (ch, &length, decomposed);
-
- if (type == UC_DECOMP_CANONICAL
- /* Consider only binary decompositions.
- Exclude singleton decompositions. */
- && length == 2)
- {
- unsigned int code1 = decomposed[0];
- unsigned int code2 = decomposed[1];
- unsigned int combined = ch;
+ {
+ FILE *stream = fopen (filename, "w");
+ if (stream == NULL)
+ {
+ fprintf (stderr, "cannot open '%s' for writing\n", filename);
+ exit (1);
+ }
- /* Exclude decompositions where the first part is not a starter,
- i.e. is not of canonical combining class 0. */
- if (streq (unicode_attributes[code1].combining, "0")
- /* Exclude characters listed in CompositionExclusions.txt. */
- && !unicode_composition_exclusions[combined])
- {
- /* The combined character must now also be a starter.
- Verify this. */
- assert (streq (unicode_attributes[combined].combining, "0"));
+ fprintf (stream, "/* DO NOT EDIT! GENERATED AUTOMATICALLY! */\n");
+ fprintf (stream, "/* Canonical composition of Unicode characters. */\n");
+ fprintf (stream, "/* Generated automatically by gen-uni-tables.c for Unicode %s. */\n",
+ version);
+ fprintf (stream, "\n");
- if (max_code1 < code1)
- max_code1 = code1;
- if (max_code2 < code2)
- max_code2 = code2;
+ fprintf (stream, "/* Copyright (C) 2009-2025 Free Software Foundation, Inc.\n");
+ fprintf (stream, "\n");
+ output_library_license (stream, true);
+ fprintf (stream, "\n");
- fprintf (stream, "\"\\x%02x\\x%02x\\x%02x\\x%02x\\x%02x\\x%02x\", 0x%04x\n",
- (code1 >> 16) & 0xff, (code1 >> 8) & 0xff, code1 & 0xff,
- (code2 >> 16) & 0xff, (code2 >> 8) & 0xff, code2 & 0xff,
- combined);
- }
- }
- }
+ /* The composition table is a set of mappings (code1, code2) -> combined,
+ with 928 entries,
+ 367 values for code1 (from 0x003C to 0x30FD),
+ 54 values for code2 (from 0x0300 to 0x309A).
+ For a fixed code1, there are from 1 to 19 possible values for code2.
+ For a fixed code2, there are from 1 to 117 possible values for code1.
+ This is a very sparse matrix.
+
+ We want an O(1) hash lookup.
+
+ We could implement the hash lookup by mapping (code1, code2) to a linear
+ combination mul1*code1 + mul2*code2, which is then used as an index into
+ a 3-level table. But this leads to a table of size 37 KB.
+
+ We use gperf to implement the hash lookup, giving it the 928 sets of
+ 4 bytes (code1, code2) as input. gperf generates a hash table of size
+ 1527, which is quite good (60% filled). It requires an auxiliary table
+ lookup in a table of size 0.5 KB. The total tables size is 11 KB. */
+
+ fprintf (stream, "struct composition_rule { char codes[6] _GL_ATTRIBUTE_NONSTRING; unsigned int combined; };\n");
+ fprintf (stream, "%%struct-type\n");
+ fprintf (stream, "%%language=ANSI-C\n");
+ fprintf (stream, "%%define slot-name codes\n");
+ fprintf (stream, "%%define hash-function-name gl_uninorm_compose_hash\n");
+ fprintf (stream, "%%define lookup-function-name gl_uninorm_compose_lookup\n");
+ fprintf (stream, "%%compare-lengths\n");
+ fprintf (stream, "%%compare-strncmp\n");
+ fprintf (stream, "%%readonly-tables\n");
+ fprintf (stream, "%%omit-struct-type\n");
+ fprintf (stream, "%%%%\n");
+
+ max_code1 = 0;
+ max_code2 = 0;
+ for (unsigned int ch = 0; ch < 0x110000; ch++)
+ {
+ unsigned int length;
+ unsigned int decomposed[MAX_DECOMP_LENGTH];
+ int type = get_decomposition (ch, &length, decomposed);
- if (ferror (stream) || fclose (stream))
- {
- fprintf (stderr, "error writing to '%s'\n", filename);
- exit (1);
- }
+ if (type == UC_DECOMP_CANONICAL
+ /* Consider only binary decompositions.
+ Exclude singleton decompositions. */
+ && length == 2)
+ {
+ unsigned int code1 = decomposed[0];
+ unsigned int code2 = decomposed[1];
+ unsigned int combined = ch;
+
+ /* Exclude decompositions where the first part is not a starter,
+ i.e. is not of canonical combining class 0. */
+ if (streq (unicode_attributes[code1].combining, "0")
+ /* Exclude characters listed in CompositionExclusions.txt. */
+ && !unicode_composition_exclusions[combined])
+ {
+ /* The combined character must now also be a starter.
+ Verify this. */
+ assert (streq (unicode_attributes[combined].combining, "0"));
+
+ if (max_code1 < code1)
+ max_code1 = code1;
+ if (max_code2 < code2)
+ max_code2 = code2;
+
+ fprintf (stream, "\"\\x%02x\\x%02x\\x%02x\\x%02x\\x%02x\\x%02x\", 0x%04x\n",
+ (code1 >> 16) & 0xff, (code1 >> 8) & 0xff, code1 & 0xff,
+ (code2 >> 16) & 0xff, (code2 >> 8) & 0xff, code2 & 0xff,
+ combined);
+ }
+ }
+ }
- stream = fopen (filename2, "w");
- if (stream == NULL)
- {
- fprintf (stderr, "cannot open '%s' for writing\n", filename2);
- exit (1);
- }
+ if (ferror (stream) || fclose (stream))
+ {
+ fprintf (stderr, "error writing to '%s'\n", filename);
+ exit (1);
+ }
+ }
+ {
+ FILE *stream = fopen (filename2, "w");
+ if (stream == NULL)
+ {
+ fprintf (stderr, "cannot open '%s' for writing\n", filename2);
+ exit (1);
+ }
- fprintf (stream, "/* DO NOT EDIT! GENERATED AUTOMATICALLY! */\n");
- fprintf (stream, "/* Canonical composition of Unicode characters. */\n");
- fprintf (stream, "/* Generated automatically by gen-uni-tables.c for Unicode %s. */\n",
- version);
- fprintf (stream, "\n");
+ fprintf (stream, "/* DO NOT EDIT! GENERATED AUTOMATICALLY! */\n");
+ fprintf (stream, "/* Canonical composition of Unicode characters. */\n");
+ fprintf (stream, "/* Generated automatically by gen-uni-tables.c for Unicode %s. */\n",
+ version);
+ fprintf (stream, "\n");
- fprintf (stream, "/* Copyright (C) 2009-2025 Free Software Foundation, Inc.\n");
- fprintf (stream, "\n");
- output_library_license (stream, true);
- fprintf (stream, "\n");
+ fprintf (stream, "/* Copyright (C) 2009-2025 Free Software Foundation, Inc.\n");
+ fprintf (stream, "\n");
+ output_library_license (stream, true);
+ fprintf (stream, "\n");
- fprintf (stream, "/* Maximum value of the first argument for which gl_uninorm_compose_lookup\n"
- " can return a non-NULL value. */\n");
- fprintf (stream, "#define UNINORM_COMPOSE_MAX_ARG1 0x%x\n", max_code1);
- fprintf (stream, "/* Maximum value of the second argument for which gl_uninorm_compose_lookup\n"
- " can return a non-NULL value. */\n");
- fprintf (stream, "#define UNINORM_COMPOSE_MAX_ARG2 0x%x\n", max_code2);
+ fprintf (stream, "/* Maximum value of the first argument for which gl_uninorm_compose_lookup\n"
+ " can return a non-NULL value. */\n");
+ fprintf (stream, "#define UNINORM_COMPOSE_MAX_ARG1 0x%x\n", max_code1);
+ fprintf (stream, "/* Maximum value of the second argument for which gl_uninorm_compose_lookup\n"
+ " can return a non-NULL value. */\n");
+ fprintf (stream, "#define UNINORM_COMPOSE_MAX_ARG2 0x%x\n", max_code2);
- if (ferror (stream) || fclose (stream))
- {
- fprintf (stderr, "error writing to '%s'\n", filename2);
- exit (1);
- }
+ if (ferror (stream) || fclose (stream))
+ {
+ fprintf (stderr, "error writing to '%s'\n", filename2);
+ exit (1);
+ }
+ }
}
/* ========================================================================= */
unsigned int (*func) (unsigned int),
const char *version)
{
- FILE *stream;
- bool need_comma;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "#include \"test-mapping-part1.h\"\n");
fprintf (stream, "\n");
- need_comma = false;
+ bool need_comma = false;
for (unsigned int ch = 0; ch < 0x110000; ch++)
{
unsigned int value = func (ch);
unsigned int (*func) (unsigned int),
const char *version)
{
- FILE *stream;
- struct mapping_table t;
- unsigned int level1_offset, level2_offset, level3_offset;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
|| streq (filename, "unicase/toupper.h"));
fprintf (stream, "\n");
+ struct mapping_table t;
t.p = 7;
t.q = 9;
mapping_table_init (&t);
mapping_table_finalize (&t);
/* Offsets in t.result, in memory of this process. */
- level1_offset =
+ unsigned int level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ unsigned int level2_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t);
- level3_offset =
+ unsigned int level3_offset =
5 * sizeof (uint32_t)
+ t.level1_size * sizeof (uint32_t)
+ (t.level2_size << t.q) * sizeof (uint32_t);
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level1_size; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level1_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level1_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
fprintf (stream, "\n ");
for (unsigned int i = 0; i < t.level2_size << t.q; i++)
{
- uint32_t offset;
if (i > 0 && (i % 8) == 0)
fprintf (stream, "\n ");
- offset = ((uint32_t *) (t.result + level2_offset))[i];
+ uint32_t offset = ((uint32_t *) (t.result + level2_offset))[i];
if (offset == 0)
fprintf (stream, " %5d", -1);
else
static void
fill_casing_rules (const char *specialcasing_filename)
{
- FILE *stream;
-
- stream = fopen (specialcasing_filename, "r");
+ FILE *stream = fopen (specialcasing_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", specialcasing_filename);
for (;;)
{
char buf[200+1];
- char *scanptr;
- char *endptr;
-
- unsigned int code;
- unsigned int lower_mapping[3];
- unsigned int title_mapping[3];
- unsigned int upper_mapping[3];
- char *language;
- int context;
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ char *scanptr;
+ char *endptr;
+
/* Scan code. */
scanptr = buf;
- code = strtoul (scanptr, &endptr, 16);
+ unsigned int code = strtoul (scanptr, &endptr, 16);
if (endptr == scanptr)
{
fprintf (stderr, "parse error in '%s'\n", specialcasing_filename);
scanptr++;
/* Scan lower mapping. */
+ unsigned int lower_mapping[3];
for (int i = 0; i < 3; i++)
lower_mapping[i] = 0;
for (int i = 0; i < 3; i++)
scanptr++;
/* Scan title mapping. */
+ unsigned int title_mapping[3];
for (int i = 0; i < 3; i++)
title_mapping[i] = 0;
for (int i = 0; i < 3; i++)
scanptr++;
/* Scan upper mapping. */
+ unsigned int upper_mapping[3];
for (int i = 0; i < 3; i++)
upper_mapping[i] = 0;
for (int i = 0; i < 3; i++)
scanptr++;
/* Scan language and context. */
- language = NULL;
- context = SCC_ALWAYS;
+ char *language = NULL;
+ int context = SCC_ALWAYS;
while (*scanptr == ' ')
scanptr++;
if (*scanptr != '\0' && *scanptr != '#')
{
const char *word_begin = scanptr;
- const char *word_end;
-
while (*scanptr != '\0' && *scanptr != '#' && *scanptr != ';' && *scanptr != ' ')
scanptr++;
- word_end = scanptr;
+ const char *word_end = scanptr;
while (*scanptr == ' ')
scanptr++;
static void
fill_casefolding_rules (const char *casefolding_filename)
{
- FILE *stream;
-
- stream = fopen (casefolding_filename, "r");
+ FILE *stream = fopen (casefolding_filename, "r");
if (stream == NULL)
{
fprintf (stderr, "error during fopen of '%s'\n", casefolding_filename);
for (;;)
{
char buf[200+1];
- char *scanptr;
- char *endptr;
-
- unsigned int code;
- char type;
- unsigned int mapping[3];
-
if (fscanf (stream, "%200[^\n]\n", buf) < 1)
break;
if (buf[0] == '\0' || buf[0] == '#')
continue;
+ char *scanptr;
+ char *endptr;
+
/* Scan code. */
scanptr = buf;
- code = strtoul (scanptr, &endptr, 16);
+ unsigned int code = strtoul (scanptr, &endptr, 16);
if (endptr == scanptr)
{
fprintf (stderr, "parse error in '%s'\n", casefolding_filename);
while (*scanptr == ' ')
scanptr++;
+ char type;
switch (*scanptr)
{
case 'C': case 'F': case 'S': case 'T':
scanptr++;
/* Scan casefold mapping. */
+ unsigned int mapping[3];
for (int i = 0; i < 3; i++)
mapping[i] = 0;
for (int i = 0; i < 3; i++)
static void
output_casing_rules (const char *filename, const char *version)
{
- FILE *stream;
- unsigned int minor;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "%%omit-struct-type\n");
fprintf (stream, "%%%%\n");
- minor = 0;
+ unsigned int minor = 0;
for (unsigned int i = 0; i < num_casing_rules; i++)
{
struct special_casing_rule *rule = casing_rules[i];
static void
output_version (const char *filename, const char *version)
{
- FILE *stream;
- int major;
- int minor;
-
- stream = fopen (filename, "w");
+ FILE *stream = fopen (filename, "w");
if (stream == NULL)
{
fprintf (stderr, "cannot open '%s' for writing\n", filename);
fprintf (stream, "#include \"unimetadata.h\"\n");
fprintf (stream, "\n");
+ int major;
+ int minor;
sscanf (version, "%d.%d", &major, &minor);
fprintf (stream, "const int _libunistring_unicode_version = (%d << 8) | %d;\n",
major, minor);
for (;;)
{
/* Here we know that the address space size is >= low_bound. */
- struct rlimit try_limit;
uintptr_t try_next = 2 * low_bound + pagesize;
if (try_next < low_bound)
goto done1;
}
+ struct rlimit try_limit;
try_limit.rlim_max = orig_limit.rlim_max;
try_limit.rlim_cur = try_next;
if (setrlimit (RLIMIT_AS, &try_limit) == 0)
>= low_bound and < high_bound. */
while (high_bound - low_bound > pagesize)
{
- struct rlimit try_limit;
uintptr_t try_next =
low_bound + (((high_bound - low_bound) / 2) / pagesize) * pagesize;
/* Here low_bound <= try_next < high_bound. */
+ struct rlimit try_limit;
try_limit.rlim_max = orig_limit.rlim_max;
try_limit.rlim_cur = try_next;
if (setrlimit (RLIMIT_AS, &try_limit) == 0)
#elif HAVE_SETRLIMIT && defined RLIMIT_AS && HAVE_SYS_MMAN_H && HAVE_MPROTECT && !defined __HAIKU__
/* Prefer get_rusage_as_via_setrlimit() if it succeeds,
because the caller may want to use the result with setrlimit(). */
- uintptr_t result;
-
- result = get_rusage_as_via_setrlimit ();
+ uintptr_t result = get_rusage_as_via_setrlimit ();
if (result == 0)
result = get_rusage_as_via_iterator ();
return result;
for (;;)
{
/* Here we know that the data segment size is >= low_bound. */
- struct rlimit try_limit;
uintptr_t try_next = 2 * low_bound + pagesize;
if (try_next < low_bound)
goto done;
}
+ struct rlimit try_limit;
try_limit.rlim_max = orig_limit.rlim_max;
try_limit.rlim_cur = try_next;
if (setrlimit (RLIMIT_DATA, &try_limit) == 0)
>= low_bound and < high_bound. */
while (high_bound - low_bound > pagesize)
{
- struct rlimit try_limit;
uintptr_t try_next =
low_bound + (((high_bound - low_bound) / 2) / pagesize) * pagesize;
/* Here low_bound <= try_next < high_bound. */
+ struct rlimit try_limit;
try_limit.rlim_max = orig_limit.rlim_max;
try_limit.rlim_cur = try_next;
if (setrlimit (RLIMIT_DATA, &try_limit) == 0)
# else
/* Prefer get_rusage_data_via_setrlimit() if it succeeds,
because the caller may want to use the result with setrlimit(). */
- uintptr_t result;
-
- result = get_rusage_data_via_setrlimit ();
+ uintptr_t result = get_rusage_data_via_setrlimit ();
if (result == 0)
result = get_rusage_data_via_iterator ();
return result;
/* Read the contents of /proc/<pid>/status into memory. */
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/status", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
char buf[4096 + 1];
/* Read the contents of /proc/<pid>/status into memory. */
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/status", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
char buf[4096 + 1];
close (fd);
if (nread >= 0)
{
- char *p;
-
/* NUL-terminate the buffer. */
buf[nread] = '\0';
/* Search for the third space-separated field. */
- p = strchr (buf, ' ');
+ char *p = strchr (buf, ' ');
if (p != NULL)
{
p = strchr (p + 1, ' ');
/* Read the contents of /proc/<pid>/psinfo into memory. */
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/psinfo", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
char buf[4096 + 1];
close (fd);
if (nread >= 0)
{
- char *p;
- int count;
-
/* NUL-terminate the buffer. */
buf[nread] = '\0';
/* Search for the 16th space-separated field. */
- p = strchr (buf, ' ');
- for (count = 1; p != NULL && count < 15; count++)
+ char *p = strchr (buf, ' ');
+ for (int count = 1; p != NULL && count < 15; count++)
p = strchr (p + 1, ' ');
if (p != NULL)
{
Alternatively, we could read the contents of /proc/<pid>/status into
memory. But it contains a lot of information that we don't need. */
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/psinfo", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
/* The contents is a 'struct psinfo'. But since 'struct psinfo'
int info_path[] =
{ CTL_KERN, KERN_PROC, KERN_PROC_PID, pid, sizeof (struct kinfo_proc), 1 };
struct kinfo_proc info;
- size_t len;
-
- len = sizeof (info);
+ size_t len = sizeof (info);
if (sysctl (info_path, 6, &info, &len, NULL, 0) >= 0 && len == sizeof (info))
return info.p_ppid;
/* Read the symlink /proc/<pid>/exe. */
{
char filename[6 + 10 + 4 + 1];
- char linkbuf[1024 + 1];
- ssize_t linklen;
-
sprintf (filename, "/proc/%u/exe", (unsigned int) pid);
- linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
+
+ char linkbuf[1024 + 1];
+ ssize_t linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
if (linklen > 0)
{
- char *slash;
-
/* NUL-terminate the link. */
linkbuf[linklen] = '\0';
/* Find the portion after the last slash. */
- slash = strrchr (linkbuf, '/');
+ char *slash = strrchr (linkbuf, '/');
return strdup (slash != NULL ? slash + 1 : linkbuf);
}
}
read the contents of /proc/<pid>/cmdline into memory. */
{
char filename[6 + 10 + 8 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/cmdline", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
char buf[4096 + 1];
close (fd);
if (nread >= 0)
{
- char *slash;
-
/* NUL-terminate the buffer (just in case it does not have the
expected format). */
buf[nread] = '\0';
/* The program name and each argument is followed by a NUL byte. */
/* Find the portion after the last slash. */
- slash = strrchr (buf, '/');
+ char *slash = strrchr (buf, '/');
return strdup (slash != NULL ? slash + 1 : buf);
}
}
/* Read the symlink /proc/<pid>/file. */
char filename[6 + 10 + 5 + 1];
- char linkbuf[1024 + 1];
- ssize_t linklen;
-
sprintf (filename, "/proc/%u/file", (unsigned int) pid);
- linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
+
+ char linkbuf[1024 + 1];
+ ssize_t linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
if (linklen > 0)
{
- char *slash;
-
/* NUL-terminate the link. */
linkbuf[linklen] = '\0';
/* Find the portion after the last slash. */
- slash = strrchr (linkbuf, '/');
+ char *slash = strrchr (linkbuf, '/');
return strdup (slash != NULL ? slash + 1 : linkbuf);
}
/* Read the contents of /proc/<pid>/psinfo into memory. */
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/psinfo", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
char buf[4096 + 1];
close (fd);
if (nread >= 0)
{
- char *p;
- int count;
-
/* NUL-terminate the buffer. */
buf[nread] = '\0';
/* Search for the 4th space-separated field. */
- p = strchr (buf, ' ');
- for (count = 1; p != NULL && count < 3; count++)
+ char *p = strchr (buf, ' ');
+ for (int count = 1; p != NULL && count < 3; count++)
p = strchr (p + 1, ' ');
if (p != NULL)
{
When it succeeds, it doesn't truncate. */
{
char filename[6 + 10 + 11 + 1];
- char linkbuf[1024 + 1];
- ssize_t linklen;
-
sprintf (filename, "/proc/%u/path/a.out", (unsigned int) pid);
- linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
+
+ char linkbuf[1024 + 1];
+ ssize_t linklen = readlink (filename, linkbuf, sizeof (linkbuf) - 1);
if (linklen > 0)
{
- char *slash;
-
/* NUL-terminate the link. */
linkbuf[linklen] = '\0';
/* Find the portion after the last slash. */
- slash = strrchr (linkbuf, '/');
+ char *slash = strrchr (linkbuf, '/');
return strdup (slash != NULL ? slash + 1 : linkbuf);
}
}
memory. But it contains a lot of information that we don't need. */
{
char filename[6 + 10 + 7 + 1];
- int fd;
-
sprintf (filename, "/proc/%u/psinfo", (unsigned int) pid);
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
{
/* The contents is a 'struct psinfo'. But since 'struct psinfo'
int info_path[] =
{ CTL_KERN, KERN_PROC, KERN_PROC_PID, pid, sizeof (struct kinfo_proc), 1 };
struct kinfo_proc info;
- size_t len;
-
- len = sizeof (info);
+ size_t len = sizeof (info);
if (sysctl (info_path, 6, &info, &len, NULL, 0) >= 0 && len == sizeof (info))
return strdup (info.p_comm);
use_win32_p (void)
{
static int done = 0;
- HMODULE h;
if (done)
return getaddrinfo_ptr ? 1 : 0;
done = 1;
- h = GetModuleHandle ("ws2_32.dll");
+ HMODULE h = GetModuleHandle ("ws2_32.dll");
if (h)
{
struct addrinfo **restrict res)
#undef getaddrinfo
{
- struct addrinfo *tmp;
- int port = 0;
- struct hostent *he;
- void *storage;
- size_t size;
# if HAVE_IPV6
struct v6_pair {
struct addrinfo addrinfo;
# endif
}
+ int port = 0;
if (servname)
{
struct servent *se = NULL;
}
/* FIXME: Use gethostbyname_r if available. */
- he = gethostbyname (nodename);
+ struct hostent *he = gethostbyname (nodename);
if (!he || he->h_addr_list[0] == NULL)
return EAI_NONAME;
+ size_t size;
switch (he->h_addrtype)
{
# if HAVE_IPV6
return EAI_NODATA;
}
- storage = calloc (1, size);
+ void *storage = calloc (1, size);
if (!storage)
return EAI_MEMORY;
+ struct addrinfo *tmp;
switch (he->h_addrtype)
{
# if HAVE_IPV6
while (ai)
{
- struct addrinfo *cur;
-
- cur = ai;
+ struct addrinfo *cur = ai;
ai = ai->ai_next;
free (cur->ai_canonname);
char *
rpl_getcwd (char *buf, size_t size)
{
- char *result;
-
/* Handle single size operations. */
if (buf)
{
errno = ENOMEM;
return NULL;
}
- result = getcwd (buf, size);
+ char *result = getcwd (buf, size);
if (!result)
free (buf);
return result;
char *ptr = getcwd (tmp, size);
if (ptr)
{
- result = strdup (ptr);
+ char *result = strdup (ptr);
if (!result)
errno = ENOMEM;
return result;
}
/* My what a large directory name we have. */
+ char *result;
do
{
size <<= 1;
size_t dotsize = sizeof dots;
size_t dotlen = 0;
#endif
- DIR *dirstream = NULL;
- dev_t rootdev, thisdev;
- ino_t rootino, thisino;
- char *dir;
- register char *dirp;
- struct stat64 st;
- size_t allocated = size;
- size_t used;
#if HAVE_MINIMALLY_WORKING_GETCWD
/* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
this wrong result with errno = 0. */
# undef getcwd
- dir = getcwd_system (buf, size);
- if (dir || (size && errno == ERANGE))
- return dir;
+ {
+ char *dir = getcwd_system (buf, size);
+ if (dir || (size && errno == ERANGE))
+ return dir;
+ }
/* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
internal magic that lets it work even if an ancestor directory is
if (errno == EINVAL && buf == NULL && size == 0)
{
char big_buffer[BIG_FILE_NAME_LENGTH + 1];
- dir = getcwd_system (big_buffer, sizeof big_buffer);
+ char *dir = getcwd_system (big_buffer, sizeof big_buffer);
if (dir)
return strdup (dir);
}
return NULL;
# endif
#endif
+
+ size_t allocated = size;
if (size == 0)
{
if (buf != NULL)
allocated = BIG_FILE_NAME_LENGTH + 1;
}
+ char *dir;
if (buf == NULL)
{
dir = malloc (allocated);
else
dir = buf;
- dirp = dir + allocated;
+ register char *dirp = dir + allocated;
*--dirp = '\0';
- if (__lstat64 (".", &st) < 0)
- goto lose;
- thisdev = st.st_dev;
- thisino = st.st_ino;
+ DIR *dirstream = NULL;
+
+ dev_t thisdev;
+ ino_t thisino;
+ {
+ struct stat64 st;
+ if (__lstat64 (".", &st) < 0)
+ goto lose;
+ thisdev = st.st_dev;
+ thisino = st.st_ino;
+ }
- if (__lstat64 ("/", &st) < 0)
- goto lose;
- rootdev = st.st_dev;
- rootino = st.st_ino;
+ dev_t rootdev;
+ ino_t rootino;
+ {
+ struct stat64 st;
+ if (__lstat64 ("/", &st) < 0)
+ goto lose;
+ rootdev = st.st_dev;
+ rootino = st.st_ino;
+ }
while (!(thisdev == rootdev && thisino == rootino))
{
- struct dirent64 *d;
+ /* Look at the parent directory. */
dev_t dotdev;
ino_t dotino;
- bool mount_point;
- int parent_status;
- size_t dirroom;
- size_t namlen;
- bool use_d_ino = true;
-
- /* Look at the parent directory. */
+ {
+ struct stat64 st;
+ int parent_status;
#if HAVE_OPENAT_SUPPORT
- fd = __openat64 (fd, "..", O_RDONLY);
- if (fd < 0)
- goto lose;
- fd_needs_closing = true;
- parent_status = __fstat64 (fd, &st);
+ fd = __openat64 (fd, "..", O_RDONLY);
+ if (fd < 0)
+ goto lose;
+ fd_needs_closing = true;
+ parent_status = __fstat64 (fd, &st);
#else
- dotlist[dotlen++] = '.';
- dotlist[dotlen++] = '.';
- dotlist[dotlen] = '\0';
- parent_status = __lstat64 (dotlist, &st);
+ dotlist[dotlen++] = '.';
+ dotlist[dotlen++] = '.';
+ dotlist[dotlen] = '\0';
+ parent_status = __lstat64 (dotlist, &st);
#endif
- if (parent_status != 0)
- goto lose;
-
- if (dirstream && __closedir (dirstream) != 0)
- {
- dirstream = NULL;
+ if (parent_status != 0)
goto lose;
- }
+ if (dirstream && __closedir (dirstream) != 0)
+ {
+ dirstream = NULL;
+ goto lose;
+ }
+
+ dotdev = st.st_dev;
+ dotino = st.st_ino;
+ }
/* Figure out if this directory is a mount point. */
- dotdev = st.st_dev;
- dotino = st.st_ino;
- mount_point = dotdev != thisdev;
+ bool mount_point = dotdev != thisdev;
/* Search for the last directory. */
#if HAVE_OPENAT_SUPPORT
goto lose;
dotlist[dotlen++] = '/';
#endif
+ struct dirent64 *d;
+ bool use_d_ino = true;
for (;;)
{
/* Clear errno to distinguish EOF from error if readdir returns
}
{
+ struct stat64 st;
int entry_status;
#if HAVE_OPENAT_SUPPORT
entry_status = __fstatat64 (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
}
}
- dirroom = dirp - dir;
- namlen = _D_EXACT_NAMLEN (d);
+ size_t dirroom = dirp - dir;
+ size_t namlen = _D_EXACT_NAMLEN (d);
if (dirroom <= namlen)
{
free (dotlist);
#endif
- used = dir + allocated - dirp;
+ size_t used = dir + allocated - dirp;
memmove (dir, dirp, used);
if (size == 0)
ssize_t
getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp)
{
- ssize_t result;
- size_t cur_len = 0;
-
if (lineptr == NULL || n == NULL
/* glibc already declares this function as __nonnull ((4)).
Avoid a gcc warning "‘nonnull’ argument ‘fp’ compared to NULL". */
flockfile (fp);
+ ssize_t result;
+
if (*lineptr == NULL || *n == 0)
{
char *new_lineptr;
*lineptr = new_lineptr;
}
+ size_t cur_len = 0;
for (;;)
{
int i;
size_t needed_max =
SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
size_t needed = 2 * *n + 1; /* Be generous. */
- char *new_lineptr;
if (needed_max < needed)
needed = needed_max;
goto unlock_return;
}
- new_lineptr = (char *) realloc (*lineptr, needed);
+ char *new_lineptr = (char *) realloc (*lineptr, needed);
if (new_lineptr == NULL)
{
alloc_failed ();
return getdomainname (name, (int) len);
#elif HAVE_SYSINFO && HAVE_SYS_SYSTEMINFO_H && defined SI_SRPC_DOMAIN
/* Solaris */
- int ret;
-
/* The third argument is a 'long', but the return value must fit in an
'int', therefore it's better to avoid arguments > INT_MAX. */
- ret = sysinfo (SI_SRPC_DOMAIN, name, len > INT_MAX ? INT_MAX : len);
+ int ret = sysinfo (SI_SRPC_DOMAIN, name, len > INT_MAX ? INT_MAX : len);
if (ret < 0)
/* errno is set here. */
return -1;
int
getentropy (void *buffer, size_t length)
{
- char *buf = buffer;
if (length <= 256)
- for (;;)
- {
- ssize_t bytes;
- if (length == 0)
- return 0;
- while ((bytes = getrandom (buf, length, 0)) < 0)
- if (errno != EINTR)
- return -1;
- if (bytes == 0)
- break;
- buf += bytes;
- length -= bytes;
- }
+ {
+ char *buf = buffer;
+ for (;;)
+ {
+ if (length == 0)
+ return 0;
+ ssize_t bytes;
+ while ((bytes = getrandom (buf, length, 0)) < 0)
+ if (errno != EINTR)
+ return -1;
+ if (bytes == 0)
+ break;
+ buf += bytes;
+ length -= bytes;
+ }
+ }
errno = EIO;
return -1;
int
rpl_getgroups (int n, gid_t *group)
{
- int n_groups;
- GETGROUPS_T *gbuf;
-
if (n < 0)
{
errno = EINVAL;
if (n != 0 || !GETGROUPS_ZERO_BUG)
{
- int result;
- if (sizeof *group == sizeof *gbuf)
+ if (sizeof *group == sizeof (GETGROUPS_T))
return getgroups (n, (GETGROUPS_T *) group);
- if (SIZE_MAX / sizeof *gbuf <= n)
+ if (SIZE_MAX / sizeof (GETGROUPS_T) <= n)
{
errno = ENOMEM;
return -1;
}
- gbuf = malloc (n * sizeof *gbuf);
+ GETGROUPS_T *gbuf = malloc (n * sizeof *gbuf);
if (!gbuf)
return -1;
- result = getgroups (n, gbuf);
+ int result = getgroups (n, gbuf);
if (0 <= result)
{
n = result;
/* No need to worry about address arithmetic overflow here,
since the ancient systems that we're running on have low
limits on the number of secondary groups. */
- gbuf = malloc (n * sizeof *gbuf);
+ GETGROUPS_T *gbuf = malloc (n * sizeof *gbuf);
if (!gbuf)
return -1;
- n_groups = getgroups (n, gbuf);
+ int n_groups = getgroups (n, gbuf);
if (n_groups == -1 ? errno != EINVAL : n_groups < n)
- break;
+ {
+ free (gbuf);
+ return n_groups;
+ }
free (gbuf);
n *= 2;
}
-
- free (gbuf);
- return n_groups;
}
#endif /* HAVE_GETGROUPS */
int
rpl_gethostname (char *name, size_t len)
{
- int r;
-
if (len > INT_MAX)
len = INT_MAX;
gl_sockets_startup (SOCKETS_1_1);
- r = gethostname (name, (int) len);
+ int r = gethostname (name, (int) len);
if (r < 0)
set_winsock_errno ();
# if !defined (LDAV_DONE) && defined (HAVE_LIBKSTAT) /* Solaris <= 2.6 */
/* Use libkstat because we don't have to be root. */
# define LDAV_DONE
- kstat_ctl_t *kc;
- kstat_t *ksp;
- kstat_named_t *kn;
- int saved_errno;
-
- kc = kstat_open ();
- if (kc == NULL)
- return -1;
- ksp = kstat_lookup (kc, "unix", 0, "system_misc");
- if (ksp == NULL)
- return -1;
- if (kstat_read (kc, ksp, 0) == -1)
- return -1;
-
-
- kn = kstat_data_lookup (ksp, "avenrun_1min");
- if (kn == NULL)
- {
- /* Return -1 if no load average information is available. */
- nelem = 0;
- elem = -1;
- }
-
- if (nelem >= 1)
- loadavg[elem++] = (double) kn->value.ul / FSCALE;
-
- if (nelem >= 2)
- {
- kn = kstat_data_lookup (ksp, "avenrun_5min");
- if (kn != NULL)
- {
- loadavg[elem++] = (double) kn->value.ul / FSCALE;
+ {
+ kstat_ctl_t *kc = kstat_open ();
+ if (kc == NULL)
+ return -1;
+ kstat_t *ksp = kstat_lookup (kc, "unix", 0, "system_misc");
+ if (ksp == NULL)
+ return -1;
+ if (kstat_read (kc, ksp, 0) == -1)
+ return -1;
- if (nelem >= 3)
- {
- kn = kstat_data_lookup (ksp, "avenrun_15min");
- if (kn != NULL)
- loadavg[elem++] = (double) kn->value.ul / FSCALE;
- }
- }
- }
+ kstat_named_t *kn = kstat_data_lookup (ksp, "avenrun_1min");
+ if (kn == NULL)
+ {
+ /* Return -1 if no load average information is available. */
+ nelem = 0;
+ elem = -1;
+ }
+
+ if (nelem >= 1)
+ loadavg[elem++] = (double) kn->value.ul / FSCALE;
+
+ if (nelem >= 2)
+ {
+ kn = kstat_data_lookup (ksp, "avenrun_5min");
+ if (kn != NULL)
+ {
+ loadavg[elem++] = (double) kn->value.ul / FSCALE;
+
+ if (nelem >= 3)
+ {
+ kn = kstat_data_lookup (ksp, "avenrun_15min");
+ if (kn != NULL)
+ loadavg[elem++] = (double) kn->value.ul / FSCALE;
+ }
+ }
+ }
- saved_errno = errno;
- kstat_close (kc);
- errno = saved_errno;
+ int saved_errno = errno;
+ kstat_close (kc);
+ errno = saved_errno;
+ }
# endif /* HAVE_LIBKSTAT */
# if !defined (LDAV_DONE) && defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
char ldavgbuf[3 * (INT_STRLEN_BOUND (int) + sizeof ".00 ")];
char const *ptr = ldavgbuf;
- int fd, count, saved_errno;
- fd = open ("/proc/loadavg", O_RDONLY | O_CLOEXEC);
+ int fd = open ("/proc/loadavg", O_RDONLY | O_CLOEXEC);
if (fd == -1)
return -1;
- count = read (fd, ldavgbuf, sizeof ldavgbuf - 1);
- saved_errno = errno;
+ int count = read (fd, ldavgbuf, sizeof ldavgbuf - 1);
+ int saved_errno = errno;
(void) close (fd);
errno = saved_errno;
if (count <= 0)
for (elem = 0; elem < nelem; elem++)
{
- double numerator = 0;
- double denominator = 1;
-
while (*ptr == ' ')
ptr++;
break;
}
+ double numerator = 0;
+ double denominator = 1;
+
while ('0' <= *ptr && *ptr <= '9')
numerator = 10 * numerator + (*ptr++ - '0');
# define NETBSD_LDAV_FILE "/kern/loadavg"
# endif
- unsigned long int load_ave[3], scale;
- int count;
- char readbuf[4 * INT_BUFSIZE_BOUND (unsigned long int) + 1];
int fd = open (NETBSD_LDAV_FILE, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return fd;
+
+ char readbuf[4 * INT_BUFSIZE_BOUND (unsigned long int) + 1];
int nread = read (fd, readbuf, sizeof readbuf - 1);
int saved_errno = errno;
close (fd);
return -1;
}
readbuf[nread] = '\0';
- count = sscanf (readbuf, "%lu %lu %lu %lu\n",
- &load_ave[0], &load_ave[1], &load_ave[2],
- &scale);
+
+ unsigned long int load_ave[3], scale;
+ int count = sscanf (readbuf, "%lu %lu %lu %lu\n",
+ &load_ave[0], &load_ave[1], &load_ave[2],
+ &scale);
if (count != 4)
{
errno = ENOTSUP;
# define LDAV_DONE
/* The NeXT code was adapted from iscreen 3.2. */
- host_t host;
- struct processor_set_basic_info info;
- unsigned int info_count;
-
/* We only know how to get the 1-minute average for this system,
so even if the caller asks for more than 1, we only return 1. */
if (getloadavg_initialized)
{
- info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
+ host_t host;
+ struct processor_set_basic_info info;
+ unsigned int info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
if (processor_set_info (default_set, PROCESSOR_SET_BASIC_INFO, &host,
(processor_set_info_t) &info, &info_count)
!= KERN_SUCCESS)
can be gathered with inq_stats system calls.
We only know how to get the 1-minute average for this system. */
- struct proc_summary proc_sum_data;
- struct stat_descr proc_info;
- double load;
- register unsigned int j;
-
if (cpus == 0)
{
register unsigned int c;
samples = cpus < 2 ? 3 : (2 * cpus / 3);
}
+ struct proc_summary proc_sum_data;
+
+ struct stat_descr proc_info;
proc_info.sd_next = 0;
proc_info.sd_subsys = SUBSYS_PROC;
proc_info.sd_type = PROCTYPE_SUMMARY;
if (inq_stats (1, &proc_info) != 0)
return -1;
- load = proc_sum_data.ps_nrunnable;
- j = 0;
+ double load = proc_sum_data.ps_nrunnable;
+ register unsigned int j = 0;
for (unsigned int i = samples - 1; i > 0; --i)
{
load += proc_sum_data.ps_nrun[j];
# define LDAV_PRIVILEGED /* This code requires special installation. */
- LOAD_AVE_TYPE load_ave[3];
-
/* Get the address of LDAV_SYMBOL. */
if (offset == 0)
{
# endif /* SUNOS_5 */
}
+ LOAD_AVE_TYPE load_ave[3];
+
/* If we can, get the load average values. */
if (offset && getloadavg_initialized)
{
newlocale (int category_mask, const char *name, locale_t base)
#undef newlocale
{
- struct locale_categories_names names;
- struct locale_hash_node *node;
- locale_t result;
-
/* Make sure name has indefinite extent. */
if (((LC_CTYPE_MASK | LC_NUMERIC_MASK | LC_TIME_MASK | LC_COLLATE_MASK
| LC_MONETARY_MASK | LC_MESSAGES_MASK)
name = struniq (name);
/* Determine the category names of the result. */
+ struct locale_categories_names names;
if (((LC_CTYPE_MASK | LC_NUMERIC_MASK | LC_TIME_MASK | LC_COLLATE_MASK
| LC_MONETARY_MASK | LC_MESSAGES_MASK)
& ~category_mask) == 0)
for (int i = 0; i < 6; i++)
{
int category = i + LCMIN;
- int mask;
+ int mask;
switch (category)
{
case LC_CTYPE:
for (int i = 0; i < 6; i++)
{
int category = i + LCMIN;
- int mask;
+ int mask;
switch (category)
{
case LC_CTYPE:
{
/* Look up the names of base in the hash table. Like multiple calls
of get_locale_t_name, but locking only once. */
- struct locale_hash_node *p;
/* Lock while looking up the hash node. */
gl_rwlock_rdlock (locale_lock);
+ struct locale_hash_node *p;
for (p = locale_hash_table[locale_hash_function (base) % LOCALE_HASH_TABLE_SIZE];
p != NULL;
p = p->next)
for (int i = 0; i < 6; i++)
{
int category = i + LCMIN;
- int mask;
+ int mask;
switch (category)
{
case LC_CTYPE:
}
}
- node = (struct locale_hash_node *) malloc (sizeof (struct locale_hash_node));
+ struct locale_hash_node *node =
+ (struct locale_hash_node *) malloc (sizeof (struct locale_hash_node));
if (node == NULL)
/* errno is set to ENOMEM. */
return NULL;
- result = newlocale (category_mask, name, base);
+ locale_t result = newlocale (category_mask, name, base);
if (result == NULL)
{
free (node);
{
size_t hashcode = locale_hash_function (result);
size_t slot = hashcode % LOCALE_HASH_TABLE_SIZE;
- struct locale_hash_node *p;
/* Lock while inserting the new node. */
gl_rwlock_wrlock (locale_lock);
+ struct locale_hash_node *p;
for (p = locale_hash_table[slot]; p != NULL; p = p->next)
if (p->locale == result)
{
duplocale (locale_t locale)
#undef duplocale
{
- struct locale_hash_node *node;
- locale_t result;
-
if (locale == NULL)
/* Invalid argument. */
abort ();
- node = (struct locale_hash_node *) malloc (sizeof (struct locale_hash_node));
+ struct locale_hash_node *node =
+ (struct locale_hash_node *) malloc (sizeof (struct locale_hash_node));
if (node == NULL)
/* errno is set to ENOMEM. */
return NULL;
- result = duplocale (locale);
+ locale_t result = duplocale (locale);
if (result == NULL)
{
free (node);
}
else
{
- struct locale_hash_node *p;
-
/* Lock once, for the lookup and the insertion. */
gl_rwlock_wrlock (locale_lock);
+ struct locale_hash_node *p;
for (p = locale_hash_table[locale_hash_function (locale) % LOCALE_HASH_TABLE_SIZE];
p != NULL;
p = p->next)
{
size_t hashcode = locale_hash_function (result);
size_t slot = hashcode % LOCALE_HASH_TABLE_SIZE;
- struct locale_hash_node *p;
+ struct locale_hash_node *p;
for (p = locale_hash_table[slot]; p != NULL; p = p->next)
if (p->locale == result)
{
{
size_t hashcode = locale_hash_function (locale);
size_t slot = hashcode % LOCALE_HASH_TABLE_SIZE;
- struct locale_hash_node *found;
- found = NULL;
+ struct locale_hash_node *found = NULL;
/* Lock while removing the hash node. */
gl_rwlock_wrlock (locale_lock);
for (struct locale_hash_node **p = &locale_hash_table[slot]; *p != NULL; p = &(*p)->next)
#elif (defined __FreeBSD__ || defined __DragonFly__) || (defined __APPLE__ && defined __MACH__)
/* FreeBSD >= 9.1, Mac OS X */
int mask;
-
switch (category)
{
case LC_CTYPE:
#undef getlogin_r
#if defined _WIN32 && ! defined __CYGWIN__
/* Native Windows platform. */
- DWORD sz;
/* When size > 0x7fff, the doc says that GetUserName will fail.
Actually, on Windows XP SP3, it succeeds. But let's be safe,
for the sake of older Windows versions. */
if (size > 0x7fff)
size = 0x7fff;
- sz = size;
+ DWORD sz = size;
if (!GetUserName (name, &sz))
{
if (GetLastError () == ERROR_INSUFFICIENT_BUFFER)
return ret;
#else
/* Platform with a getlogin() function. */
- char *n;
- size_t nlen;
-
errno = 0;
- n = getlogin ();
+ char *n = getlogin ();
if (!n)
/* ENOENT is a reasonable errno value if getlogin returns NULL. */
return (errno != 0 ? errno : ENOENT);
- nlen = strlen (n);
+ size_t nlen = strlen (n);
if (size <= nlen)
return ERANGE;
memcpy (name, n, nlen + 1);
getndelim2 (char **lineptr, size_t *linesize, size_t offset, size_t nmax,
int delim1, int delim2, FILE *stream)
{
- size_t nbytes_avail; /* Allocated but unused bytes in *LINEPTR. */
- char *read_pos; /* Where we're reading into *LINEPTR. */
- ssize_t bytes_stored = -1;
char *ptr = *lineptr;
size_t size = *linesize;
- bool found_delimiter;
-
if (!ptr)
{
size = nmax < MIN_CHUNK ? nmax : MIN_CHUNK;
return -1;
}
+ ssize_t bytes_stored = -1;
+
if (size < offset)
goto done;
- nbytes_avail = size - offset;
- read_pos = ptr + offset;
+ size_t nbytes_avail = /* Allocated but unused bytes in *LINEPTR. */
+ size - offset;
+ char *read_pos = ptr + offset; /* Where we're reading into *LINEPTR. */
if (nbytes_avail == 0 && nmax <= size)
goto done;
flockfile (stream);
- found_delimiter = false;
+ bool found_delimiter = false;
do
{
/* Here always ptr + size == read_pos + nbytes_avail.
int bottom = d->__first_nonopt;
int middle = d->__last_nonopt;
int top = d->optind;
- char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
- tem = argv[bottom + i];
+ char *tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
- tem = argv[bottom + i];
+ char *tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
int long_only, struct _getopt_data *d,
int print_errors, const char *prefix)
{
- char *nameend;
- size_t namelen;
- const struct option *p;
- const struct option *pfound = NULL;
- int n_options;
- int option_index;
+ char *nameend;
for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
- namelen = nameend - d->__nextchar;
+ size_t namelen = nameend - d->__nextchar;
/* First look for an exact match, counting the options as a side
effect. */
- for (p = longopts, n_options = 0; p->name; p++, n_options++)
- if (!strncmp (p->name, d->__nextchar, namelen)
- && namelen == strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- option_index = n_options;
- break;
- }
+ const struct option *pfound = NULL;
+ int n_options;
+ int option_index;
+ {
+ const struct option *p;
+ for (p = longopts, n_options = 0; p->name; p++, n_options++)
+ if (!strncmp (p->name, d->__nextchar, namelen)
+ && namelen == strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ option_index = n_options;
+ break;
+ }
+ }
if (pfound == NULL)
{
unsigned char ambig_fallback;
void *ambig_malloced = NULL;
int indfound = -1;
+ const struct option *p;
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, d->__nextchar, namelen))
const struct option *longopts, int *longind,
int long_only, struct _getopt_data *d, int posixly_correct)
{
- int print_errors = d->opterr;
-
if (argc < 1)
return -1;
+ int print_errors = d->opterr;
+
d->optarg = NULL;
if (d->optind == 0 || !d->__initialized)
if (long_only && (argv[d->optind][2]
|| !strchr (optstring, argv[d->optind][1])))
{
- int code;
d->__nextchar = argv[d->optind] + 1;
- code = process_long_option (argc, argv, optstring, longopts,
- longind, long_only, d,
- print_errors, "-");
+ int code = process_long_option (argc, argv, optstring, longopts,
+ longind, long_only, d,
+ print_errors, "-");
if (code != -1)
return code;
}
const struct option *longopts, int *longind, int long_only,
int posixly_correct)
{
- int result;
-
getopt_data.optind = optind;
getopt_data.opterr = opterr;
- result = _getopt_internal_r (argc, argv, optstring, longopts,
- longind, long_only, &getopt_data,
- posixly_correct);
+ int result = _getopt_internal_r (argc, argv, optstring, longopts,
+ longind, long_only, &getopt_data,
+ posixly_correct);
optind = getopt_data.optind;
optarg = getopt_data.optarg;
int
main (int argc, char **argv)
{
- int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
- c = getopt (argc, argv, "abc:d:0123456789");
+ int c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
break;
int
main (int argc, char **argv)
{
- int c;
int digit_optind = 0;
while (1)
{0, 0, 0, 0}
};
- c = getopt_long (argc, argv, "abc:d:0123456789",
- long_options, &option_index);
+ int c = getopt_long (argc, argv, "abc:d:0123456789",
+ long_options, &option_index);
if (c == -1)
break;
char *
getpass (const char *prompt)
{
- FILE *tty;
- FILE *in, *out;
-# if HAVE_TCGETATTR
- struct termios s, t;
-# endif
- bool tty_changed = false;
- static char *buf;
- static size_t bufsize;
- ssize_t nread;
-
/* Try to write to and read from the terminal if we can.
If we can't open the terminal, use stderr and stdin. */
- tty = fopen ("/dev/tty", "w+e");
+ FILE *tty = fopen ("/dev/tty", "w+e");
+ FILE *in, *out;
if (tty == NULL)
{
in = stdin;
flockfile (out);
+ bool tty_changed = false;
+
/* Turn echoing off if it is on now. */
# if HAVE_TCGETATTR
+ struct termios s, t;
if (tcgetattr (fileno (in), &t) == 0)
{
/* Save the old one. */
}
/* Read the password. */
- nread = getline (&buf, &bufsize, in);
+ static char *buf;
+ static size_t bufsize;
+ ssize_t nread = getline (&buf, &bufsize, in);
/* According to the C standard, input may not be followed by output
on the same stream without an intervening call to a file
char *
getpass (const char *prompt)
{
- char getpassbuf[PASS_MAX + 1];
- size_t i = 0;
- int c;
-
if (prompt)
{
fputs (prompt, stderr);
fflush (stderr);
}
- for (;;)
- {
- c = _getch ();
- if (c == '\r')
- {
- getpassbuf[i] = '\0';
- break;
- }
- else if (i < PASS_MAX)
- {
- getpassbuf[i++] = c;
- }
-
- if (i >= PASS_MAX)
- {
- getpassbuf[i] = '\0';
- break;
- }
- }
+ char getpassbuf[PASS_MAX + 1];
+ {
+ size_t i = 0;
+ for (;;)
+ {
+ int c = _getch ();
+ if (c == '\r')
+ {
+ getpassbuf[i] = '\0';
+ break;
+ }
+ else if (i < PASS_MAX)
+ {
+ getpassbuf[i++] = c;
+ }
+
+ if (i >= PASS_MAX)
+ {
+ getpassbuf[i] = '\0';
+ break;
+ }
+ }
+ }
if (prompt)
{
return p;
# elif defined __SCO_VERSION__ || defined __sysv5__ /* SCO OpenServer6/UnixWare */
char buf[80];
- int fd;
sprintf (buf, "/proc/%d/cmdline", getpid());
- fd = open (buf, O_RDONLY);
+ int fd = open (buf, O_RDONLY);
if (0 <= fd)
{
size_t n = read (fd, buf, 79);
if (n > 0)
{
buf[n] = '\0'; /* Guarantee null-termination */
- char *progname;
- progname = strrchr (buf, '/');
+ char *progname = strrchr (buf, '/');
if (progname)
- {
- progname = progname + 1; /* Skip the '/' */
- }
+ progname = progname + 1; /* Skip the '/' */
else
- {
- progname = buf;
- }
- char *ret;
- ret = malloc (strlen (progname) + 1);
+ progname = buf;
+ char *ret = malloc (strlen (progname) + 1);
if (ret)
{
strcpy (ret, progname);
clock_t user_ticks;
clock_t system_ticks;
- uint64_t user_usec;
- uint64_t system_usec;
-
if (who == RUSAGE_CHILDREN)
{
user_ticks = time.tms_cutime;
system_ticks = time.tms_stime;
}
- user_usec =
+ uint64_t user_usec =
(((uint64_t) user_ticks * (uint64_t) 1000000U)
+ clocks_per_second / 2) / clocks_per_second;
- system_usec =
+ uint64_t system_usec =
(((uint64_t) system_ticks * (uint64_t) 1000000U)
+ clocks_per_second / 2) / clocks_per_second;
{
int milliseconds;
int milliseconds_len = sizeof (int);
- size_t n;
r = getsockopt (sock, level, optname, (char *) &milliseconds,
&milliseconds_len);
.tv_sec = milliseconds / 1000,
.tv_usec = (milliseconds % 1000) * 1000
};
- n = sizeof (struct timeval);
+ size_t n = sizeof (struct timeval);
if (n > *optlen)
n = *optlen;
memcpy (optval, &tv, n);
int
getsubopt (char **optionp, char *const *tokens, char **valuep)
{
- char *endp, *vstart;
- int cnt;
-
if (**optionp == '\0')
return -1;
/* Find end of next token. */
- endp = __strchrnul (*optionp, ',');
+ char *endp = __strchrnul (*optionp, ',');
/* Find start of value. */
- vstart = memchr (*optionp, '=', endp - *optionp);
+ char *vstart = memchr (*optionp, '=', endp - *optionp);
if (vstart == NULL)
vstart = endp;
/* Try to match the characters between *OPTIONP and VSTART against
one of the TOKENS. */
- for (cnt = 0; tokens[cnt] != NULL; ++cnt)
+ for (int cnt = 0; tokens[cnt] != NULL; ++cnt)
if (strncmp (*optionp, tokens[cnt], vstart - *optionp) == 0
&& tokens[cnt][vstart - *optionp] == '\0')
{
if (msg_ctxt_id != NULL)
#endif
{
- int found_translation;
memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
msg_ctxt_id[msgctxt_len - 1] = '\004';
memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
translation = dcgettext (domain, msg_ctxt_id, category);
- found_translation = (translation != msg_ctxt_id);
+ int found_translation = (translation != msg_ctxt_id);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
free (msg_ctxt_id);
if (msg_ctxt_id != NULL)
#endif
{
- int found_translation;
memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
msg_ctxt_id[msgctxt_len - 1] = '\004';
memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
- found_translation = !(translation == msg_ctxt_id || translation == msgid_plural);
+ int found_translation = !(translation == msg_ctxt_id || translation == msgid_plural);
#if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
if (msg_ctxt_id != buf)
free (msg_ctxt_id);
microseconds.
More discussion on this topic:
<http://www.windowstimestamp.com/description>. */
- FILETIME current_time;
-
# if !(_WIN32_WINNT >= _WIN32_WINNT_WIN8)
if (!initialized)
initialize ();
# endif
+
+ FILETIME current_time;
if (GetSystemTimePreciseAsFileTimeFunc != NULL)
GetSystemTimePreciseAsFileTimeFunc (¤t_time);
else
setgrent ();
while (1)
{
- struct group *grp;
-
errno = 0;
- grp = getgrent ();
+ struct group *grp = getgrent ();
if (grp == NULL)
break;
for (char **cp = grp->gr_mem; *cp; ++cp)
{
- int n;
-
if (streq (username, *cp))
{
/* See if this group number is already on the list. */
+ int n;
for (n = 0; n < count; ++n)
if (grouplist && grouplist[n] == grp->gr_gid)
break;
{
/* In Linux >= 4.7, the umask can be retrieved from an "Umask:" line in the
/proc/self/status file. */
- char buf[4096];
int fd = open ("/proc/self/status", O_RDONLY);
if (fd >= 0)
{
+ char buf[4096];
ssize_t n = read (fd, buf, sizeof (buf));
if (n > 0)
{
{
for (;;)
{
- gl_list_node_t child;
- int previous_balance;
- int balance_diff;
- gl_list_node_t nodeleft;
- gl_list_node_t noderight;
-
- child = node;
+ gl_list_node_t child = node;
node = parent;
- previous_balance = node->balance;
+ int previous_balance = node->balance;
/* The balance of NODE is incremented by BALANCE_DIFF: +1 if the right
branch's height has increased by 1 or the left branch's height has
decreased by 1, -1 if the right branch's height has decreased by 1 or
the left branch's height has increased by 1, 0 if no height change. */
+ int balance_diff;
if (node->left != NULL || node->right != NULL)
balance_diff = (child == node->right ? height_diff : -height_diff);
else
else
abort ();
- nodeleft = node->left;
- noderight = node->right;
+ gl_list_node_t nodeleft = node->left;
+ gl_list_node_t noderight = node->right;
if (balance_diff < 0)
{
else
{
/* Replace node with the rightmost element of the node->left subtree. */
- gl_list_node_t subst;
- gl_list_node_t subst_parent;
- gl_list_node_t child;
+ gl_list_node_t subst;
for (subst = node->left; subst->right != NULL; )
subst = subst->right;
- subst_parent = subst->parent;
+ gl_list_node_t subst_parent = subst->parent;
- child = subst->left;
+ gl_list_node_t child = subst->left;
/* The case subst_parent == node is special: If we do nothing special,
we get confusion about node->left, subst->left and child->parent.
else
{
gl_list_node_t node;
-
for (node = list->root; node->left != NULL; )
node = node->left;
else
{
gl_list_node_t node;
-
for (node = list->root; node->right != NULL; )
node = node->right;
{
/* Create new node. */
gl_list_node_t new_node;
- bool height_inc;
new_node =
(struct gl_list_node_impl *) malloc (sizeof (struct gl_list_node_impl));
#endif
/* Add it to the tree. */
+ bool height_inc;
if (node->left == NULL)
{
node->left = new_node;
{
/* Create new node. */
gl_list_node_t new_node;
- bool height_inc;
new_node =
(struct gl_list_node_impl *) malloc (sizeof (struct gl_list_node_impl));
#endif
/* Add it to the tree. */
+ bool height_inc;
if (node->right == NULL)
{
node->right = new_node;
if (new_size > container->table_size)
{
gl_hash_entry_t *old_table = container->table;
- /* Allocate the new table. */
- gl_hash_entry_t *new_table;
+ /* Allocate the new table. */
if (size_overflow_p (xtimes (new_size, sizeof (gl_hash_entry_t))))
goto fail;
- new_table =
+ gl_hash_entry_t *new_table =
(gl_hash_entry_t *) calloc (new_size, sizeof (gl_hash_entry_t));
if (new_table == NULL)
goto fail;
gl_linked_get_at (gl_list_t list, size_t position)
{
size_t count = list->count;
- gl_list_node_t node;
if (!(position < count))
/* Invalid argument. */
abort ();
/* Here we know count > 0. */
+ gl_list_node_t node;
if (position <= ((count - 1) / 2))
{
node = list->root.next;
gl_linked_nx_set_at (gl_list_t list, size_t position, const void *elt)
{
size_t count = list->count;
- gl_list_node_t node;
if (!(position < count))
/* Invalid argument. */
abort ();
/* Here we know count > 0. */
+ gl_list_node_t node;
if (position <= ((count - 1) / 2))
{
node = list->root.next;
}
}
#else
- gl_listelement_equals_fn equals = list->base.equals_fn;
- gl_list_node_t node = list->root.next;
-
end_index -= start_index;
+
+ gl_list_node_t node = list->root.next;
for (; start_index > 0; start_index--)
node = node->next;
+ gl_listelement_equals_fn equals = list->base.equals_fn;
if (equals != NULL)
{
for (; end_index > 0; node = node->next, end_index--)
: (size_t)(uintptr_t) elt);
size_t bucket = hashcode % list->table_size;
gl_listelement_equals_fn equals = list->base.equals_fn;
- gl_list_node_t node;
/* First step: Look up the node. */
+ gl_list_node_t node;
if (!list->base.allow_duplicates)
{
/* Look for the first match in the hash bucket. */
{
/* We need the match with the smallest index. But we don't have
a fast mapping node -> index. So we have to walk the list. */
- size_t index;
-
- index = start_index;
+ size_t index = start_index;
node = list->root.next;
for (; start_index > 0; start_index--)
node = node->next;
else
{
size_t index = 0;
-
for (; node->prev != &list->root; node = node->prev)
index++;
return (size_t)(-1);
}
#else
- gl_listelement_equals_fn equals = list->base.equals_fn;
size_t index = start_index;
- gl_list_node_t node = list->root.next;
+ gl_list_node_t node = list->root.next;
for (; start_index > 0; start_index--)
node = node->next;
+ gl_listelement_equals_fn equals = list->base.equals_fn;
if (equals != NULL)
{
for (;
/* Add new_node to the list. */
if (position <= (count / 2))
{
- gl_list_node_t node;
-
- node = &list->root;
+ gl_list_node_t node = &list->root;
for (; position > 0; position--)
node = node->next;
+
new_node->prev = node;
ASYNCSAFE(gl_list_node_t) new_node->next = node->next;
new_node->next->prev = new_node;
}
else
{
- gl_list_node_t node;
-
position = count - position;
- node = &list->root;
+
+ gl_list_node_t node = &list->root;
for (; position > 0; position--)
node = node->prev;
+
ASYNCSAFE(gl_list_node_t) new_node->next = node;
new_node->prev = node->prev;
ASYNCSAFE(gl_list_node_t) new_node->prev->next = new_node;
static bool
gl_linked_remove_node (gl_list_t list, gl_list_node_t node)
{
- gl_list_node_t prev;
- gl_list_node_t next;
-
#if WITH_HASHTABLE
/* Remove node from the hash table. */
remove_from_bucket (list, node);
#endif
/* Remove node from the list. */
- prev = node->prev;
- next = node->next;
+ gl_list_node_t prev = node->prev;
+ gl_list_node_t next = node->next;
ASYNCSAFE(gl_list_node_t) prev->next = next;
next->prev = prev;
gl_linked_remove_at (gl_list_t list, size_t position)
{
size_t count = list->count;
- gl_list_node_t removed_node;
if (!(position < count))
/* Invalid argument. */
abort ();
/* Here we know count > 0. */
+ gl_list_node_t removed_node;
if (position <= ((count - 1) / 2))
{
- gl_list_node_t node;
- gl_list_node_t after_removed;
-
- node = &list->root;
+ gl_list_node_t node = &list->root;
for (; position > 0; position--)
node = node->next;
+
removed_node = node->next;
- after_removed = node->next->next;
+ gl_list_node_t after_removed = node->next->next;
ASYNCSAFE(gl_list_node_t) node->next = after_removed;
after_removed->prev = node;
}
else
{
- gl_list_node_t node;
- gl_list_node_t before_removed;
-
position = count - 1 - position;
- node = &list->root;
+
+ gl_list_node_t node = &list->root;
for (; position > 0; position--)
node = node->prev;
+
removed_node = node->prev;
- before_removed = node->prev->prev;
+ gl_list_node_t before_removed = node->prev->prev;
node->prev = before_removed;
ASYNCSAFE(gl_list_node_t) before_removed->next = node;
}
if (n1 > n2 && n1 > n3)
{
/* n1 is the maximum, use n2 and n3. */
- gl_list_node_t node;
-
- node = &list->root;
+ gl_list_node_t node = &list->root;
for (size_t i = n3; i > 0; i--)
node = node->prev;
result.q = node;
+
for (size_t i = n2; i > 0; i--)
node = node->prev;
result.p = node;
else if (n2 > n3)
{
/* n2 is the maximum, use n1 and n3. */
- gl_list_node_t node;
-
- node = list->root.next;
+ gl_list_node_t node = list->root.next;
for (size_t i = n1; i > 0; i--)
node = node->next;
result.p = node;
else
{
/* n3 is the maximum, use n1 and n2. */
- gl_list_node_t node;
-
- node = list->root.next;
+ gl_list_node_t node = list->root.next;
for (size_t i = n1; i > 0; i--)
node = node->next;
result.p = node;
+
for (size_t i = n2; i > 0; i--)
node = node->next;
result.q = node;
{
/* Here we know low < count. */
size_t position = low;
- gl_list_node_t node;
+ gl_list_node_t node;
if (position <= ((count - 1) / 2))
{
node = list->root.next;
/* Here we know low < count. */
size_t index = low;
size_t position = low;
- gl_list_node_t node;
+ gl_list_node_t node;
if (position <= ((count - 1) / 2))
{
node = list->root.next;
/* At this point, parent = node->parent != NULL.
Think of node->color being RED (although node->color is not yet
assigned.) */
- gl_list_node_t grandparent;
- gl_list_node_t uncle;
if (parent->color == BLACK)
{
return;
}
- grandparent = parent->parent;
+ gl_list_node_t grandparent = parent->parent;
/* Since parent is RED, we know that
grandparent is != NULL and colored BLACK. */
+ gl_list_node_t uncle;
if (grandparent->left == parent)
uncle = grandparent->right;
else if (grandparent->right == parent)
else
{
/* Replace node with the rightmost element of the node->left subtree. */
- gl_list_node_t subst;
- gl_list_node_t subst_parent;
- gl_list_node_t child;
- color_t removed_color;
+ gl_list_node_t subst;
for (subst = node->left; subst->right != NULL; )
subst = subst->right;
- subst_parent = subst->parent;
+ gl_list_node_t subst_parent = subst->parent;
- child = subst->left;
+ gl_list_node_t child = subst->left;
- removed_color = subst->color;
+ color_t removed_color = subst->color;
/* The case subst_parent == node is special: If we do nothing special,
we get confusion about node->left, subst->left and child->parent.
else
{
gl_list_node_t node;
-
for (node = list->root; node->left != NULL; )
node = node->left;
else
{
gl_list_node_t node;
-
for (node = list->root; node->right != NULL; )
node = node->right;
gl_tree_iterator (gl_list_t list)
{
gl_list_iterator_t result;
- gl_list_node_t node;
result.vtable = list->base.vtable;
result.list = list;
- /* Start node is the leftmost node. */
- node = list->root;
- if (node != NULL)
- while (node->left != NULL)
- node = node->left;
- result.p = node;
+ {
+ /* Start node is the leftmost node. */
+ gl_list_node_t node = list->root;
+ if (node != NULL)
+ while (node->left != NULL)
+ node = node->left;
+ result.p = node;
+ }
/* End point is past the rightmost node. */
result.q = NULL;
#if defined GCC_LINT || defined lint
size_t low, size_t high,
const void *elt)
{
- gl_list_node_t node;
- size_t position;
-
if (!(low <= high
&& high <= (list->root != NULL ? list->root->branch_size : 0)))
/* Invalid arguments. */
abort ();
+ gl_list_node_t node;
+ size_t position;
+
for (node = list->root, position = 0; node != NULL; )
{
size_t left_branch_size =
gl_tree_nx_getput (gl_omap_t map, const void *key, const void *value,
const void **oldvaluep)
{
- gl_mapkey_compar_fn compar;
gl_omap_node_t node = map->root;
if (node == NULL)
return 1;
}
- compar = map->base.compar_fn;
+ gl_mapkey_compar_fn compar = map->base.compar_fn;
for (;;)
{
gl_tree_iterator (gl_omap_t map)
{
gl_omap_iterator_t result;
- gl_omap_node_t node;
result.vtable = map->base.vtable;
result.map = map;
- /* Start node is the leftmost node. */
- node = map->root;
- if (node != NULL)
- while (node->left != NULL)
- node = node->left;
- result.p = node;
+ {
+ /* Start node is the leftmost node. */
+ gl_omap_node_t node = map->root;
+ if (node != NULL)
+ while (node->left != NULL)
+ node = node->left;
+ result.p = node;
+ }
/* End point is past the rightmost node. */
result.q = NULL;
#if defined GCC_LINT || defined lint
static int
gl_tree_nx_add (gl_oset_t set, const void *elt)
{
- gl_setelement_compar_fn compar;
gl_oset_node_t node = set->root;
if (node == NULL)
return true;
}
- compar = set->base.compar_fn;
+ gl_setelement_compar_fn compar = set->base.compar_fn;
for (;;)
{
&& (next_node == NULL || next_node->value > elt)))
{
/* old_node needs to move in the tree. */
- gl_oset_node_t node;
/* Remove the node from the tree. Don't free it. */
gl_tree_remove_node_no_free (set, old_node);
- node = set->root;
+ gl_oset_node_t node = set->root;
for (;;)
{
gl_tree_iterator (gl_oset_t set)
{
gl_oset_iterator_t result;
- gl_oset_node_t node;
result.vtable = set->base.vtable;
result.set = set;
- /* Start node is the leftmost node. */
- node = set->root;
- if (node != NULL)
- while (node->left != NULL)
- node = node->left;
- result.p = node;
+ {
+ /* Start node is the leftmost node. */
+ gl_oset_node_t node = set->root;
+ if (node != NULL)
+ while (node->left != NULL)
+ node = node->left;
+ result.p = node;
+ }
/* End point is past the rightmost node. */
result.q = NULL;
#if defined GCC_LINT || defined lint
{
/* Found already a node with the same value. Turn it
into an ordered set, and add new_node to it. */
- gl_oset_t nodes;
- struct gl_multiple_nodes *multi_entry;
-
- nodes =
+ gl_oset_t nodes =
gl_oset_nx_create_empty (OSET_TREE_FLAVOR,
compare_by_position, NULL);
if (nodes == NULL)
if (gl_oset_nx_add (nodes, new_node) < 0)
goto fail;
- multi_entry =
+ struct gl_multiple_nodes *multi_entry =
(struct gl_multiple_nodes *) malloc (sizeof (struct gl_multiple_nodes));
if (multi_entry == NULL)
goto fail;
static int
grow (gl_list_t list)
{
- size_t new_allocated;
- size_t memory_size;
- const void **memory;
-
- new_allocated = xtimes (list->allocated, 2);
+ size_t new_allocated = xtimes (list->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (const void *));
+ size_t memory_size = xtimes (new_allocated, sizeof (const void *));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
- memory = (const void **) realloc (list->elements, memory_size);
+ const void **memory = (const void **) realloc (list->elements, memory_size);
if (memory == NULL)
/* Out of memory. */
return -1;
gl_array_nx_add_first (gl_list_t list, const void *elt)
{
size_t count = list->count;
- const void **elements;
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- elements = list->elements;
+ const void **elements = list->elements;
for (size_t i = count; i > 0; i--)
elements[i] = elements[i - 1];
elements[0] = elt;
{
size_t count = list->count;
uintptr_t index = NODE_TO_INDEX (node);
- size_t position;
- const void **elements;
if (!(index < count))
/* Invalid argument. */
abort ();
- position = index;
+ size_t position = index;
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- elements = list->elements;
+ const void **elements = list->elements;
for (size_t i = count; i > position; i--)
elements[i] = elements[i - 1];
elements[position] = elt;
{
size_t count = list->count;
uintptr_t index = NODE_TO_INDEX (node);
- size_t position;
- const void **elements;
if (!(index < count))
/* Invalid argument. */
abort ();
- position = index + 1;
+ size_t position = index + 1;
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- elements = list->elements;
+ const void **elements = list->elements;
for (size_t i = count; i > position; i--)
elements[i] = elements[i - 1];
elements[position] = elt;
gl_array_nx_add_at (gl_list_t list, size_t position, const void *elt)
{
size_t count = list->count;
- const void **elements;
if (!(position <= count))
/* Invalid argument. */
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- elements = list->elements;
+ const void **elements = list->elements;
for (size_t i = count; i > position; i--)
elements[i] = elements[i - 1];
elements[position] = elt;
{
size_t count = list->count;
uintptr_t index = NODE_TO_INDEX (node);
- size_t position;
- const void **elements;
if (!(index < count))
/* Invalid argument. */
abort ();
- position = index;
- elements = list->elements;
+ size_t position = index;
+ const void **elements = list->elements;
if (list->base.dispose_fn != NULL)
list->base.dispose_fn (elements[position]);
for (size_t i = position + 1; i < count; i++)
gl_array_remove_at (gl_list_t list, size_t position)
{
size_t count = list->count;
- const void **elements;
if (!(position < count))
/* Invalid argument. */
abort ();
- elements = list->elements;
+ const void **elements = list->elements;
if (list->base.dispose_fn != NULL)
list->base.dispose_fn (elements[position]);
for (size_t i = position + 1; i < count; i++)
static int
grow (gl_map_t map)
{
- size_t new_allocated;
- size_t memory_size;
- struct pair *memory;
-
- new_allocated = xtimes (map->allocated, 2);
+ size_t new_allocated = xtimes (map->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (struct pair));
+ size_t memory_size = xtimes (new_allocated, sizeof (struct pair));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
- memory = (struct pair *) realloc (map->pairs, memory_size);
+ struct pair *memory = (struct pair *) realloc (map->pairs, memory_size);
if (memory == NULL)
/* Out of memory. */
return -1;
else
{
size_t count = map->count;
- struct pair *pairs;
-
if (count == map->allocated)
if (grow (map) < 0)
return -1;
- pairs = map->pairs;
+ struct pair *pairs = map->pairs;
pairs[count].key = key;
pairs[count].value = value;
map->count = count + 1;
gl_array_remove_at (gl_map_t map, size_t position)
{
size_t count = map->count;
- struct pair *pairs;
-
- pairs = map->pairs;
+ struct pair *pairs = map->pairs;
if (map->base.kdispose_fn != NULL)
map->base.kdispose_fn (pairs[position].key);
for (size_t i = position + 1; i < count; i++)
static int
grow (gl_omap_t map)
{
- size_t new_allocated;
- size_t memory_size;
- struct pair *memory;
-
- new_allocated = xtimes (map->allocated, 2);
+ size_t new_allocated = xtimes (map->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (struct pair));
+ size_t memory_size = xtimes (new_allocated, sizeof (struct pair));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
- memory = (struct pair *) realloc (map->pairs, memory_size);
+ struct pair *memory = (struct pair *) realloc (map->pairs, memory_size);
if (memory == NULL)
/* Out of memory. */
return -1;
const void *key, const void *value)
{
size_t count = map->count;
- struct pair *pairs;
-
if (count == map->allocated)
if (grow (map) < 0)
return -1;
- pairs = map->pairs;
+ struct pair *pairs = map->pairs;
for (size_t i = count; i > position; i--)
pairs[i] = pairs[i - 1];
pairs[position].key = key;
gl_array_remove_at (gl_omap_t map, size_t position)
{
size_t count = map->count;
- struct pair *pairs;
-
- pairs = map->pairs;
+ struct pair *pairs = map->pairs;
if (map->base.kdispose_fn != NULL)
map->base.kdispose_fn (pairs[position].key);
for (size_t i = position + 1; i < count; i++)
static int
grow (gl_oset_t set)
{
- size_t new_allocated;
- size_t memory_size;
- const void **memory;
-
- new_allocated = xtimes (set->allocated, 2);
+ size_t new_allocated = xtimes (set->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (const void *));
+ size_t memory_size = xtimes (new_allocated, sizeof (const void *));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
- memory = (const void **) realloc (set->elements, memory_size);
+ const void **memory = (const void **) realloc (set->elements, memory_size);
if (memory == NULL)
/* Out of memory. */
return -1;
gl_array_nx_add_at (gl_oset_t set, size_t position, const void *elt)
{
size_t count = set->count;
- const void **elements;
-
if (count == set->allocated)
if (grow (set) < 0)
return -1;
- elements = set->elements;
+ const void **elements = set->elements;
for (size_t i = count; i > position; i--)
elements[i] = elements[i - 1];
elements[position] = elt;
gl_array_remove_at (gl_oset_t set, size_t position)
{
size_t count = set->count;
- const void **elements;
-
- elements = set->elements;
+ const void **elements = set->elements;
if (set->base.dispose_fn != NULL)
set->base.dispose_fn (elements[position]);
for (size_t i = position + 1; i < count; i++)
static int
grow (gl_set_t set)
{
- size_t new_allocated;
- size_t memory_size;
- const void **memory;
-
- new_allocated = xtimes (set->allocated, 2);
+ size_t new_allocated = xtimes (set->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (const void *));
+ size_t memory_size = xtimes (new_allocated, sizeof (const void *));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
- memory = (const void **) realloc (set->elements, memory_size);
+ const void **memory = (const void **) realloc (set->elements, memory_size);
if (memory == NULL)
/* Out of memory. */
return -1;
{
for (;;)
{
- NODE_T child;
- int previous_balance;
- int balance_diff;
- NODE_T nodeleft;
- NODE_T noderight;
-
- child = node;
+ NODE_T child = node;
node = parent;
- previous_balance = node->balance;
+ int previous_balance = node->balance;
/* The balance of NODE is incremented by BALANCE_DIFF: +1 if the right
branch's height has increased by 1 or the left branch's height has
decreased by 1, -1 if the right branch's height has decreased by 1 or
the left branch's height has increased by 1, 0 if no height change. */
+ int balance_diff;
if (node->left != NULL || node->right != NULL)
balance_diff = (child == node->right ? height_diff : -height_diff);
else
else
abort ();
- nodeleft = node->left;
- noderight = node->right;
+ NODE_T nodeleft = node->left;
+ NODE_T noderight = node->right;
if (balance_diff < 0)
{
else
{
NODE_T node;
-
for (node = container->root; node->left != NULL; )
node = node->left;
static void
gl_tree_add_node_before (CONTAINER_T container, NODE_T node, NODE_T new_node)
{
- bool height_inc;
-
new_node->left = NULL;
new_node->right = NULL;
new_node->balance = 0;
/* Add it to the tree. */
+ bool height_inc;
if (node->left == NULL)
{
node->left = new_node;
static void
gl_tree_add_node_after (CONTAINER_T container, NODE_T node, NODE_T new_node)
{
- bool height_inc;
-
new_node->left = NULL;
new_node->right = NULL;
new_node->balance = 0;
/* Add it to the tree. */
+ bool height_inc;
if (node->right == NULL)
{
node->right = new_node;
{
/* Replace node with the rightmost element of the node->left subtree. */
NODE_T subst;
- NODE_T subst_parent;
- NODE_T child;
-
for (subst = node->left; subst->right != NULL; )
subst = subst->right;
- subst_parent = subst->parent;
+ NODE_T subst_parent = subst->parent;
- child = subst->left;
+ NODE_T child = subst->left;
/* The case subst_parent == node is special: If we do nothing special,
we get confusion about node->left, subst->left and child->parent.
gl_carray_node_value (gl_list_t list, gl_list_node_t node)
{
uintptr_t index = NODE_TO_INDEX (node);
- size_t i;
if (!(index < list->count))
/* Invalid argument. */
abort ();
- i = list->offset + index;
+ size_t i = list->offset + index;
if (i >= list->allocated)
i -= list->allocated;
return list->elements[i];
const void *elt)
{
uintptr_t index = NODE_TO_INDEX (node);
- size_t i;
if (!(index < list->count))
/* Invalid argument. */
abort ();
- i = list->offset + index;
+ size_t i = list->offset + index;
if (i >= list->allocated)
i -= list->allocated;
list->elements[i] = elt;
gl_carray_get_at (gl_list_t list, size_t position)
{
size_t count = list->count;
- size_t i;
if (!(position < count))
/* Invalid argument. */
abort ();
- i = list->offset + position;
+ size_t i = list->offset + position;
if (i >= list->allocated)
i -= list->allocated;
return list->elements[i];
gl_carray_nx_set_at (gl_list_t list, size_t position, const void *elt)
{
size_t count = list->count;
- size_t i;
if (!(position < count))
/* Invalid argument. */
abort ();
- i = list->offset + position;
+ size_t i = list->offset + position;
if (i >= list->allocated)
i -= list->allocated;
list->elements[i] = elt;
{
gl_listelement_equals_fn equals = list->base.equals_fn;
size_t allocated = list->allocated;
- size_t i_end;
- i_end = list->offset + end_index;
+ size_t i_end = list->offset + end_index;
if (i_end >= allocated)
i_end -= allocated;
static int
grow (gl_list_t list)
{
- size_t new_allocated;
- size_t memory_size;
- const void **memory;
-
- new_allocated = xtimes (list->allocated, 2);
+ size_t new_allocated = xtimes (list->allocated, 2);
new_allocated = xsum (new_allocated, 1);
- memory_size = xtimes (new_allocated, sizeof (const void *));
+ size_t memory_size = xtimes (new_allocated, sizeof (const void *));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
return -1;
+ const void **memory;
if (list->offset > 0 && list->count > 0)
{
memory = (const void **) malloc (memory_size);
gl_carray_nx_add_last (gl_list_t list, const void *elt)
{
size_t count = list->count;
- size_t i;
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- i = list->offset + count;
+ size_t i = list->offset + count;
if (i >= list->allocated)
i -= list->allocated;
list->elements[i] = elt;
gl_carray_nx_add_at (gl_list_t list, size_t position, const void *elt)
{
size_t count = list->count;
- const void **elements;
if (!(position <= count))
/* Invalid argument. */
if (count == list->allocated)
if (grow (list) < 0)
return NULL;
- elements = list->elements;
+ const void **elements = list->elements;
if (position <= (count / 2))
{
/* Shift at most count/2 elements to the left. */
- size_t i2;
-
list->offset = (list->offset == 0 ? list->allocated : list->offset) - 1;
- i2 = list->offset + position;
+ size_t i2 = list->offset + position;
if (i2 >= list->allocated)
{
/* Here we must have list->offset > 0, hence list->allocated > 0. */
else
{
/* Shift at most (count+1)/2 elements to the right. */
- size_t i1, i3;
-
- i1 = list->offset + position;
- i3 = list->offset + count;
+ size_t i1 = list->offset + position;
+ size_t i3 = list->offset + count;
if (i1 >= list->allocated)
{
i1 -= list->allocated;
gl_carray_remove_at (gl_list_t list, size_t position)
{
size_t count = list->count;
- const void **elements;
if (!(position < count))
/* Invalid argument. */
abort ();
/* Here we know count > 0. */
- elements = list->elements;
+ const void **elements = list->elements;
if (position <= ((count - 1) / 2))
{
/* Shift at most (count-1)/2 elements to the right. */
- size_t i0, i2;
-
- i0 = list->offset;
- i2 = list->offset + position;
+ size_t i0 = list->offset;
+ size_t i2 = list->offset + position;
if (i2 >= list->allocated)
{
/* Here we must have list->offset > 0, hence list->allocated > 0. */
else
{
/* Shift at most count/2 elements to the left. */
- size_t i1, i3;
-
- i1 = list->offset + position;
- i3 = list->offset + count - 1;
+ size_t i1 = list->offset + position;
+ size_t i3 = list->offset + count - 1;
if (i1 >= list->allocated)
{
i1 -= list->allocated;
static gl_list_iterator_t _GL_ATTRIBUTE_PURE
gl_carray_iterator_from_to (gl_list_t list, size_t start_index, size_t end_index)
{
- gl_list_iterator_t result;
-
if (!(start_index <= end_index && end_index <= list->count))
/* Invalid arguments. */
abort ();
+
+ gl_list_iterator_t result;
result.vtable = list->base.vtable;
result.list = list;
result.count = list->count;
do
{
size_t mid = low + (high - low) / 2; /* low <= mid < high */
- size_t i_mid;
- int cmp;
- i_mid = list->offset + mid;
+ size_t i_mid = list->offset + mid;
if (i_mid >= list->allocated)
i_mid -= list->allocated;
- cmp = compar (list->elements[i_mid], elt);
+ int cmp = compar (list->elements[i_mid], elt);
if (cmp < 0)
low = mid + 1;
while (low < high)
{
size_t mid2 = low + (high - low) / 2; /* low <= mid2 < high */
- size_t i_mid2;
- int cmp2;
- i_mid2 = list->offset + mid2;
+ size_t i_mid2 = list->offset + mid2;
if (i_mid2 >= list->allocated)
i_mid2 -= list->allocated;
- cmp2 = compar (list->elements[i_mid2], elt);
+ int cmp2 = compar (list->elements[i_mid2], elt);
if (cmp2 < 0)
low = mid2 + 1;
while (low < high)
{
size_t mid = low + (high - low) / 2; /* low <= mid < high */
- size_t i_mid;
- int cmp;
- i_mid = list->offset + mid;
+ size_t i_mid = list->offset + mid;
if (i_mid >= list->allocated)
i_mid -= list->allocated;
- cmp = compar (list->elements[i_mid], elt);
+ int cmp = compar (list->elements[i_mid], elt);
if (cmp < 0)
low = mid + 1;
/* At this point, parent = node->parent != NULL.
Think of node->color being RED (although node->color is not yet
assigned.) */
- NODE_T grandparent;
- NODE_T uncle;
if (parent->color == BLACK)
{
return;
}
- grandparent = parent->parent;
+ NODE_T grandparent = parent->parent;
/* Since parent is RED, we know that
grandparent is != NULL and colored BLACK. */
+ NODE_T uncle;
if (grandparent->left == parent)
uncle = grandparent->right;
else if (grandparent->right == parent)
else
{
/* Replace node with the rightmost element of the node->left subtree. */
- NODE_T subst;
- NODE_T subst_parent;
- NODE_T child;
- color_t removed_color;
+ NODE_T subst;
for (subst = node->left; subst->right != NULL; )
subst = subst->right;
- subst_parent = subst->parent;
+ NODE_T subst_parent = subst->parent;
- child = subst->left;
+ NODE_T child = subst->left;
- removed_color = subst->color;
+ color_t removed_color = subst->color;
/* The case subst_parent == node is special: If we do nothing special,
we get confusion about node->left, subst->left and child->parent.
size_t low, size_t high,
const void *elt)
{
- size_t index;
-
if (!(low <= high && high <= list->end - list->start))
/* Invalid arguments. */
abort ();
- index =
+ size_t index =
gl_sortedlist_indexof_from_to (list->whole, compar,
list->start + low, list->start + high, elt);
if (index != (size_t)(-1))
size_t low, size_t high,
const void *elt)
{
- size_t index;
-
if (!(low <= high && high <= list->end - list->start))
/* Invalid arguments. */
abort ();
- index = gl_sortedlist_indexof_from_to (list->whole, compar,
- list->start + low, list->start + high,
- elt);
+ size_t index =
+ gl_sortedlist_indexof_from_to (list->whole, compar,
+ list->start + low, list->start + high, elt);
if (index != (size_t)(-1))
index -= list->start;
return index;
__glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
glob_t *pglob)
{
- const char *filename;
- char *dirname = NULL;
- size_t dirlen;
- int status;
- size_t oldcount;
- int meta;
- int dirname_modified;
- int malloc_dirname = 0;
- glob_t dirs;
- int retval = 0;
- size_t alloca_used = 0;
-
if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
{
__set_errno (EINVAL);
pglob->gl_pathv = NULL;
else
{
- size_t i;
-
if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))
return GLOB_NOSPACE;
if (pglob->gl_pathv == NULL)
return GLOB_NOSPACE;
- for (i = 0; i <= pglob->gl_offs; ++i)
+ for (size_t i = 0; i <= pglob->gl_offs; ++i)
pglob->gl_pathv[i] = NULL;
}
}
+ size_t alloca_used = 0;
+
if (flags & GLOB_BRACE)
{
const char *begin;
{
/* Allocate working buffer large enough for our work. Note that
we have at least an opening and closing brace. */
- size_t firstc;
- char *alt_start;
- const char *p;
- const char *next;
- const char *rest;
- size_t rest_len;
- char *onealt;
size_t pattern_len = strlen (pattern) - 1;
int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);
+ char *onealt;
if (alloca_onealt)
onealt = alloca_account (pattern_len, alloca_used);
else
}
/* We know the prefix for all sub-patterns. */
- alt_start = mempcpy (onealt, pattern, begin - pattern);
+ char *alt_start = mempcpy (onealt, pattern, begin - pattern);
/* Find the first sub-pattern and at the same time find the
rest after the closing brace. */
- next = next_brace_sub (begin + 1, flags);
+ const char *next = next_brace_sub (begin + 1, flags);
if (next == NULL)
{
/* It is an invalid expression. */
}
/* Now find the end of the whole brace expression. */
- rest = next;
+ const char *rest = next;
while (*rest != '}')
{
rest = next_brace_sub (rest + 1, flags);
}
/* Please note that we now can be sure the brace expression
is well-formed. */
- rest_len = strlen (++rest) + 1;
+ size_t rest_len = strlen (++rest) + 1;
/* We have a brace expression. BEGIN points to the opening {,
NEXT points past the terminator of the first element, and END
points past the final }. We will accumulate result names from
recursive runs for each brace alternative in the buffer using
GLOB_APPEND. */
- firstc = pglob->gl_pathc;
+ size_t firstc = pglob->gl_pathc;
- p = begin + 1;
+ const char *p = begin + 1;
while (1)
{
- int result;
-
/* Construct the new glob expression. */
mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
- result = __glob (onealt,
- ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
- | GLOB_APPEND),
- errfunc, pglob);
+ int result = __glob (onealt,
+ ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
+ | GLOB_APPEND),
+ errfunc, pglob);
/* If we got an error, return it. */
if (result && result != GLOB_NOMATCH)
}
}
- no_brace:
- oldcount = pglob->gl_pathc + pglob->gl_offs;
+ no_brace: ;
+ size_t oldcount = pglob->gl_pathc + pglob->gl_offs;
/* Find the filename. */
- filename = strrchr (pattern, '/');
+ const char *filename = strrchr (pattern, '/');
#if defined __MSDOS__ || defined WINDOWS32
/* The case of "d:pattern". Since ':' is not allowed in
filename = strchr (pattern, ':');
#endif /* __MSDOS__ || WINDOWS32 */
- dirname_modified = 0;
+ char *dirname = NULL;
+ size_t dirlen;
+ int malloc_dirname = 0;
+ int dirname_modified = 0;
+ glob_t dirs;
+ int retval = 0;
if (filename == NULL)
{
/* This can mean two things: a simple name or "~name". The latter
}
else
{
- char *newp;
dirlen = filename - pattern;
#if defined __MSDOS__ || defined WINDOWS32
if (*filename == ':'
}
#endif
+ char *newp;
if (glob_use_alloca (alloca_used, dirlen + 1))
newp = alloca_account (dirlen + 1, alloca_used);
else
}
else
{
- char *newp;
size_t home_len = strlen (home_dir);
int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);
+ char *newp;
if (use_alloca)
newp = alloca_account (home_len + dirlen, alloca_used);
else
/* dirname contains end_name; we can't free it now. */
char *prev_dirname =
(__glibc_unlikely (malloc_dirname) ? dirname : NULL);
- char *d;
malloc_dirname = 0;
}
malloc_dirname = 1;
}
- d = mempcpy (dirname, p->pw_dir, home_len);
+ char *d = mempcpy (dirname, p->pw_dir, home_len);
if (end_name != NULL)
d = mempcpy (d, end_name, rest_len);
*d = '\0';
if (filename == NULL)
{
size_t newcount = pglob->gl_pathc + pglob->gl_offs;
- char **new_gl_pathv;
if (newcount > SIZE_MAX / sizeof (char *) - 2)
{
goto out;
}
- new_gl_pathv = realloc (pglob->gl_pathv,
- (newcount + 2) * sizeof (char *));
+ char **new_gl_pathv = realloc (pglob->gl_pathv,
+ (newcount + 2) * sizeof (char *));
if (new_gl_pathv == NULL)
goto nospace;
pglob->gl_pathv = new_gl_pathv;
if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))
{
- char *p;
pglob->gl_pathv[newcount] = malloc (dirlen + 2);
if (pglob->gl_pathv[newcount] == NULL)
goto nospace;
- p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
+ char *p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
p[0] = '/';
p[1] = '\0';
if (__glibc_unlikely (malloc_dirname))
return 0;
}
- meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
+ int meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
/* meta is 1 if correct glob pattern containing metacharacters.
If meta has bit (1 << 2) set, it means there was an unterminated
[ which we handle the same, using fnmatch. Broken unterminated
/* The directory name contains metacharacters, so we
have to glob for the directory, and then glob for
the pattern in each directory found. */
- size_t i;
-
if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
{
/* "foo\\/bar". Remove the final backslash from dirname
dirs.gl_lstat = pglob->gl_lstat;
}
- status = __glob (dirname,
- ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC))
- | GLOB_NOSORT | GLOB_ONLYDIR),
- errfunc, &dirs);
+ int status =
+ __glob (dirname,
+ ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC))
+ | GLOB_NOSORT | GLOB_ONLYDIR),
+ errfunc, &dirs);
if (status != 0)
{
if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
/* We have successfully globbed the preceding directory name.
For each name we found, call glob_in_dir on it and FILENAME,
appending the results to PGLOB. */
- for (i = 0; i < dirs.gl_pathc; ++i)
+ for (size_t i = 0; i < dirs.gl_pathc; ++i)
{
- size_t old_pathc;
-
- old_pathc = pglob->gl_pathc;
+ size_t old_pathc = pglob->gl_pathc;
status = glob_in_dir (filename, dirs.gl_pathv[i],
((flags | GLOB_APPEND)
& ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
if (flags & GLOB_NOCHECK)
{
size_t newcount = pglob->gl_pathc + pglob->gl_offs;
- char **new_gl_pathv;
-
if (newcount > SIZE_MAX / sizeof (char *) - 2)
{
nospace2:
goto out;
}
- new_gl_pathv = realloc (pglob->gl_pathv,
- (newcount + 2) * sizeof (char *));
+ char **new_gl_pathv = realloc (pglob->gl_pathv,
+ (newcount + 2) * sizeof (char *));
if (new_gl_pathv == NULL)
goto nospace2;
pglob->gl_pathv = new_gl_pathv;
}
if (dirname_modified)
flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
- status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
- alloca_used);
+ int status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
+ alloca_used);
if (status != 0)
{
if (status == GLOB_NOMATCH && flags != orig_flags
if (flags & GLOB_MARK)
{
/* Append slashes to directory names. */
- size_t i;
-
- for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
+ for (size_t i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
if (is_dir (pglob->gl_pathv[i], flags, pglob))
{
size_t len = strlen (pglob->gl_pathv[i]) + 2;
{
if (pglob->gl_pathv != NULL)
{
- size_t i;
- for (i = 0; i < pglob->gl_pathc; ++i)
+ for (size_t i = 0; i < pglob->gl_pathc; ++i)
free (pglob->gl_pathv[pglob->gl_offs + i]);
free (pglob->gl_pathv);
pglob->gl_pathv = NULL;
glthread_rwlock_init_for_glibc (pthread_rwlock_t *lock)
{
pthread_rwlockattr_t attributes;
- int err;
-
- err = pthread_rwlockattr_init (&attributes);
+ int err = pthread_rwlockattr_init (&attributes);
if (err != 0)
return err;
/* Note: PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP is the only value that
int
glthread_rwlock_init_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_rwlock_init (&lock->rwlock, NULL);
+ int err = pthread_rwlock_init (&lock->rwlock, NULL);
if (err != 0)
return err;
lock->initialized = 1;
{
if (!lock->initialized)
{
- int err;
-
- err = pthread_mutex_lock (&lock->guard);
+ int err = pthread_mutex_lock (&lock->guard);
if (err != 0)
return err;
if (!lock->initialized)
{
if (!lock->initialized)
{
- int err;
-
- err = pthread_mutex_lock (&lock->guard);
+ int err = pthread_mutex_lock (&lock->guard);
if (err != 0)
return err;
if (!lock->initialized)
int
glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
if (!lock->initialized)
return EINVAL;
- err = pthread_rwlock_destroy (&lock->rwlock);
+ int err = pthread_rwlock_destroy (&lock->rwlock);
if (err != 0)
return err;
lock->initialized = 0;
int
glthread_rwlock_init_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_init (&lock->lock, NULL);
+ int err = pthread_mutex_init (&lock->lock, NULL);
if (err != 0)
return err;
err = pthread_cond_init (&lock->waiting_readers, NULL);
int
glthread_rwlock_rdlock_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
+ int err = pthread_mutex_lock (&lock->lock);
if (err != 0)
return err;
/* Test whether only readers are currently running, and whether the runcount
int
glthread_rwlock_wrlock_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
+ int err = pthread_mutex_lock (&lock->lock);
if (err != 0)
return err;
/* Test whether no readers or writers are currently running. */
int
glthread_rwlock_unlock_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
+ int err = pthread_mutex_lock (&lock->lock);
if (err != 0)
return err;
if (lock->runcount < 0)
int
glthread_rwlock_destroy_multithreaded (gl_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_destroy (&lock->lock);
+ int err = pthread_mutex_destroy (&lock->lock);
if (err != 0)
return err;
err = pthread_cond_destroy (&lock->waiting_readers);
glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
{
pthread_mutexattr_t attributes;
- int err;
-
- err = pthread_mutexattr_init (&attributes);
+ int err = pthread_mutexattr_init (&attributes);
if (err != 0)
return err;
err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
{
pthread_mutexattr_t attributes;
- int err;
-
- err = pthread_mutexattr_init (&attributes);
+ int err = pthread_mutexattr_init (&attributes);
if (err != 0)
return err;
err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
{
if (!lock->initialized)
{
- int err;
-
- err = pthread_mutex_lock (&lock->guard);
+ int err = pthread_mutex_lock (&lock->guard);
if (err != 0)
return err;
if (!lock->initialized)
int
glthread_recursive_lock_destroy_multithreaded (gl_recursive_lock_t *lock)
{
- int err;
-
if (!lock->initialized)
return EINVAL;
- err = pthread_mutex_destroy (&lock->recmutex);
+ int err = pthread_mutex_destroy (&lock->recmutex);
if (err != 0)
return err;
lock->initialized = 0;
int
glthread_recursive_lock_init_multithreaded (gl_recursive_lock_t *lock)
{
- int err;
-
- err = pthread_mutex_init (&lock->mutex, NULL);
+ int err = pthread_mutex_init (&lock->mutex, NULL);
if (err != 0)
return err;
lock->owner = (pthread_t) 0;
pthread_t self = pthread_self ();
if (lock->owner != self)
{
- int err;
-
- err = pthread_mutex_lock (&lock->mutex);
+ int err = pthread_mutex_lock (&lock->mutex);
if (err != 0)
return err;
lock->owner = self;
gl_thread_create (void *(*func) (void *arg), void *arg)
{
gl_thread_t thread;
- int ret;
-
- ret = glthread_create (&thread, func, arg);
+ int ret = glthread_create (&thread, func, arg);
if (ret != 0)
abort ();
return thread;
int
group_member (gid_t gid)
{
- int found;
struct group_info gi;
int n_groups = get_group_info (&gi);
/* Search through the list looking for GID. */
- found = 0;
+ int found = 0;
for (int i = 0; i < n_groups; i++)
{
if (gid == gi.group[i])
{
for (int i = 1; i < argc; i++)
{
- gid_t gid;
-
- gid = atoi (argv[i]);
+ gid_t gid = atoi (argv[i]);
printf ("%d: %s\n", gid, group_member (gid) ? "yes" : "no");
}
exit (0);
hash_get_next (const Hash_table *table, const void *entry)
{
struct hash_entry const *bucket = safe_hasher (table, entry);
- struct hash_entry const *cursor;
/* Find next entry in the same bucket. */
- cursor = bucket;
- do
- {
- if (cursor->data == entry && cursor->next)
- return cursor->next->data;
- cursor = cursor->next;
- }
- while (cursor != NULL);
+ {
+ struct hash_entry const *cursor = bucket;
+ do
+ {
+ if (cursor->data == entry && cursor->next)
+ return cursor->next->data;
+ cursor = cursor->next;
+ }
+ while (cursor != NULL);
+ }
/* Find first entry in any subsequent bucket. */
while (++bucket < table->bucket_limit)
check_tuning (Hash_table *table)
{
const Hash_tuning *tuning = table->tuning;
- float epsilon;
if (tuning == &default_tuning)
return true;
fail to grow or shrink as they should. The smallest allocation
is 11 (due to next_prime's algorithm), so an epsilon of 0.1
should be good enough. */
- epsilon = 0.1f;
+ float epsilon = 0.1f;
if (epsilon < tuning->growth_threshold
&& tuning->growth_threshold < 1 - epsilon
Hash_hasher hasher, Hash_comparator comparator,
Hash_data_freer data_freer)
{
- Hash_table *table;
-
if (hasher == NULL)
hasher = raw_hasher;
if (comparator == NULL)
comparator = raw_comparator;
- table = malloc (sizeof *table);
+ Hash_table *table = malloc (sizeof *table);
if (table == NULL)
return NULL;
{
if (bucket->data)
{
- struct hash_entry *next;
-
/* Free the bucket overflow. */
- for (struct hash_entry *cursor = bucket->next; cursor; cursor = next)
+ for (struct hash_entry *cursor = bucket->next; cursor; )
{
if (table->data_freer)
table->data_freer (cursor->data);
cursor->data = NULL;
- next = cursor->next;
+ struct hash_entry *next = cursor->next;
/* Relinking is done one entry at a time, as it is to be expected
that overflows are either rare or short. */
cursor->next = table->free_entry_list;
table->free_entry_list = cursor;
+
+ cursor = next;
}
/* Free the bucket head. */
void
hash_free (Hash_table *table)
{
- struct hash_entry *next;
int saved_errno = errno;
/* Call the user data_freer function. */
bucket < table->bucket_limit;
bucket++)
{
- for (struct hash_entry *cursor = bucket->next; cursor; cursor = next)
+ for (struct hash_entry *cursor = bucket->next; cursor; )
{
- next = cursor->next;
+ struct hash_entry *next = cursor->next;
free (cursor);
+ cursor = next;
}
}
/* Also reclaim the internal list of previously freed entries. */
- for (struct hash_entry *cursor = table->free_entry_list; cursor; cursor = next)
+ for (struct hash_entry *cursor = table->free_entry_list; cursor; )
{
- next = cursor->next;
+ struct hash_entry *next = cursor->next;
free (cursor);
+ cursor = next;
}
#endif
static bool
transfer_entries (Hash_table *dst, Hash_table *src, bool safe)
{
- struct hash_entry *next;
-
for (struct hash_entry *bucket = src->bucket; bucket < src->bucket_limit; bucket++)
if (bucket->data)
{
bucket head, but moving overflow entries first may create
free entries that can be recycled by the time we finally
get to the bucket head. */
- for (struct hash_entry *cursor = bucket->next; cursor; cursor = next)
+ for (struct hash_entry *cursor = bucket->next; cursor; )
{
data = cursor->data;
new_bucket = safe_hasher (dst, data);
- next = cursor->next;
+ struct hash_entry *next = cursor->next;
if (new_bucket->data)
{
dst->n_buckets_used++;
free_entry (dst, cursor);
}
+
+ cursor = next;
}
/* Now move the bucket head. Be sure that if we fail due to
allocation failure that the src table is in a consistent
bool
hash_rehash (Hash_table *table, size_t candidate)
{
- Hash_table storage;
- Hash_table *new_table;
size_t new_size = compute_bucket_size (candidate, table->tuning);
if (!new_size)
return false;
if (new_size == table->n_buckets)
return true;
- new_table = &storage;
+
+ Hash_table storage;
+ Hash_table *new_table = &storage;
new_table->bucket = calloc (new_size, sizeof *new_table->bucket);
if (new_table->bucket == NULL)
return false;
hash_insert_if_absent (Hash_table *table, void const *entry,
void const **matched_ent)
{
- void *data;
- struct hash_entry *bucket;
/* The caller cannot insert a NULL entry, since hash_lookup returns NULL
to indicate "not found", and find_entry uses "bucket->data == NULL"
abort ();
/* If there's a matching entry already in the table, return that. */
- if ((data = find_entry (table, entry, &bucket, false)) != NULL)
+ struct hash_entry *bucket;
+ void *data = find_entry (table, entry, &bucket, false);
+ if (data != NULL)
{
if (matched_ent)
*matched_ent = data;
void *
hash_remove (Hash_table *table, const void *entry)
{
- void *data;
struct hash_entry *bucket;
-
- data = find_entry (table, entry, &bucket, true);
+ void *data = find_entry (table, entry, &bucket, true);
if (!data)
return NULL;
void
hash_print (const Hash_table *table)
{
- struct hash_entry *bucket = (struct hash_entry *) table->bucket;
-
- for ( ; bucket < table->bucket_limit; bucket++)
+ for (struct hash_entry *bucket = (struct hash_entry *) table->bucket;
+ bucket < table->bucket_limit;
+ bucket++)
{
if (bucket)
printf ("%lu:\n", (unsigned long int) (bucket - table->bucket));
hasmntopt (const struct mntent *mnt, const char *opt)
{
const size_t optlen = strlen (opt);
- char *rest = mnt->mnt_opts, *p;
+ char *p;
- while ((p = strstr (rest, opt)) != NULL)
+ for (char *rest = mnt->mnt_opts; (p = strstr (rest, opt)) != NULL; )
{
if ((p == rest || p[-1] == ',')
&& (p[optlen] == '\0' || p[optlen] == '=' || p[optlen] == ','))
const void *in, size_t inlen,
int pad, void *resbuf)
{
- struct GL_HMAC_CTX hmac_ctx;
char block[GL_HMAC_BLOCKSIZE];
memset (block, pad, sizeof block);
memxor (block, key, keylen);
+ struct GL_HMAC_CTX hmac_ctx;
GL_HMAC_FN_INIT (&hmac_ctx);
GL_HMAC_FN_BLOC (block, sizeof block, &hmac_ctx);
GL_HMAC_FN_PROC (in, inlen, &hmac_ctx);
const void *in, size_t inlen, void *resbuf)
{
char optkeybuf[GL_HMAC_HASHSIZE];
- char innerhash[GL_HMAC_HASHSIZE];
/* Ensure key size is <= block size. */
if (keylen > GL_HMAC_BLOCKSIZE)
}
/* Compute INNERHASH from KEY and IN. */
+ char innerhash[GL_HMAC_HASHSIZE];
hmac_hash (key, keylen, in, inlen, IPAD, innerhash);
/* Compute result from KEY and INNERHASH. */
group_number (char *number, size_t numberlen,
char const *grouping, char const *thousands_sep)
{
- register char *d;
- size_t grouplen = SIZE_MAX;
size_t thousands_seplen = strlen (thousands_sep);
- size_t i = numberlen;
/* The maximum possible value for NUMBERLEN is the number of digits
in the square of the largest uintmax_t, so double the size needed. */
char buf[2 * INT_STRLEN_BOUND (uintmax_t) + 1];
memcpy (buf, number, numberlen);
- d = number + numberlen;
+ register char *d = number + numberlen;
+ size_t grouplen = SIZE_MAX;
+ size_t i = numberlen;
for (;;)
{
unsigned char g = *grouping;
int inexact_style =
opts & (human_round_to_nearest | human_floor | human_ceiling);
unsigned int base = opts & human_base_1024 ? 1024 : 1000;
- uintmax_t amt;
- int tenths;
- int exponent = -1;
- int exponent_max = sizeof power_letter - 1;
- char *p;
- char *psuffix;
- char const *integerlim;
-
- /* 0 means adjusted N == AMT.TENTHS;
- 1 means AMT.TENTHS < adjusted N < AMT.TENTHS + 0.05;
- 2 means adjusted N == AMT.TENTHS + 0.05;
- 3 means AMT.TENTHS + 0.05 < adjusted N < AMT.TENTHS + 0.1. */
- int rounding;
char const *decimal_point = ".";
size_t decimal_pointlen = 1;
thousands_sep = l->thousands_sep;
/* Leave room for a trailing space and following suffix. */
- psuffix = buf + LONGEST_HUMAN_READABLE - 1 - HUMAN_READABLE_SUFFIX_LENGTH_MAX;
- p = psuffix;
+ char *psuffix =
+ buf + LONGEST_HUMAN_READABLE - 1 - HUMAN_READABLE_SUFFIX_LENGTH_MAX;
+ char *p = psuffix;
/* Adjust AMT out of FROM_BLOCK_SIZE units and into TO_BLOCK_SIZE
units. If this can be done exactly with integer arithmetic, do
not use floating point operations. */
+ uintmax_t amt;
+ int tenths;
+ /* 0 means adjusted N == AMT.TENTHS;
+ 1 means AMT.TENTHS < adjusted N < AMT.TENTHS + 0.05;
+ 2 means adjusted N == AMT.TENTHS + 0.05;
+ 3 means AMT.TENTHS + 0.05 < adjusted N < AMT.TENTHS + 0.1. */
+ int rounding;
if (to_block_size <= from_block_size)
{
if (from_block_size % to_block_size == 0)
goto use_integer_arithmetic;
}
+ int exponent = -1;
+ int exponent_max = sizeof power_letter - 1;
+ char const *integerlim;
+
{
/* Either the result cannot be computed easily using uintmax_t,
or from_block_size is zero. Fall back on floating point.
static strtol_error
humblock (char const *spec, uintmax_t *block_size, int *options)
{
- int i;
int opts = 0;
if (! spec
spec++;
}
- if (0 <= (i = ARGMATCH (spec, block_size_args, block_size_opts)))
+ int i = ARGMATCH (spec, block_size_args, block_size_opts);
+ if (0 <= i)
{
opts |= block_size_opts[i];
*block_size = 1;
/* Now 0 <= b <= a. */
{
- int e;
- double an;
- double bn;
-
/* Write a = an * 2^e, b = bn * 2^e with 0 <= bn <= an < 1. */
- an = frexp (a, &e);
- bn = ldexp (b, - e);
+ int e;
+ double an = frexp (a, &e);
+ double bn = ldexp (b, - e);
{
- double cn;
-
/* Through the normalization, no unneeded overflow or underflow
will occur here. */
- cn = sqrt (an * an + bn * bn);
+ double cn = sqrt (an * an + bn * bn);
return ldexp (cn, e);
}
}
/* Now 0 <= b <= a. */
{
- int e;
- long double an;
- long double bn;
-
/* Write a = an * 2^e, b = bn * 2^e with 0 <= bn <= an < 1. */
- an = frexpl (a, &e);
- bn = ldexpl (b, - e);
+ int e;
+ long double an = frexpl (a, &e);
+ long double bn = ldexpl (b, - e);
{
- long double cn;
-
/* Through the normalization, no unneeded overflow or underflow
will occur here. */
- cn = sqrtl (an * an + bn * bn);
+ long double cn = sqrtl (an * an + bn * bn);
return ldexpl (cn, e);
}
}
int
i_ring_pop (I_ring *ir)
{
- int top_val;
if (i_ring_empty (ir))
abort ();
- top_val = ir->ir_data[ir->ir_front];
+ int top_val = ir->ir_data[ir->ir_front];
ir->ir_data[ir->ir_front] = ir->ir_default_val;
if (ir->ir_front == ir->ir_back)
ir->ir_empty = true;
rpl_iconv_open (const char *tocode, const char *fromcode)
#undef iconv_open
{
- char fromcode_upper[32];
- char tocode_upper[32];
- char *fromcode_upper_end;
- char *tocode_upper_end;
-
#if REPLACE_ICONV_UTF
/* Special handling of conversion between UTF-8 and UTF-{16,32}{BE,LE}.
We do not need to handle conversion between arbitrary encodings and
/* Convert the encodings to upper case, because
1. in the arguments of iconv_open() on AIX and HP-UX, the case matters,
2. it makes searching in the table faster. */
+ char fromcode_upper[32];
+ char *fromcode_upper_end;
{
const char *p = fromcode;
char *q = fromcode_upper;
fromcode_upper_end = q;
}
+ char tocode_upper[32];
+ char *tocode_upper_end;
{
const char *p = tocode;
char *q = tocode_upper;
uid_t *
getuidbyname (const char *user)
{
- struct passwd *pwent;
-
for (struct userid *tail = user_alist; tail; tail = tail->next)
/* Avoid a function call for the most common case. */
if (*tail->name == *user && streq (tail->name, user))
if (*tail->name == *user && streq (tail->name, user))
return NULL;
- pwent = getpwnam (user);
+ struct passwd *pwent = getpwnam (user);
#ifdef __DJGPP__
/* We need to pretend to be the user USER, to make
pwd functions know about an arbitrary user name. */
gid_t *
getgidbyname (const char *group)
{
- struct group *grent;
-
for (struct userid *tail = group_alist; tail; tail = tail->next)
/* Avoid a function call for the most common case. */
if (*tail->name == *group && streq (tail->name, group))
if (*tail->name == *group && streq (tail->name, group))
return NULL;
- grent = getgrnam (group);
+ struct group *grent = getgrnam (group);
#ifdef __DJGPP__
/* We need to pretend to belong to group GROUP, to make
grp functions know about an arbitrary group name. */
inet_ntop4 (const unsigned char *src, char *dst, socklen_t size)
{
char tmp[sizeof "255.255.255.255"];
- int len;
-
- len = sprintf (tmp, "%u.%u.%u.%u", src[0], src[1], src[2], src[3]);
+ int len = sprintf (tmp, "%u.%u.%u.%u", src[0], src[1], src[2], src[3]);
if (len < 0)
return NULL;
static const char *
inet_ntop6 (const unsigned char *src, char *dst, socklen_t size)
{
- /*
- * Note that int32_t and int16_t need only be "at least" large enough
- * to contain a value of the specified size. On some systems, like
- * Crays, there is no such thing as an integer variable with 16 bits.
- * Keep this in mind if you think this function should have been coded
- * to use pointer overlays. All the world's not a VAX.
- */
- char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
- struct
- {
- int base, len;
- } best, cur;
- unsigned int words[NS_IN6ADDRSZ / NS_INT16SZ];
-
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
+ unsigned int words[NS_IN6ADDRSZ / NS_INT16SZ];
memset (words, '\0', sizeof words);
for (int i = 0; i < NS_IN6ADDRSZ; i += 2)
words[i / 2] = (src[i] << 8) | src[i + 1];
+
+ struct
+ {
+ int base, len;
+ } best, cur;
best.base = -1;
cur.base = -1;
IF_LINT(best.len = 0);
IF_LINT(cur.len = 0);
+
for (int i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++)
{
if (words[i] == 0)
/*
* Format the result.
*/
- tp = tmp;
+ /*
+ * Note that int32_t and int16_t need only be "at least" large enough
+ * to contain a value of the specified size. On some systems, like
+ * Crays, there is no such thing as an integer variable with 16 bits.
+ * Keep this in mind if you think this function should have been coded
+ * to use pointer overlays. All the world's not a VAX.
+ */
+ char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
+ char *tp = tmp;
for (int i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++)
{
/* Are we inside the best run of 0x00's? */
static int
inet_pton4 (const char *restrict src, unsigned char *restrict dst)
{
- int saw_digit, octets, ch;
- unsigned char tmp[NS_INADDRSZ], *tp;
+ unsigned char tmp[NS_INADDRSZ];
- saw_digit = 0;
- octets = 0;
- *(tp = tmp) = 0;
- while ((ch = *src++) != '\0')
- {
-
- if (ch >= '0' && ch <= '9')
- {
- unsigned new = *tp * 10 + (ch - '0');
-
- if (saw_digit && *tp == 0)
- return (0);
- if (new > 255)
- return (0);
- *tp = new;
- if (!saw_digit)
- {
- if (++octets > 4)
- return (0);
- saw_digit = 1;
- }
- }
- else if (ch == '.' && saw_digit)
- {
- if (octets == 4)
- return (0);
- *++tp = 0;
- saw_digit = 0;
- }
- else
- return (0);
- }
- if (octets < 4)
- return (0);
+ {
+ int saw_digit = 0;
+ int octets = 0;
+ unsigned char *tp = tmp;
+ *tp = 0;
+ int ch;
+ while ((ch = *src++) != '\0')
+ {
+ if (ch >= '0' && ch <= '9')
+ {
+ if (saw_digit && *tp == 0)
+ return (0);
+ unsigned new = *tp * 10 + (ch - '0');
+ if (new > 255)
+ return (0);
+ *tp = new;
+ if (!saw_digit)
+ {
+ if (++octets > 4)
+ return (0);
+ saw_digit = 1;
+ }
+ }
+ else if (ch == '.' && saw_digit)
+ {
+ if (octets == 4)
+ return (0);
+ *++tp = 0;
+ saw_digit = 0;
+ }
+ else
+ return (0);
+ }
+ if (octets < 4)
+ return (0);
+ }
memcpy (dst, tmp, NS_INADDRSZ);
return (1);
}
inet_pton6 (const char *restrict src, unsigned char *restrict dst)
{
static const char xdigits[] = "0123456789abcdef";
- unsigned char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
- const char *curtok;
- int ch, saw_xdigit;
- unsigned val;
+ unsigned char tmp[NS_IN6ADDRSZ];
- tp = memset (tmp, '\0', NS_IN6ADDRSZ);
- endp = tp + NS_IN6ADDRSZ;
- colonp = NULL;
/* Leading :: requires some special handling. */
if (*src == ':')
if (*++src != ':')
return (0);
- curtok = src;
- saw_xdigit = 0;
- val = 0;
- while ((ch = c_tolower (*src++)) != '\0')
- {
- const char *pch;
- pch = strchr (xdigits, ch);
- if (pch != NULL)
- {
- val <<= 4;
- val |= (pch - xdigits);
- if (val > 0xffff)
- return (0);
- saw_xdigit = 1;
- }
- else if (ch == ':')
- {
- curtok = src;
- if (!saw_xdigit)
- {
- if (colonp)
- return (0);
- colonp = tp;
- }
- else if (*src == '\0')
- {
+ {
+ unsigned char *tp = memset (tmp, '\0', NS_IN6ADDRSZ);
+ unsigned char *endp = tp + NS_IN6ADDRSZ;
+ unsigned char *colonp = NULL;
+ const char *curtok = src;
+ int saw_xdigit = 0;
+ unsigned int val = 0;
+ int ch;
+ while ((ch = c_tolower (*src++)) != '\0')
+ {
+ const char *pch = strchr (xdigits, ch);
+ if (pch != NULL)
+ {
+ val <<= 4;
+ val |= (pch - xdigits);
+ if (val > 0xffff)
return (0);
- }
- else if (tp + NS_INT16SZ > endp)
- return (0);
- else
- {
- *tp++ = (unsigned char) (val >> 8) & 0xff;
- *tp++ = (unsigned char) val & 0xff;
- saw_xdigit = 0;
- val = 0;
- }
- }
- else if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
- inet_pton4 (curtok, tp) > 0)
- {
- tp += NS_INADDRSZ;
- saw_xdigit = 0;
- break; /* '\0' was seen by inet_pton4(). */
- }
- else
- return (0);
- }
- if (saw_xdigit)
- {
- if (tp + NS_INT16SZ > endp)
- return (0);
- *tp++ = (unsigned char) (val >> 8) & 0xff;
- *tp++ = (unsigned char) val & 0xff;
- }
- if (colonp != NULL)
- {
- /*
- * Since some memmove()'s erroneously fail to handle
- * overlapping regions, we'll do the shift by hand.
- */
- const int n = tp - colonp;
-
- if (tp == endp)
- return (0);
- for (int i = 1; i <= n; i++)
- {
- endp[-i] = colonp[n - i];
- colonp[n - i] = 0;
- }
- tp = endp;
- }
- if (tp != endp)
- return (0);
+ saw_xdigit = 1;
+ }
+ else if (ch == ':')
+ {
+ curtok = src;
+ if (!saw_xdigit)
+ {
+ if (colonp)
+ return (0);
+ colonp = tp;
+ }
+ else if (*src == '\0')
+ return (0);
+ else if (tp + NS_INT16SZ > endp)
+ return (0);
+ else
+ {
+ *tp++ = (unsigned char) (val >> 8) & 0xff;
+ *tp++ = (unsigned char) val & 0xff;
+ saw_xdigit = 0;
+ val = 0;
+ }
+ }
+ else if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
+ inet_pton4 (curtok, tp) > 0)
+ {
+ tp += NS_INADDRSZ;
+ saw_xdigit = 0;
+ break; /* '\0' was seen by inet_pton4(). */
+ }
+ else
+ return (0);
+ }
+ if (saw_xdigit)
+ {
+ if (tp + NS_INT16SZ > endp)
+ return (0);
+ *tp++ = (unsigned char) (val >> 8) & 0xff;
+ *tp++ = (unsigned char) val & 0xff;
+ }
+ if (colonp != NULL)
+ {
+ if (tp == endp)
+ return (0);
+ /*
+ * Since some memmove()'s erroneously fail to handle
+ * overlapping regions, we'll do the shift by hand.
+ */
+ const int n = tp - colonp;
+ for (int i = 1; i <= n; i++)
+ {
+ endp[-i] = colonp[n - i];
+ colonp[n - i] = 0;
+ }
+ tp = endp;
+ }
+ if (tp != endp)
+ return (0);
+ }
memcpy (dst, tmp, NS_IN6ADDRSZ);
return (1);
}
size_t
ino_map_insert (struct ino_map *im, ino_t ino)
{
- struct ino_map_ent *ent;
-
/* Find space for the probe, reusing the cache if available. */
struct ino_map_ent *probe = im->probe;
if (probe)
}
probe->ino = ino;
- ent = hash_insert (im->map, probe);
+ struct ino_map_ent *ent = hash_insert (im->map, probe);
if (! ent)
return INO_MAP_INSERT_FAILURE;
else
{
memory_double m;
- unsigned int exponent;
if (1)
{
m.value = m.value - TWO_DBL_MANT_DIG;
}
- exponent =
+ unsigned int exponent =
(m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK;
return exponent - DBL_EXP_BIAS;
}
int
rpl_ioctl (int fd, int request, ... /* {void *,char *} arg */)
{
- void *buf;
va_list args;
-
va_start (args, request);
- buf = va_arg (args, void *);
+ void *buf = va_arg (args, void *);
va_end (args);
/* Cast 'request' so that when the system's ioctl function takes a 64-bit
int
ioctl (int fd, int request, ... /* {void *,char *} arg */)
{
- void *arg;
va_list args;
-
va_start (args, request);
- arg = va_arg (args, void *);
+ void *arg = va_arg (args, void *);
va_end (args);
# if WINDOWS_SOCKETS
#else
/* Implementation for the global locale. */
{
- int ret;
# if HAVE_WORKING_USELOCALE
locale_t saved_locale = uselocale (LC_GLOBAL_LOCALE);
# endif
- ret = GLOBAL_FUNC (c);
+ int ret = GLOBAL_FUNC (c);
# if HAVE_WORKING_USELOCALE
uselocale (saved_locale);
# endif
{
nlink_t pipe_link_count_max = PIPE_LINK_COUNT_MAX;
bool check_for_fifo = (HAVE_FIFO_PIPES == 1);
+
struct stat st;
int fstat_result = fstat (fd, &st);
-
if (fstat_result != 0)
return fstat_result;
static BOOL IsCygwinConsoleHandle (HANDLE h)
{
- /* A handle to a Cygwin console is in fact a named pipe whose client process
- and server process is <CYGWIN_INSTALL_DIR>\bin\mintty.exe. */
- BOOL result = FALSE;
- ULONG processId;
-
#if !(_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if (!initialized)
initialize ();
#endif
+ /* A handle to a Cygwin console is in fact a named pipe whose client process
+ and server process is <CYGWIN_INSTALL_DIR>\bin\mintty.exe. */
+ BOOL result = FALSE;
+
/* GetNamedPipeClientProcessId
<https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-getnamedpipeclientprocessid>
It requires -D_WIN32_WINNT=_WIN32_WINNT_VISTA or higher. */
- if (GetNamedPipeClientProcessIdFunc && QueryFullProcessImageNameFunc
- && GetNamedPipeClientProcessIdFunc (h, &processId))
+ if (GetNamedPipeClientProcessIdFunc && QueryFullProcessImageNameFunc)
{
- /* OpenProcess
- <https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess> */
- HANDLE processHandle =
- OpenProcess (PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
- if (processHandle != NULL)
+ ULONG processId;
+ if (GetNamedPipeClientProcessIdFunc (h, &processId))
{
- char buf[1024];
- DWORD bufsize = sizeof (buf);
- /* The file name can be determined through
- GetProcessImageFileName
- <https://docs.microsoft.com/en-us/windows/desktop/api/psapi/nf-psapi-getprocessimagefilenamea>
- or
- QueryFullProcessImageName
- <https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-queryfullprocessimagenamea>
- The former returns a file name in non-standard notation (it starts
- with '\Device\') and may require linking with psapi.dll.
- The latter is better, but requires -D_WIN32_WINNT=_WIN32_WINNT_VISTA
- or higher. */
- if (QueryFullProcessImageNameFunc (processHandle, 0, buf, &bufsize))
+ /* OpenProcess
+ <https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess> */
+ HANDLE processHandle =
+ OpenProcess (PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
+ if (processHandle != NULL)
{
- if (str_endswith (buf, "\\mintty.exe"))
- result = TRUE;
+ char buf[1024];
+ DWORD bufsize = sizeof (buf);
+ /* The file name can be determined through
+ GetProcessImageFileName
+ <https://docs.microsoft.com/en-us/windows/desktop/api/psapi/nf-psapi-getprocessimagefilenamea>
+ or
+ QueryFullProcessImageName
+ <https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-queryfullprocessimagenamea>
+ The former returns a file name in non-standard notation (it
+ starts with '\Device\') and may require linking with psapi.dll.
+ The latter is better, but requires
+ -D_WIN32_WINNT=_WIN32_WINNT_VISTA or higher. */
+ if (QueryFullProcessImageNameFunc (processHandle, 0, buf, &bufsize))
+ {
+ if (str_endswith (buf, "\\mintty.exe"))
+ result = TRUE;
+ }
+ CloseHandle (processHandle);
}
- CloseHandle (processHandle);
}
}
return result;
The NaN bit pattern is:
- exponent = 0x7FFF, mantissa >= 0x8000000000000001. */
memory_double m;
- unsigned int exponent;
-
m.value = x;
- exponent = (m.word[EXPBIT0_WORD] >> EXPBIT0_BIT) & EXP_MASK;
+ unsigned int exponent = (m.word[EXPBIT0_WORD] >> EXPBIT0_BIT) & EXP_MASK;
# ifdef WORDS_BIGENDIAN
/* Big endian: EXPBIT0_WORD = 0, EXPBIT0_BIT = 16. */
if (exponent == 0)
Visual C/C++ compiler also fails when constant-folding 1.0 / 0.0 even
when constant-folding is not required. */
static DOUBLE zero = L_(0.0);
- memory_double nan;
DOUBLE plus_inf = L_(1.0) / zero;
DOUBLE minus_inf = -L_(1.0) / zero;
+ memory_double nan;
nan.value = zero / zero;
# else
static memory_double nan = { L_(0.0) / L_(0.0) };
# endif
{
memory_double m;
+ m.value = x;
/* A NaN can be recognized through its exponent. But exclude +Infinity and
-Infinity, which have the same exponent. */
- m.value = x;
if (((m.word[EXPBIT0_WORD] ^ nan.word[EXPBIT0_WORD])
& (EXP_MASK << EXPBIT0_BIT))
== 0)
# if defined USE_LONG_DOUBLE && ((defined __ia64 && LDBL_MANT_DIG == 64) || (defined __x86_64__ || defined __amd64__) || (defined __i386 || defined __i386__ || defined _I386 || defined _M_IX86 || defined _X86_)) && !HAVE_SAME_LONG_DOUBLE_AS_DOUBLE
/* Detect any special bit patterns that pass ==; see comment above. */
memory_double m1;
- memory_double m2;
-
memset (&m1.value, 0, SIZE);
- memset (&m2.value, 0, SIZE);
m1.value = x;
+
+ memory_double m2;
+ memset (&m2.value, 0, SIZE);
m2.value = x + (x ? 0.0L : -0.0L);
+
if (!memeq (&m1.value, &m2.value, SIZE))
return 1;
# endif
shell. Because $JAVAC has been set by the user, we leave all
environment variables in place, including JAVA_HOME, and we don't
erase the user's CLASSPATH. */
- bool err;
- unsigned int command_length;
- char *command;
- const char *argv[4];
- int exitstatus;
- char *p;
- command_length = strlen (javac);
+ unsigned int command_length = strlen (javac);
if (optimize)
command_length += 3;
if (debug)
command_length += 1 + shell_quote_length (java_sources[i]);
command_length += 1;
- command = (char *) xmalloca (command_length);
- p = command;
- /* Don't shell_quote $JAVAC, because it may consist of a command
- and options. */
- memcpy (p, javac, strlen (javac));
- p += strlen (javac);
- if (optimize)
- {
- memcpy (p, " -O", 3);
- p += 3;
- }
- if (debug)
- {
- memcpy (p, " -g", 3);
- p += 3;
- }
- if (directory != NULL)
- {
- memcpy (p, " -d ", 4);
- p += 4;
- p = shell_quote_copy (p, directory);
- }
- for (unsigned int i = 0; i < java_sources_count; i++)
- {
- *p++ = ' ';
- p = shell_quote_copy (p, java_sources[i]);
- }
- *p++ = '\0';
- /* Ensure command_length was correctly calculated. */
- if (p - command > command_length)
- abort ();
+ char *command = (char *) xmalloca (command_length);
+ {
+ char *p = command;
+ /* Don't shell_quote $JAVAC, because it may consist of a command
+ and options. */
+ memcpy (p, javac, strlen (javac));
+ p += strlen (javac);
+ if (optimize)
+ {
+ memcpy (p, " -O", 3);
+ p += 3;
+ }
+ if (debug)
+ {
+ memcpy (p, " -g", 3);
+ p += 3;
+ }
+ if (directory != NULL)
+ {
+ memcpy (p, " -d ", 4);
+ p += 4;
+ p = shell_quote_copy (p, directory);
+ }
+ for (unsigned int i = 0; i < java_sources_count; i++)
+ {
+ *p++ = ' ';
+ p = shell_quote_copy (p, java_sources[i]);
+ }
+ *p++ = '\0';
+ /* Ensure command_length was correctly calculated. */
+ if (p - command > command_length)
+ abort ();
+ }
if (verbose)
printf ("%s\n", command);
+ const char *argv[4];
argv[0] = BOURNE_SHELL;
argv[1] = "-c";
argv[2] = command;
argv[3] = NULL;
- exitstatus = execute (javac, BOURNE_SHELL, argv, NULL, NULL,
- false, false, false, null_stderr,
- true, true, NULL);
- err = (exitstatus != 0);
+ int exitstatus = execute (javac, BOURNE_SHELL, argv, NULL, NULL,
+ false, false, false, null_stderr,
+ true, true, NULL);
+ bool err = (exitstatus != 0);
freea (command);
bool optimize, bool debug,
bool verbose, bool null_stderr)
{
- bool err;
- unsigned int argc;
- const char **argv;
- const char **argp;
- int exitstatus;
-
- argc =
+ unsigned int argc =
1 + (nowarn_option != NULL ? 1 : 0) + (source_option ? 2 : 0)
+ (target_option ? 2 : 0) + (optimize ? 1 : 0) + (debug ? 1 : 0)
+ (directory != NULL ? 2 : 0) + java_sources_count;
- argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
-
- argp = argv;
- *argp++ = "javac";
- if (nowarn_option != NULL)
- *argp++ = nowarn_option;
- if (source_option)
- {
- *argp++ = "-source";
- *argp++ = source_version;
- }
- if (target_option)
- {
- *argp++ = "-target";
- *argp++ = target_version;
- }
- if (optimize)
- *argp++ = "-O";
- if (debug)
- *argp++ = "-g";
- if (directory != NULL)
- {
- *argp++ = "-d";
- *argp++ = directory;
- }
- for (unsigned int i = 0; i < java_sources_count; i++)
- *argp++ = java_sources[i];
- *argp = NULL;
- /* Ensure argv length was correctly calculated. */
- if (argp - argv != argc)
- abort ();
+ const char **argv = (const char **) xmalloca ((argc + 1) * sizeof (const char *));
+ {
+ const char **argp = argv;
+ *argp++ = "javac";
+ if (nowarn_option != NULL)
+ *argp++ = nowarn_option;
+ if (source_option)
+ {
+ *argp++ = "-source";
+ *argp++ = source_version;
+ }
+ if (target_option)
+ {
+ *argp++ = "-target";
+ *argp++ = target_version;
+ }
+ if (optimize)
+ *argp++ = "-O";
+ if (debug)
+ *argp++ = "-g";
+ if (directory != NULL)
+ {
+ *argp++ = "-d";
+ *argp++ = directory;
+ }
+ for (unsigned int i = 0; i < java_sources_count; i++)
+ *argp++ = java_sources[i];
+ *argp = NULL;
+ /* Ensure argv length was correctly calculated. */
+ if (argp - argv != argc)
+ abort ();
+ }
if (verbose)
{
free (command);
}
- exitstatus = execute ("javac", "javac", argv, NULL, NULL,
- false, false, false,
- null_stderr, true, true, NULL);
- err = (exitstatus != 0);
+ int exitstatus = execute ("javac", "javac", argv, NULL, NULL,
+ false, false, false,
+ null_stderr, true, true, NULL);
+ bool err = (exitstatus != 0);
freea (argv);
execute_and_read_line (const char *progname,
const char *prog_path, const char * const *prog_argv)
{
- pid_t child;
- int fd[1];
- FILE *fp;
- char *line;
- size_t linesize;
- size_t linelen;
-
/* Open a pipe to the program. */
- child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
- DEV_NULL, false, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
+ DEV_NULL, false, true, false, fd);
if (child == -1)
return NULL;
/* Retrieve its result. */
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
- line = NULL; linesize = 0;
- linelen = getline (&line, &linesize, fp);
+ char *line = NULL;
+ size_t linesize = 0;
+ size_t linelen = getline (&line, &linesize, fp);
if (linelen == (size_t)(-1))
{
error (0, 0, _("%s subprocess I/O error"), progname);
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, progname, true, false, true, false, NULL);
if (exitstatus == 0)
return line;
write_temp_file (struct temp_dir *tmpdir, const char *file_name,
const char *contents)
{
- FILE *fp;
-
register_temp_file (tmpdir, file_name);
- fp = fopen_temp (file_name, "we", false);
+ FILE *fp = fopen_temp (file_name, "we", false);
if (fp == NULL)
{
error (0, errno, _("failed to create \"%s\""), file_name);
static int
get_classfile_version (const char *compiled_file_name)
{
- unsigned char header[8];
- int fd;
/* Open the class file. */
- fd = open (compiled_file_name, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
+ int fd = open (compiled_file_name, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
if (fd >= 0)
{
/* Read its first 8 bytes. */
+ unsigned char header[8];
if (safe_read (fd, header, 8) == 8)
{
/* Verify the class file signature. */
if (try_source_version <= try_target_version)
{
/* Try $JAVAC. */
- struct temp_dir *tmpdir;
- char *conftest_file_name;
- char *compiled_file_name;
- const char *java_sources[1];
- const char *nowarn_option;
- struct stat statbuf;
-
- tmpdir = create_temp_dir ("java", NULL, false);
+ struct temp_dir *tmpdir = create_temp_dir ("java", NULL, false);
if (tmpdir == NULL)
return true;
- conftest_file_name =
+ char *conftest_file_name =
xconcatenated_filename (tmpdir->dir_name, "conftest.java", NULL);
if (write_temp_file (tmpdir, conftest_file_name, "class conftest {}"))
{
return true;
}
- compiled_file_name =
+ char *compiled_file_name =
xconcatenated_filename (tmpdir->dir_name, "conftest.class", NULL);
register_temp_file (tmpdir, compiled_file_name);
/* See the discussion in javacomp.m4. */
- nowarn_option = " -Xlint:-options";
+ const char *nowarn_option = " -Xlint:-options";
char *javac_nowarn = xasprintf ("%s%s", javac, nowarn_option);
assume (javac_nowarn != NULL);
+ const char *java_sources[1];
java_sources[0] = conftest_file_name;
+ struct stat statbuf;
if ((!compile_using_envjavac (javac_nowarn,
java_sources, 1, tmpdir->dir_name,
false, false, false, true)
{
/* Test for presence of javac: "javac 2> /dev/null ; test $? -le 2" */
const char *argv[2];
- int exitstatus;
-
argv[0] = "javac";
argv[1] = NULL;
- exitstatus = execute ("javac", "javac", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("javac", "javac", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
javac_present = (exitstatus == 0 || exitstatus == 1 || exitstatus == 2);
javac_tested = true;
}
if (try_source_version <= try_target_version)
{
/* Try javac. */
- struct temp_dir *tmpdir;
- char *conftest_file_name;
- char *compiled_file_name;
- const char *java_sources[1];
- const char *nowarn_option;
- struct stat statbuf;
-
- tmpdir = create_temp_dir ("java", NULL, false);
+ struct temp_dir *tmpdir = create_temp_dir ("java", NULL, false);
if (tmpdir == NULL)
return true;
- conftest_file_name =
+ char *conftest_file_name =
xconcatenated_filename (tmpdir->dir_name, "conftest.java", NULL);
if (write_temp_file (tmpdir, conftest_file_name, "class conftest {}"))
{
return true;
}
- compiled_file_name =
+ char *compiled_file_name =
xconcatenated_filename (tmpdir->dir_name, "conftest.class", NULL);
register_temp_file (tmpdir, compiled_file_name);
/* See the discussion in javacomp.m4. */
- nowarn_option = "-Xlint:-options";
+ const char *nowarn_option = "-Xlint:-options";
+ const char *java_sources[1];
java_sources[0] = conftest_file_name;
+ struct stat statbuf;
if ((!compile_using_javac (java_sources, 1,
nowarn_option,
false, source_version,
{
const char *argv[3];
-
argv[0] = "javac";
argv[1] = "-version";
argv[2] = NULL;
bool use_minimal_classpath,
bool verbose)
{
- bool err = false;
- char *old_JAVA_HOME;
-
/* Map source_version 1.1 ... 1.7 to 1.8. */
if (source_version[0] == '1' && source_version[1] == '.'
&& (source_version[2] >= '1' && source_version[2] <= '7')
&& target_version[3] == '\0')
target_version = "1.8";
+ bool err = false;
+
{
const char *javac = getenv ("JAVAC");
if (javac != NULL && javac[0] != '\0')
}
/* Unset the JAVA_HOME environment variable. */
- old_JAVA_HOME = getenv ("JAVA_HOME");
+ char *old_JAVA_HOME = getenv ("JAVA_HOME");
if (old_JAVA_HOME != NULL)
{
old_JAVA_HOME = xstrdup (old_JAVA_HOME);
if (usable)
{
- char *old_classpath;
-
/* Set CLASSPATH. We don't use the "-classpath ..." option because
in JDK 1.1.x its argument should also contain the JDK's
classes.zip, but we don't know its location. (In JDK 1.3.0 it
would work.) */
- old_classpath =
+ char *old_classpath =
set_classpath (classpaths, classpaths_count, use_minimal_classpath,
verbose);
execute_fn *executer, void *private_data)
{
bool err = false;
- unsigned int nargs;
- char *old_JAVA_HOME;
/* Count args. */
+ unsigned int nargs;
{
const char * const *arg;
if (exe_dir != NULL)
{
char *exe_pathname = xconcatenated_filename (exe_dir, class_name, EXEEXT);
- char *old_classpath;
- const char **argv =
- (const char **) xmalloca ((1 + nargs + 1) * sizeof (const char *));
/* Set CLASSPATH. */
- old_classpath =
+ char *old_classpath =
set_classpath (classpaths, classpaths_count, use_minimal_classpath,
verbose);
+ const char **argv =
+ (const char **) xmalloca ((1 + nargs + 1) * sizeof (const char *));
argv[0] = exe_pathname;
for (unsigned int i = 0; i <= nargs; i++)
argv[1 + i] = args[i];
err = executer (class_name, exe_pathname, argv, private_data);
+ freea (argv);
+
/* Reset CLASSPATH. */
reset_classpath (old_classpath);
- freea (argv);
-
goto done1;
}
shell. Because $JAVA has been set by the user, we leave all
all environment variables in place, including JAVA_HOME, and
we don't erase the user's CLASSPATH. */
- char *old_classpath;
- unsigned int command_length;
- char *command;
- const char *argv[4];
- char *p;
/* Set CLASSPATH. */
- old_classpath =
+ char *old_classpath =
set_classpath (classpaths, classpaths_count, false,
verbose);
- command_length = strlen (java);
+ unsigned int command_length = strlen (java);
command_length += 1 + shell_quote_length (class_name);
for (const char * const *arg = args; *arg != NULL; arg++)
command_length += 1 + shell_quote_length (*arg);
command_length += 1;
- command = (char *) xmalloca (command_length);
- p = command;
- /* Don't shell_quote $JAVA, because it may consist of a command
- and options. */
- memcpy (p, java, strlen (java));
- p += strlen (java);
- *p++ = ' ';
- p = shell_quote_copy (p, class_name);
- for (const char * const *arg = args; *arg != NULL; arg++)
- {
- *p++ = ' ';
- p = shell_quote_copy (p, *arg);
- }
- *p++ = '\0';
- /* Ensure command_length was correctly calculated. */
- if (p - command > command_length)
- abort ();
+ char *command = (char *) xmalloca (command_length);
+ {
+ char *p = command;
+ /* Don't shell_quote $JAVA, because it may consist of a command
+ and options. */
+ memcpy (p, java, strlen (java));
+ p += strlen (java);
+ *p++ = ' ';
+ p = shell_quote_copy (p, class_name);
+ for (const char * const *arg = args; *arg != NULL; arg++)
+ {
+ *p++ = ' ';
+ p = shell_quote_copy (p, *arg);
+ }
+ *p++ = '\0';
+ /* Ensure command_length was correctly calculated. */
+ if (p - command > command_length)
+ abort ();
+ }
if (verbose)
printf ("%s\n", command);
+ const char *argv[4];
argv[0] = BOURNE_SHELL;
argv[1] = "-c";
argv[2] = command;
}
/* Unset the JAVA_HOME environment variable. */
- old_JAVA_HOME = getenv ("JAVA_HOME");
+ char *old_JAVA_HOME = getenv ("JAVA_HOME");
if (old_JAVA_HOME != NULL)
{
old_JAVA_HOME = xstrdup (old_JAVA_HOME);
{
/* Test for presence of java: "java -version 2> /dev/null" */
const char *argv[3];
- int exitstatus;
-
argv[0] = "java";
argv[1] = "-version";
argv[2] = NULL;
- exitstatus = execute ("java", "java", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("java", "java", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
java_present = (exitstatus == 0);
java_tested = true;
}
if (java_present)
{
- char *old_classpath;
- const char **argv =
- (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
-
/* Set CLASSPATH. We don't use the "-classpath ..." option because
in JDK 1.1.x its argument should also contain the JDK's classes.zip,
but we don't know its location. (In JDK 1.3.0 it would work.) */
- old_classpath =
+ char *old_classpath =
set_classpath (classpaths, classpaths_count, use_minimal_classpath,
verbose);
+ const char **argv =
+ (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
argv[0] = "java";
argv[1] = class_name;
for (unsigned int i = 0; i <= nargs; i++)
err = executer ("java", "java", argv, private_data);
+ freea (argv);
+
/* Reset CLASSPATH. */
reset_classpath (old_classpath);
- freea (argv);
-
goto done2;
}
}
{
/* Test for presence of jre: "jre 2> /dev/null ; test $? = 1" */
const char *argv[2];
- int exitstatus;
-
argv[0] = "jre";
argv[1] = NULL;
- exitstatus = execute ("jre", "jre", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+ int exitstatus = execute ("jre", "jre", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
jre_present = (exitstatus == 0 || exitstatus == 1);
jre_tested = true;
}
if (jre_present)
{
- char *old_classpath;
- const char **argv =
- (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
-
/* Set CLASSPATH. We don't use the "-classpath ..." option because
in JDK 1.1.x its argument should also contain the JDK's classes.zip,
but we don't know its location. */
- old_classpath =
+ char *old_classpath =
set_classpath (classpaths, classpaths_count, use_minimal_classpath,
verbose);
+ const char **argv =
+ (const char **) xmalloca ((2 + nargs + 1) * sizeof (const char *));
argv[0] = "jre";
argv[1] = class_name;
for (unsigned int i = 0; i <= nargs; i++)
err = executer ("jre", "jre", argv, private_data);
+ freea (argv);
+
/* Reset CLASSPATH. */
reset_classpath (old_classpath);
- freea (argv);
-
goto done2;
}
}
void *private_data)
{
struct locals *l = (struct locals *) private_data;
- pid_t child;
- int fd[1];
- FILE *fp;
- char *line;
- size_t linesize;
- size_t linelen;
/* Open a pipe to the JVM. */
- child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
- DEV_NULL, false, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
+ DEV_NULL, false, true, false, fd);
if (child == -1)
return false;
/* Retrieve its result. */
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
- line = NULL; linesize = 0;
- linelen = getline (&line, &linesize, fp);
+ char *line = NULL;
+ size_t linesize = 0;
+ size_t linelen = getline (&line, &linesize, fp);
if (linelen == (size_t)(-1))
{
error (0, 0, _("%s subprocess I/O error"), progname);
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, progname, true, false, true, false, NULL);
if (exitstatus == 0)
{
const char *class_name = "javaversion";
char *malloc_pkgdatadir;
const char *pkgdatadir = relocate2 (PKGDATADIR, &malloc_pkgdatadir);
- const char *args[1];
- struct locals locals;
+ const char *args[1];
args[0] = NULL;
+
+ struct locals locals;
locals.line = NULL;
+
execute_java_class (class_name, &pkgdatadir, 1, true, NULL, args,
false, false, execute_and_read_line, &locals);
treefails (struct tree const *tree, struct trie const *fail,
struct trie *recourse, bool reverse)
{
- struct tree *cur;
-
if (!tree)
return;
node that has a descendant on the current label. */
while (fail)
{
- cur = fail->links;
+ struct tree *cur = fail->links;
while (cur && tree->label != cur->label)
if (tree->label < cur->label)
cur = cur->llink;
char const *trans = kwset->trans;
unsigned char deltabuf[NCHAR];
unsigned char *delta = trans ? deltabuf : kwset->delta;
- struct trie *curr, *last;
/* Use Boyer-Moore if just one pattern, Aho-Corasick otherwise. */
bool reverse = kwset->words == 1;
if (reverse)
{
- kwset_t new_kwset;
-
/* Enqueue the immediate descendants in the level order queue. */
- for (curr = last = kwset->trie; curr; curr = curr->next)
- enqueue (curr->links, &last);
+ {
+ struct trie *last;
+ for (struct trie *curr = last = kwset->trie; curr; curr = curr->next)
+ enqueue (curr->links, &last);
+ }
/* Looking for just one string. Extract it from the trie. */
kwset->target = obstack_alloc (&kwset->obstack, kwset->mind);
- curr = kwset->trie;
+ struct trie *curr = kwset->trie;
for (idx_t i = 0; i < kwset->mind; i++)
{
kwset->target[i] = curr->links->label;
curr = curr->next;
}
- new_kwset = kwsalloc (kwset->trans);
+ kwset_t new_kwset = kwsalloc (kwset->trans);
new_kwset->kwsexec = bmexec;
kwsincr (new_kwset, kwset->target, kwset->mind);
obstack_free (&kwset->obstack, nullptr);
/* Traverse the nodes of the trie in level order, simultaneously
computing the delta table, failure function, and shift function. */
- for (curr = last = kwset->trie; curr; curr = curr->next)
- {
- /* Enqueue the immediate descendants in the level order queue. */
- enqueue (curr->links, &last);
+ {
+ struct trie *last;
+ for (struct trie *curr = last = kwset->trie; curr; curr = curr->next)
+ {
+ /* Enqueue the immediate descendants in the level order queue. */
+ enqueue (curr->links, &last);
- /* Update the delta table for the descendants of this node. */
- treedelta (curr->links, curr->depth, delta);
+ /* Update the delta table for the descendants of this node. */
+ treedelta (curr->links, curr->depth, delta);
- /* Compute the failure function for the descendants of this node. */
- treefails (curr->links, curr->fail, kwset->trie, reverse);
+ /* Compute the failure function for the descendants of this node. */
+ treefails (curr->links, curr->fail, kwset->trie, reverse);
- if (reverse)
- {
- curr->shift = kwset->mind;
- curr->maxshift = kwset->mind;
+ if (reverse)
+ {
+ curr->shift = kwset->mind;
+ curr->maxshift = kwset->mind;
- /* Update the shifts at each node in the current node's chain
- of fails back to the root. */
- for (struct trie *fail = curr->fail; fail; fail = fail->fail)
- {
- /* If the current node has some outgoing edge that the fail
- doesn't, then the shift at the fail should be no larger
- than the difference of their depths. */
- if (!hasevery (fail->links, curr->links))
- if (curr->depth - fail->depth < fail->shift)
- fail->shift = curr->depth - fail->depth;
-
- /* If the current node is accepting then the shift at the
- fail and its descendants should be no larger than the
- difference of their depths. */
- if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
- fail->maxshift = curr->depth - fail->depth;
- }
- }
- }
+ /* Update the shifts at each node in the current node's chain
+ of fails back to the root. */
+ for (struct trie *fail = curr->fail; fail; fail = fail->fail)
+ {
+ /* If the current node has some outgoing edge that the fail
+ doesn't, then the shift at the fail should be no larger
+ than the difference of their depths. */
+ if (!hasevery (fail->links, curr->links))
+ if (curr->depth - fail->depth < fail->shift)
+ fail->shift = curr->depth - fail->depth;
+
+ /* If the current node is accepting then the shift at the
+ fail and its descendants should be no larger than the
+ difference of their depths. */
+ if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
+ fail->maxshift = curr->depth - fail->depth;
+ }
+ }
+ }
+ }
if (reverse)
{
/* Traverse the trie in level order again, fixing up all nodes whose
shift exceeds their inherited maxshift. */
- for (curr = kwset->trie->next; curr; curr = curr->next)
+ for (struct trie *curr = kwset->trie->next; curr; curr = curr->next)
{
if (curr->maxshift > curr->parent->maxshift)
curr->maxshift = curr->parent->maxshift;
/* Create a vector, indexed by character code, of the outgoing links
from the root node. Accumulate GC1 and GC1HELP. */
- struct trie *nextbuf[NCHAR];
- struct trie **next = trans ? nextbuf : kwset->next;
- memset (next, 0, sizeof nextbuf);
- treenext (kwset->trie->links, next);
- int gc1 = -2;
- int gc1help = -1;
- for (int i = 0; i < NCHAR; i++)
- {
- int ti = i;
- if (trans)
- {
- ti = U(trans[i]);
- kwset->next[i] = next[ti];
- }
- if (kwset->next[i])
- {
- if (gc1 < -1)
- {
- gc1 = ti;
+ {
+ struct trie *nextbuf[NCHAR];
+ struct trie **next = trans ? nextbuf : kwset->next;
+ memset (next, 0, sizeof nextbuf);
+ treenext (kwset->trie->links, next);
+ int gc1 = -2;
+ int gc1help = -1;
+ for (int i = 0; i < NCHAR; i++)
+ {
+ int ti = i;
+ if (trans)
+ {
+ ti = U(trans[i]);
+ kwset->next[i] = next[ti];
+ }
+ if (kwset->next[i])
+ {
+ if (gc1 < -1)
+ {
+ gc1 = ti;
+ gc1help = i;
+ }
+ else if (gc1 == ti)
+ gc1help = gc1help == ti ? i : -1;
+ else if (i == ti && gc1 == gc1help)
gc1help = i;
- }
- else if (gc1 == ti)
- gc1help = gc1help == ti ? i : -1;
- else if (i == ti && gc1 == gc1help)
- gc1help = i;
- else
- gc1 = -1;
- }
- }
- kwset->gc1 = gc1;
- kwset->gc1help = gc1help;
+ else
+ gc1 = -1;
+ }
+ }
+ kwset->gc1 = gc1;
+ kwset->gc1help = gc1help;
+ }
if (reverse)
{
/* Looking for just one string. Extract it from the trie. */
kwset->target = obstack_alloc (&kwset->obstack, kwset->mind);
- curr = kwset->trie;
- for (idx_t i = kwset->mind; 0 < i; i--)
- {
- kwset->target[i - 1] = curr->links->label;
- curr = curr->next;
- }
+ {
+ struct trie *curr = kwset->trie;
+ for (idx_t i = kwset->mind; 0 < i; i--)
+ {
+ kwset->target[i - 1] = curr->links->label;
+ curr = curr->next;
+ }
+ }
if (kwset->mind > 1)
{
kwset->shift
= obstack_alloc (&kwset->obstack,
sizeof *kwset->shift * (kwset->mind - 1));
- curr = kwset->trie->next;
- for (idx_t i = 0; i < kwset->mind - 1; i++)
- {
- kwset->shift[i] = curr->shift;
- curr = curr->next;
- }
+ {
+ struct trie *curr = kwset->trie->next;
+ for (idx_t i = 0; i < kwset->mind - 1; i++)
+ {
+ kwset->shift[i] = curr->shift;
+ curr = curr->next;
+ }
+ }
/* The penultimate byte. */
kwset->gc2 = tr (trans, kwset->target[kwset->mind - 2]);
bmexec_trans (kwset_t kwset, char const *text, idx_t size)
{
assume (0 <= size);
- unsigned char const *d1;
- char const *ep, *sp, *tp;
- int d;
- idx_t len = kwset->mind;
- char const *trans = kwset->trans;
+ idx_t len = kwset->mind;
if (len == 0)
return 0;
if (len > size)
return -1;
if (len == 1)
{
- tp = memchr_kwset (text, size, kwset);
+ char const *tp = memchr_kwset (text, size, kwset);
return tp ? tp - text : -1;
}
- d1 = kwset->delta;
- sp = kwset->target + len;
- tp = text + len;
+ char const *trans = kwset->trans;
+
+ unsigned char const *d1 = kwset->delta;
+ char const *sp = kwset->target + len;
+ char const *tp = text + len;
char gc1 = kwset->gc1;
char gc2 = kwset->gc2;
idx_t len12;
if (!ckd_mul (&len12, len, 12) && len12 < size)
/* 11 is not a bug, the initial offset happens only once. */
- for (ep = text + size - 11 * len; tp <= ep; )
+ for (char const *ep = text + size - 11 * len; tp <= ep; )
{
char const *tp0 = tp;
+ int d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d != 0)
/* Now only a few characters are left to search. Carefully avoid
ever producing an out-of-bounds pointer. */
- ep = text + size;
- d = d1[U(tp[-1])];
+ char const *ep = text + size;
+ int d = d1[U(tp[-1])];
while (d <= ep - tp)
{
d = d1[U((tp += d)[-1])];
acexec_trans (kwset_t kwset, char const *text, idx_t len,
struct kwsmatch *kwsmatch, bool longest)
{
- struct trie const *trie, *accept;
- char const *tp, *left, *lim;
- struct tree const *tree;
- char const *trans;
-
/* Initialize register copies and look for easy ways out. */
if (len < kwset->mind)
return -1;
- trans = kwset->trans;
- trie = kwset->trie;
- lim = text + len;
- tp = text;
+
+ char const *trans = kwset->trans;
+ struct trie const *trie = kwset->trie;
+ char const *lim = text + len;
+ char const *tp = text;
if (!trie->accepting)
{
return -1;
c = tr (trans, *tp++);
+ struct tree const *tree;
for (tree = trie->links; c != tree->label; )
{
tree = c < tree->label ? tree->llink : tree->rlink;
}
}
- match:
- accept = trie;
+ match: ;
+ struct trie const *accept = trie;
while (accept->accepting < 0)
accept = accept->fail;
- left = tp - accept->depth;
+ char const *left = tp - accept->depth;
/* Try left-most longest match. */
if (longest)
{
while (tp < lim)
{
- struct trie const *accept1;
- char const *left1;
unsigned char c = tr (trans, *tp++);
+ struct tree const *tree;
do
{
tree = trie->links;
trie = tree->trie;
if (trie->accepting)
{
- accept1 = trie;
+ struct trie const *accept1 = trie;
while (accept1->accepting < 0)
accept1 = accept1->fail;
- left1 = tp - accept1->depth;
+ char const *left1 = tp - accept1->depth;
if (left1 <= left)
{
left = left1;
int
rpl_lchown (const char *file, uid_t owner, gid_t group)
{
- struct stat st;
gid_t no_gid = -1;
uid_t no_uid = -1;
bool gid_noop = group == no_gid;
bool uid_noop = owner == no_uid;
bool change_time_check = CHOWN_CHANGE_TIME_BUG && !(gid_noop & uid_noop);
+ struct stat st;
if (change_time_check
|| (CHOWN_TRAILING_SLASH_BUG
readlinebuffer_delim (struct linebuffer *linebuffer, FILE *stream,
char delimiter)
{
- int c;
+ if (feof (stream))
+ return NULL;
+
char *buffer = linebuffer->buffer;
char *p = linebuffer->buffer;
char *end = buffer + linebuffer->size; /* Sentinel. */
-
- if (feof (stream))
- return NULL;
+ int c;
do
{
int
link (const char *file1, const char *file2)
{
- char *dir;
- size_t len1 = strlen (file1);
- size_t len2 = strlen (file2);
-
# if !(_WIN32_WINNT >= _WIN32_WINNT_WINXP)
if (!initialized)
initialize ();
errno = EPERM;
return -1;
}
+
/* Reject trailing slashes on non-directories; native Windows does not
support hard-linking directories. */
- if ((len1 && (file1[len1 - 1] == '/' || file1[len1 - 1] == '\\'))
- || (len2 && (file2[len2 - 1] == '/' || file2[len2 - 1] == '\\')))
- {
- /* If stat() fails, then link() should fail for the same reason. */
- struct stat st;
- if (stat (file1, &st))
- {
- if (errno == EOVERFLOW)
- /* It's surely a file, not a directory (see stat-w32.c). */
- errno = ENOTDIR;
- return -1;
- }
- if (!S_ISDIR (st.st_mode))
- errno = ENOTDIR;
- else
- errno = EPERM;
- return -1;
- }
+ {
+ size_t len1 = strlen (file1);
+ size_t len2 = strlen (file2);
+ if ((len1 && (file1[len1 - 1] == '/' || file1[len1 - 1] == '\\'))
+ || (len2 && (file2[len2 - 1] == '/' || file2[len2 - 1] == '\\')))
+ {
+ /* If stat() fails, then link() should fail for the same reason. */
+ struct stat st;
+ if (stat (file1, &st))
+ {
+ if (errno == EOVERFLOW)
+ /* It's surely a file, not a directory (see stat-w32.c). */
+ errno = ENOTDIR;
+ return -1;
+ }
+ if (!S_ISDIR (st.st_mode))
+ errno = ENOTDIR;
+ else
+ errno = EPERM;
+ return -1;
+ }
+ }
/* CreateHardLink("b/.","a",NULL) creates file "b", so we must check
that dirname(file2) exists. */
- dir = strdup (file2);
+ char *dir = strdup (file2);
if (!dir)
return -1;
{
int
rpl_link (char const *file1, char const *file2)
{
- size_t len1;
- size_t len2;
struct stat st;
/* Don't allow IRIX to dereference dangling file2 symlink. */
}
/* Reject trailing slashes on non-directories. */
- len1 = strlen (file1);
- len2 = strlen (file2);
+ size_t len1 = strlen (file1);
+ size_t len2 = strlen (file2);
if ((len1 && file1[len1 - 1] == '/')
|| (len2 && file2[len2 - 1] == '/'))
{
{
/* Fix Cygwin 1.5.x bug where link("a","b/.") creates file "b". */
char *dir = strdup (file2);
- char *p;
if (!dir)
return -1;
/* We already know file2 does not end in slash. Strip off the
basename, then check that the dirname exists. */
- p = strrchr (dir, '/');
+ char *p = strrchr (dir, '/');
if (p)
{
*p = '\0';
an identical symlink behaves like a hard link to a symlink,
except for incorrect st_ino and st_nlink. However, we must
be careful of EXDEV. */
- struct stat st1;
- struct stat st2;
char *dir = mdir_name (file2);
if (!dir)
{
errno = ENOMEM;
return -1;
}
+ struct stat st1;
+ struct stat st2;
if (lstat (file1, &st1) == 0 && stat (dir, &st2) == 0)
{
if (st1.st_dev == st2.st_dev)
{
char *name = (char *) file1;
char *target;
- int result;
int i = __eloop_threshold ();
/* Using realpath or canonicalize_file_name is too heavy-handed: we
free (name);
return -1;
}
- result = link (name, file2);
+ int result = link (name, file2);
if (name != file1)
free (name);
return result;
{
char *name = (char *) file1;
char *target;
- int result;
int i = __eloop_threshold ();
/* There is no realpathat. */
free (name);
return -1;
}
- result = linkat (fd1, name, fd2, file2, 0);
+ int result = linkat (fd1, name, fd2, file2, 0);
if (name != file1)
free (name);
return result;
environment variables (if present) or the codepage as a number. */
if (codeset != NULL && streq (codeset, "US-ASCII"))
{
- const char *locale;
static char resultbuf[2 + 10 + 1];
- locale = getenv ("LC_ALL");
+ const char *locale = getenv ("LC_ALL");
if (locale == NULL || locale[0] == '\0')
{
locale = getenv ("LC_CTYPE");
# elif defined OS2
- const char *locale;
static char resultbuf[2 + 10 + 1];
- ULONG cp[3];
- ULONG cplen;
codeset = NULL;
/* Allow user to override the codeset, as set in the operating system,
with standard language environment variables. */
- locale = getenv ("LC_ALL");
+ const char *locale = getenv ("LC_ALL");
if (locale == NULL || locale[0] == '\0')
{
locale = getenv ("LC_CTYPE");
if (codeset == NULL)
{
+ ULONG cp[3];
+ ULONG cplen;
+
/* OS/2 has a function returning the locale's codepage as a number. */
if (DosQueryCp (sizeof (cp), cp, &cplen))
codeset = "";
static bool
is_using_utf8 (void)
{
+ mbstate_t state; mbszero (&state);
char32_t wc;
- mbstate_t mbs; mbszero (&mbs);
- return mbrtoc32 (&wc, "\xc4\x80", 2, &mbs) == 2 && wc == 0x100;
+ return mbrtoc32 (&wc, "\xc4\x80", 2, &state) == 2 && wc == 0x100;
}
/* Return true if the locale is compatible enough with the C locale so
{
char c = i;
unsigned char uc = i;
- mbstate_t s; mbszero (&s);
+ mbstate_t state; mbszero (&state);
char32_t wc;
- size_t len = mbrtoc32 (&wc, &c, 1, &s);
+ size_t len = mbrtoc32 (&wc, &c, 1, &state);
localeinfo->sbclen[uc] = len <= 1 ? 1 : - (int) - len;
localeinfo->sbctowc[uc] = len <= 1 ? wc : WEOF;
}
const char *
gl_locale_name_environ (_GL_UNUSED int category, const char *categoryname)
{
- const char *retval;
-
/* Setting of LC_ALL overrides all other. */
- retval = getenv ("LC_ALL");
- if (retval != NULL && retval[0] != '\0')
- return retval;
+ {
+ const char *retval = getenv ("LC_ALL");
+ if (retval != NULL && retval[0] != '\0')
+ return retval;
+ }
/* Next comes the name of the desired category. */
- retval = getenv (categoryname);
- if (retval != NULL && retval[0] != '\0')
- return retval;
+ {
+ const char *retval = getenv (categoryname);
+ if (retval != NULL && retval[0] != '\0')
+ return retval;
+ }
/* Last possibility is the LANG environment variable. */
- retval = getenv ("LANG");
- if (retval != NULL && retval[0] != '\0')
- {
+ {
+ const char *retval = getenv ("LANG");
+ if (retval != NULL && retval[0] != '\0')
+ {
#if HAVE_CFPREFERENCESCOPYAPPVALUE
- /* Mac OS X 10.2 or newer.
- Ignore invalid LANG value set by the Terminal application. */
- if (!streq (retval, "UTF-8"))
+ /* Mac OS X 10.2 or newer.
+ Ignore invalid LANG value set by the Terminal application. */
+ if (!streq (retval, "UTF-8"))
#endif
#if defined __CYGWIN__
- /* Cygwin.
- Ignore dummy LANG value set by ~/.profile. */
- if (!streq (retval, "C.UTF-8"))
+ /* Cygwin.
+ Ignore dummy LANG value set by ~/.profile. */
+ if (!streq (retval, "C.UTF-8"))
#endif
- return retval;
- }
+ return retval;
+ }
+ }
return NULL;
}
/* Step 2: Convert using langtag_table and script_table. */
if (strlen (name) == 7 && name[2] == '-')
{
- unsigned int i1, i2;
- i1 = 0;
- i2 = sizeof (langtag_table) / sizeof (langtag_entry);
- while (i2 - i1 > 1)
- {
- /* At this point we know that if name occurs in langtag_table,
- its index must be >= i1 and < i2. */
- unsigned int i = (i1 + i2) >> 1;
- const langtag_entry *p = &langtag_table[i];
- if (strcmp (name, p->langtag) < 0)
- i2 = i;
- else
- i1 = i;
- }
- if (streq (name, langtag_table[i1].langtag))
- {
- strcpy (name, langtag_table[i1].unixy);
- return;
- }
+ {
+ unsigned int i1, i2;
+ i1 = 0;
+ i2 = sizeof (langtag_table) / sizeof (langtag_entry);
+ while (i2 - i1 > 1)
+ {
+ /* At this point we know that if name occurs in langtag_table,
+ its index must be >= i1 and < i2. */
+ unsigned int i = (i1 + i2) >> 1;
+ const langtag_entry *p = &langtag_table[i];
+ if (strcmp (name, p->langtag) < 0)
+ i2 = i;
+ else
+ i1 = i;
+ }
+ if (streq (name, langtag_table[i1].langtag))
+ {
+ strcpy (name, langtag_table[i1].unixy);
+ return;
+ }
+ }
- i1 = 0;
- i2 = sizeof (script_table) / sizeof (script_entry);
- while (i2 - i1 > 1)
- {
- /* At this point we know that if (name + 3) occurs in script_table,
- its index must be >= i1 and < i2. */
- unsigned int i = (i1 + i2) >> 1;
- const script_entry *p = &script_table[i];
- if (strcmp (name + 3, p->script) < 0)
- i2 = i;
- else
- i1 = i;
- }
- if (streq (name + 3, script_table[i1].script))
- {
- name[2] = '@';
- strcpy (name + 3, script_table[i1].unixy);
- return;
- }
+ {
+ unsigned int i1, i2;
+ i1 = 0;
+ i2 = sizeof (script_table) / sizeof (script_entry);
+ while (i2 - i1 > 1)
+ {
+ /* At this point we know that if (name + 3) occurs in script_table,
+ its index must be >= i1 and < i2. */
+ unsigned int i = (i1 + i2) >> 1;
+ const script_entry *p = &script_table[i];
+ if (strcmp (name + 3, p->script) < 0)
+ i2 = i;
+ else
+ i1 = i;
+ }
+ if (streq (name + 3, script_table[i1].script))
+ {
+ name[2] = '@';
+ strcpy (name + 3, script_table[i1].unixy);
+ return;
+ }
+ }
}
/* Step 3: Convert new-style dash to Unix underscore. */
#define N(name) (is_utf8 ? name ".UTF-8" : name)
#define NM(name,modifier) (is_utf8 ? name ".UTF-8" modifier : name modifier)
{
- int primary, sub;
-
/* Split into language and territory part. */
- primary = PRIMARYLANGID (langid);
- sub = SUBLANGID (langid);
+ int primary = PRIMARYLANGID (langid);
+ int sub = SUBLANGID (langid);
/* Dispatch on language.
See also https://www.unicode.org/unicode/onlinedat/languages.html .
const char *
gl_locale_name_from_win32_LCID (LCID lcid)
{
- LANGID langid;
-
/* Strip off the sorting rules, keep only the language part. */
- langid = LANGIDFROMLCID (lcid);
+ LANGID langid = LANGIDFROMLCID (lcid);
return gl_locale_name_from_win32_LANGID (langid);
}
enum_locales_fn (LPSTR locale_num_str)
{
char *endp;
- char locval[2 * LOCALE_NAME_MAX_LENGTH + 1 + 1];
LCID try_lcid = strtoul (locale_num_str, &endp, 16);
+ char locval[2 * LOCALE_NAME_MAX_LENGTH + 1 + 1];
if (GetLocaleInfo (try_lcid, LOCALE_SENGLANGUAGE,
- locval, LOCALE_NAME_MAX_LENGTH))
+ locval, LOCALE_NAME_MAX_LENGTH))
{
strcat (locval, "_");
if (GetLocaleInfo (try_lcid, LOCALE_SENGCOUNTRY,
const char *
gl_locale_name_unsafe (int category, const char *categoryname)
{
- const char *retval;
-
if (category == LC_ALL)
/* Invalid argument. */
abort ();
- retval = gl_locale_name_thread_unsafe (category, categoryname);
- if (retval != NULL)
- return retval;
+ {
+ const char *retval = gl_locale_name_thread_unsafe (category, categoryname);
+ if (retval != NULL)
+ return retval;
+ }
- retval = gl_locale_name_posix_unsafe (category, categoryname);
- if (retval != NULL)
- return retval;
+ {
+ const char *retval = gl_locale_name_posix_unsafe (category, categoryname);
+ if (retval != NULL)
+ return retval;
+ }
return gl_locale_name_default ();
}
const char *
gl_locale_name (int category, const char *categoryname)
{
- const char *retval;
-
if (category == LC_ALL)
/* Invalid argument. */
abort ();
- retval = gl_locale_name_thread (category, categoryname);
- if (retval != NULL)
- return retval;
-
- retval = gl_locale_name_posix (category, categoryname);
- if (retval != NULL)
- return retval;
+ {
+ const char *retval = gl_locale_name_thread (category, categoryname);
+ if (retval != NULL)
+ return retval;
+ }
+
+ {
+ const char *retval = gl_locale_name_posix (category, categoryname);
+ if (retval != NULL)
+ return retval;
+ }
return gl_locale_name_default ();
}
Then log2(x) = e + log2(y) = e + log(y)/log(2). */
{
int e;
- double y;
-
- y = frexp (x, &e);
+ double y = frexp (x, &e);
if (y < SQRT_HALF)
{
y = 2.0 * y;
Then log2(x) = e + log2(y) = e + log(y)/log(2). */
{
int e;
- float y;
-
- y = frexpf (x, &e);
+ float y = frexpf (x, &e);
if (y < SQRT_HALF)
{
y = 2.0f * y;
Then log2(x) = e + log2(y) = e + log(y)/log(2). */
{
int e;
- long double y;
-
- y = frexpl (x, &e);
+ long double y = frexpl (x, &e);
if (y < SQRT_HALF)
{
y = 2.0L * y;
return -1;
#else
{
- char *slave_name;
- int dummy_fd;
-
- slave_name = ttyname (slave_fd);
+ char *slave_name = ttyname (slave_fd);
if (slave_name == NULL)
return -1;
- dummy_fd = open (slave_name, O_RDWR | O_CLOEXEC);
+ int dummy_fd = open (slave_name, O_RDWR | O_CLOEXEC);
if (dummy_fd < 0)
return -1;
close (dummy_fd);
long double
logl (long double x)
{
- long double z, y, w;
- long double t;
- int k, e;
-
/* Check for IEEE special cases. */
/* log(NaN) = NaN. */
}
/* Extract exponent and reduce domain to 0.703125 <= u < 1.40625 */
+ int e;
x = frexpl (x, &e);
if (x < 0.703125L)
{
}
/* On this interval the table is not used due to cancellation error. */
+ long double z;
+ int k;
+ long double t;
if ((x <= 1.0078125L) && (x >= 0.9921875L))
{
z = x - 1.0L;
}
/* Series expansion of log(1+z). */
- w = z * z;
- y = ((((((((((((l15 * z
- + l14) * z
- + l13) * z
- + l12) * z
- + l11) * z
- + l10) * z
- + l9) * z
- + l8) * z
- + l7) * z
- + l6) * z
- + l5) * z
- + l4) * z
- + l3) * z * w;
+ long double w = z * z;
+ long double y = ((((((((((((l15 * z
+ + l14) * z
+ + l13) * z
+ + l12) * z
+ + l11) * z
+ + l10) * z
+ + l9) * z
+ + l8) * z
+ + l7) * z
+ + l6) * z
+ + l5) * z
+ + l4) * z
+ + l3) * z * w;
y -= 0.5 * w;
y += e * ln2b; /* Base 2 exponent offset times ln(2). */
y += z;
void (*usage_func) (int),
/* const char *author1, ...*/ ...)
{
- int c;
- int saved_opterr;
-
- saved_opterr = opterr;
+ int saved_opterr = opterr;
/* Don't print an error message for unrecognized options. */
opterr = 0;
- if (argc == 2
- && (c = getopt_long (argc, argv, "+", long_options, NULL)) != -1)
+ if (argc == 2)
{
- switch (c)
+ int c = getopt_long (argc, argv, "+", long_options, NULL);
+ if (c != -1)
{
- case 'h':
- (*usage_func) (EXIT_SUCCESS);
- break;
-
- case 'v':
- {
- va_list authors;
- va_start (authors, usage_func);
- version_etc_va (stdout, command_name, package, version, authors);
- exit (EXIT_SUCCESS);
- }
-
- default:
- /* Don't process any other long-named options. */
- break;
+ switch (c)
+ {
+ case 'h':
+ (*usage_func) (EXIT_SUCCESS);
+ break;
+
+ case 'v':
+ {
+ va_list authors;
+ va_start (authors, usage_func);
+ version_etc_va (stdout, command_name, package, version, authors);
+ exit (EXIT_SUCCESS);
+ }
+
+ default:
+ /* Don't process any other long-named options. */
+ break;
+ }
}
}
void (*usage_func) (int),
/* const char *author1, ...*/ ...)
{
- int c;
int saved_opterr = opterr;
/* Print an error message for unrecognized options. */
const char *optstring = scan_all ? "" : "+";
- if ((c = getopt_long (argc, argv, optstring, long_options, NULL)) != -1)
+ int c = getopt_long (argc, argv, optstring, long_options, NULL);
+ if (c != -1)
{
switch (c)
{
MBFILE_INLINE void
mbfile_multi_getc (struct mbchar *mbc, struct mbfile_multi *mbf)
{
- unsigned int new_bufcount;
- size_t bytes;
-
/* Return character pushed back, if there is one. */
if (mbf->pushback_count > 0)
{
if (mbf->eof_seen)
goto eof;
- new_bufcount = mbf->bufcount;
+ unsigned int new_bufcount = mbf->bufcount;
/* If mbf->state is not in an initial state, some more 32-bit wide character
may be hiding in the state. We need to call mbrtoc32 again. */
/* Use mbrtoc32 on an increasing number of bytes. Read only as many bytes
from mbf->fp as needed. This is needed to give reasonable interactive
behaviour when mbf->fp is connected to an interactive tty. */
+ size_t bytes;
for (;;)
{
/* Feed the bytes one by one into mbrtoc32. */
char *outbuf, size_t outbufsize)
{
char *outbuf_orig = outbuf;
- size_t remaining;
-
- remaining = inbufsize;
+ size_t remaining = inbufsize;
while (remaining > 0)
{
mbstate_t state;
-
mbszero (&state);
+
for (;;)
{
char32_t wc1;
- size_t n1;
-
- n1 = mbrtoc32 (&wc1, inbuf, remaining, &state);
+ size_t n1 = mbrtoc32 (&wc1, inbuf, remaining, &state);
if (n1 == (size_t)(-1))
{
}
else
{
- wint_t wc2;
-
if (n1 == 0) /* NUL character? */
n1 = 1;
#if !GNULIB_MBRTOC32_REGULAR
n1 = 0;
#endif
- wc2 = c32tolower (wc1);
+ wint_t wc2 = c32tolower (wc1);
if (wc2 != wc1)
{
mbstate_t state2;
- size_t n2;
-
mbszero (&state2);
- n2 = c32rtomb (outbuf, wc2, &state2);
+
+ size_t n2 = c32rtomb (outbuf, wc2, &state2);
if (n2 != (size_t)(-1))
{
/* Store the translated multibyte character. */
size_t t1len;
char *t2;
size_t t2len;
- char *memory;
- int cmp;
if (MB_CUR_MAX > 1)
{
t2len = s2len;
}
/* Allocate memory for t1 and t2. */
- memory = (char *) malloca (t1len + 1 + t2len + 1);
+ char *memory = (char *) malloca (t1len + 1 + t2len + 1);
if (memory == NULL)
{
errno = ENOMEM;
}
/* Compare the two case-folded strings. */
+ int cmp;
if (hard_LC_COLLATE)
cmp = memcoll (t1, t1len, t2, t2len);
else
char buf[4];
const char *p;
size_t m;
- int res;
switch (nstate)
{
/* Here m > 0. */
+ int res;
{
# define FITS_IN_CHAR_TYPE(wc) 1
# include "mbrtowc-impl-utf8.h"
char buf[4];
const char *p;
size_t m;
- enc_t enc;
- int res;
switch (nstate)
{
/* Here m > 0. */
- enc = locale_encoding_classification ();
+ enc_t enc = locale_encoding_classification ();
+ int res;
if (enc == enc_utf8) /* UTF-8 */
{
{
/* The hidden internal state of mbtowc would make this function not
multi-thread safe. Achieve multi-thread safety through a lock. */
- wchar_t wc;
- res = mbtowc_with_lock (&wc, p, m);
+ {
+ wchar_t wc;
+ res = mbtowc_with_lock (&wc, p, m);
- if (res >= 0)
- {
- if ((wc == 0) != (res == 0))
- abort ();
- if (pwc != NULL)
- *pwc = wc;
- goto success;
- }
+ if (res >= 0)
+ {
+ if ((wc == 0) != (res == 0))
+ abort ();
+ if (pwc != NULL)
+ *pwc = wc;
+ goto success;
+ }
+ }
/* mbtowc does not distinguish between invalid and incomplete multibyte
sequences. But mbrtowc needs to make this distinction.
size_t
rpl_mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps)
{
- size_t ret;
- wchar_t wc;
-
# if MBRTOWC_RETVAL_BUG || MBRTOWC_EMPTY_INPUT_BUG
if (s == NULL)
{
return (size_t) -2;
# endif
+ wchar_t wc;
if (! pwc)
pwc = &wc;
size_t count = 0;
for (; n > 0; s++, n--)
{
- ret = mbrtowc (&wc, s, 1, ps);
+ size_t ret = mbrtowc (&wc, s, 1, ps);
if (ret == (size_t)(-1))
return (size_t)(-1);
}
# endif
+ size_t ret;
# if MBRTOWC_STORES_INCOMPLETE_BUG
ret = mbrtowc (&wc, s, n, ps);
if (ret < (size_t) -2 && pwc != NULL)
/* Allocate room for needle_mbchars and the table. */
void *memory = nmalloca (m + !!extra_align,
sizeof (mbchar_t) + sizeof (size_t));
- void *table_memory;
if (memory == NULL)
return false;
needle_mbchars = memory;
- table_memory = needle_mbchars + m;
+ void *table_memory = needle_mbchars + m;
char *aligned = table_memory;
aligned += extra_align;
aligned -= (uintptr_t) aligned % alignof (size_t);
#else
{
mbui_iterator_t iter;
- size_t j;
-
- j = 0;
+ size_t j = 0;
for (mbui_init (iter, needle); mbui_avail (iter); mbui_advance (iter), j++)
{
mb_copy (&needle_mbchars[j], &mbui_cur (iter));
/* Search, using the table to accelerate the processing. */
{
#if GNULIB_MCEL_PREFER
- size_t j;
char const *rhaystack = haystack;
char const *phaystack = haystack;
- j = 0;
+ size_t j = 0;
/* Invariant: phaystack = rhaystack + j. */
for (;;)
{
}
*resultp = rhaystack;
#else
- size_t j;
- mbui_iterator_t rhaystack;
- mbui_iterator_t phaystack;
-
*resultp = NULL;
- j = 0;
+ size_t j = 0;
+ mbui_iterator_t rhaystack;
mbui_init (rhaystack, haystack);
+ mbui_iterator_t phaystack;
mbui_init (phaystack, haystack);
/* Invariant: phaystack = rhaystack + j. */
while (mbui_avail (phaystack))
{
mbchar_t c;
-
mb_copy (&c, &mbui_cur (phaystack));
if (c.wc_valid)
c.wc = c32tolower (c.wc);
return NULL;
#else
mbui_iterator_t iter_needle;
-
mbui_init (iter_needle, needle);
if (mbui_avail (iter_needle))
{
size_t last_ccount = 0; /* last comparison count */
mbui_iterator_t iter_needle_last_ccount; /* = needle + last_ccount */
- mbchar_t b;
- mbui_iterator_t iter_haystack;
-
mbui_init (iter_needle_last_ccount, needle);
+ mbchar_t b;
mb_copy (&b, &mbui_cur (iter_needle));
if (b.wc_valid)
b.wc = c32tolower (b.wc);
+ mbui_iterator_t iter_haystack;
mbui_init (iter_haystack, haystack);
for (;; mbui_advance (iter_haystack))
{
- mbchar_t c;
-
if (!mbui_avail (iter_haystack))
/* No match. */
return NULL;
outer_loop_count++;
comparison_count++;
+ mbchar_t c;
mb_copy (&c, &mbui_cur (iter_haystack));
if (c.wc_valid)
c.wc = c32tolower (c.wc);
/* The first character matches. */
{
mbui_iterator_t rhaystack;
- mbui_iterator_t rneedle;
-
memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
mbui_advance (rhaystack);
+ mbui_iterator_t rneedle;
mbui_init (rneedle, needle);
if (!mbui_avail (rneedle))
abort ();
if (MB_CUR_MAX > 1)
{
#if GNULIB_MCEL_PREFER
- mcel_t a, g;
size_t i;
- for (i = 0; string[i]; i += g.len)
+ for (i = 0; string[i]; )
{
- g = mcel_scanz (string + i);
+ mcel_t g = mcel_scanz (string + i);
if (g.len == 1)
{
if (mbschr (accept, string[i]))
return i;
}
else
- for (char const *aiter = accept; *aiter; aiter += a.len)
+ for (char const *aiter = accept; *aiter; )
{
- a = mcel_scanz (aiter);
+ mcel_t a = mcel_scanz (aiter);
if (mcel_eq (g, a))
return i;
+ aiter += a.len;
}
+ i += g.len;
}
return i;
#else
for (; srclen > 0 && len > 0; destptr++, len--)
{
size_t src_avail;
- size_t ret;
/* An optimized variant of
src_avail = strnlen1 (src, MIN (srclen, MB_LEN_MAX)); */
src_avail = 4 + strnlen1 (src + 4, MIN (srclen, MB_LEN_MAX) - 4);
/* Parse the next multibyte character. */
- ret = MBRTOWC (destptr, src, src_avail, ps);
+ size_t ret = MBRTOWC (destptr, src, src_avail, ps);
if (ret == (size_t)(-2))
/* Encountered a multibyte character that extends past a '\0' byte
for (; srclen > 0; totalcount++)
{
size_t src_avail;
- size_t ret;
/* An optimized variant of
src_avail = strnlen1 (src, MIN (srclen, MB_LEN_MAX)); */
src_avail = 4 + strnlen1 (src + 4, MIN (srclen, MB_LEN_MAX) - 4);
/* Parse the next multibyte character. */
- ret = MBRTOWC (NULL, src, src_avail, &state);
+ size_t ret = MBRTOWC (NULL, src, src_avail, &state);
if (ret == (size_t)(-2))
/* Encountered a multibyte character that extends past a '\0' byte
{
char const *iter = string;
#if GNULIB_MCEL_PREFER
- mcel_t a, g;
- for (; *iter; iter += g.len)
+ for (; *iter; )
{
- g = mcel_scanz (iter);
+ mcel_t g = mcel_scanz (iter);
if (g.len == 1)
{
if (mbschr (accept, *iter))
return (char *) iter;
}
else
- for (char const *aiter = accept; *aiter; aiter += a.len)
+ for (char const *aiter = accept; *aiter; )
{
- a = mcel_scanz (aiter);
+ mcel_t a = mcel_scanz (aiter);
if (mcel_eq (a, g))
return (char *) iter;
+ aiter += a.len;
}
+ iter += g.len;
}
#else
mbuif_state_t state;
for (; len > 0; destptr++, len--)
{
size_t src_avail;
- size_t ret;
/* An optimized variant of
src_avail = strnlen1 (src, MB_LEN_MAX); */
src_avail = 4 + strnlen1 (src + 4, MB_LEN_MAX - 4);
/* Parse the next multibyte character. */
- ret = MBRTOWC (destptr, src, src_avail, ps);
+ size_t ret = MBRTOWC (destptr, src, src_avail, ps);
if (ret == (size_t)(-2))
/* Encountered a multibyte character that extends past a '\0' byte
for (;; totalcount++)
{
size_t src_avail;
- size_t ret;
/* An optimized variant of
src_avail = strnlen1 (src, MB_LEN_MAX); */
src_avail = 4 + strnlen1 (src + 4, MB_LEN_MAX - 4);
/* Parse the next multibyte character. */
- ret = MBRTOWC (NULL, src, src_avail, &state);
+ size_t ret = MBRTOWC (NULL, src, src_avail, &state);
if (ret == (size_t)(-2))
/* Encountered a multibyte character that extends past a '\0' byte
if (MB_CUR_MAX > 1)
{
#if GNULIB_MCEL_PREFER
- for (mcel_t g; *iter; iter += g.len)
+ for (; *iter; )
{
- g = mcel_scanz (iter);
+ mcel_t g = mcel_scanz (iter);
if (! (g.len == 1 && (unsigned char) *iter == uc))
break;
+ iter += g.len;
}
#else
mbuif_state_t state;
/* Allocate room for needle_mbchars and the table. */
void *memory = nmalloca (m + !!extra_align,
sizeof (mbchar_t) + sizeof (size_t));
- void *table_memory;
if (memory == NULL)
return false;
needle_mbchars = memory;
- table_memory = needle_mbchars + m;
+ void *table_memory = needle_mbchars + m;
char *aligned = table_memory;
aligned += extra_align;
aligned -= (uintptr_t) aligned % alignof (size_t);
#else
{
mbui_iterator_t iter;
- size_t j;
-
- j = 0;
+ size_t j = 0;
for (mbui_init (iter, needle); mbui_avail (iter); mbui_advance (iter), j++)
mb_copy (&needle_mbchars[j], &mbui_cur (iter));
}
/* Search, using the table to accelerate the processing. */
{
#if GNULIB_MCEL_PREFER
- size_t j;
char const *rhaystack = haystack;
char const *phaystack = haystack;
- j = 0;
+ size_t j = 0;
/* Invariant: phaystack = rhaystack + j. */
for (;;)
{
}
*resultp = rhaystack;
#else
- size_t j;
- mbui_iterator_t rhaystack;
- mbui_iterator_t phaystack;
-
*resultp = NULL;
- j = 0;
+ size_t j = 0;
+ mbui_iterator_t rhaystack;
mbui_init (rhaystack, haystack);
+ mbui_iterator_t phaystack;
mbui_init (phaystack, haystack);
/* Invariant: phaystack = rhaystack + j. */
while (mbui_avail (phaystack))
char const *iter_haystack = haystack;
- for (mcel_t hg; *iter_haystack; iter_haystack += hg.len)
+ for (; *iter_haystack; )
{
/* See whether it's advisable to use an asymptotically faster
algorithm. */
outer_loop_count++;
comparison_count++;
- hg = mcel_scanz (iter_haystack);
+ mcel_t hg = mcel_scanz (iter_haystack);
if (mcel_eq (hg, ng))
/* The first character matches. */
{
}
while (mcel_eq (rhg, rng));
}
+
+ iter_haystack += hg.len;
}
return NULL;
#else
mbui_iterator_t iter_needle;
-
mbui_init (iter_needle, needle);
if (mbui_avail (iter_needle))
{
size_t outer_loop_count = 0;
size_t comparison_count = 0;
size_t last_ccount = 0; /* last comparison count */
+
mbui_iterator_t iter_needle_last_ccount; /* = needle + last_ccount */
+ mbui_init (iter_needle_last_ccount, needle);
mbui_iterator_t iter_haystack;
-
- mbui_init (iter_needle_last_ccount, needle);
mbui_init (iter_haystack, haystack);
for (;; mbui_advance (iter_haystack))
{
/* The first character matches. */
{
mbui_iterator_t rhaystack;
- mbui_iterator_t rneedle;
-
memcpy (&rhaystack, &iter_haystack, sizeof (mbui_iterator_t));
mbui_advance (rhaystack);
+ mbui_iterator_t rneedle;
mbui_init (rneedle, needle);
if (!mbui_avail (rneedle))
abort ();
mbstoc32s (char32_t *dest, const char *src, size_t len)
{
mbstate_t state;
-
mbszero (&state);
return mbsrtoc32s (dest, &src, len, &state);
}
mbstowcs (wchar_t *dest, const char *src, size_t len)
{
mbstate_t state;
-
mbszero (&state);
return mbsrtowcs (dest, &src, len, &state);
}
{
const char *p = string;
const char *plimit = p + nbytes;
- int width;
-
- width = 0;
+ int width = 0;
if (MB_CUR_MAX > 1)
{
while (p < plimit)
for (;;)
{
char32_t wc;
- size_t bytes;
- int w;
-
- bytes = mbrtoc32 (&wc, p, plimit - p, &mbstate);
+ size_t bytes = mbrtoc32 (&wc, p, plimit - p, &mbstate);
if (bytes == (size_t) -1)
/* An invalid multibyte sequence was encountered. */
bytes = 0;
#endif
- w = c32width (wc);
+ int w = c32width (wc);
if (w >= 0)
/* A printable multibyte character. */
{
else
{
mbstate_t state;
- wchar_t wc;
- size_t result;
-
mbszero (&state);
- result = mbrtowc (&wc, s, n, &state);
+
+ wchar_t wc;
+ size_t result = mbrtowc (&wc, s, n, &state);
if (result == (size_t)-1 || result == (size_t)-2)
{
errno = EILSEQ;
mbtowc_with_lock (wchar_t *pwc, const char *p, size_t m)
{
CRITICAL_SECTION *lock = gl_get_mbtowc_lock ();
- int ret;
EnterCriticalSection (lock);
- ret = mbtowc_unlocked (pwc, p, m);
+ int ret = mbtowc_unlocked (pwc, p, m);
LeaveCriticalSection (lock);
return ret;
if (pthread_in_use())
{
pthread_mutex_t *lock = gl_get_mbtowc_lock ();
- int ret;
if (pthread_mutex_lock (lock))
abort ();
- ret = mbtowc_unlocked (pwc, p, m);
+ int ret = mbtowc_unlocked (pwc, p, m);
if (pthread_mutex_unlock (lock))
abort ();
mbtowc_with_lock (wchar_t *pwc, const char *p, size_t m)
{
mtx_t *lock = gl_get_mbtowc_lock ();
- int ret;
if (mtx_lock (lock) != thrd_success)
abort ();
- ret = mbtowc_unlocked (pwc, p, m);
+ int ret = mbtowc_unlocked (pwc, p, m);
if (mtx_unlock (lock) != thrd_success)
abort ();
You can use this multi-byte code:
char *p = ..., *lim = ...;
- for (mcel_t g; p < lim; p += g.len)
+ for (; p < lim; )
{
- g = mcel_scan (p, lim);
+ mcel_t g = mcel_scan (p, lim);
process (g);
+ p += g.len;
}
You can select from G using G.ch, G.err, and G.len.
You can use this multi-byte code:
char *p = ...;
- for (mcel_t g; *p; p += g.len)
+ for (; *p; )
{
- g = mcel_scanz (p);
+ mcel_t g = mcel_scanz (p);
process (g);
+ p += g.len;
}
mcel_scant (P, TERMINATOR) is like mcel_scanz (P) except the
int
md2_stream (FILE *stream, void *resblock)
{
- struct md2_ctx ctx;
- size_t sum;
-
char *buffer = malloc (BLOCKSIZE + 72);
if (!buffer)
return 1;
/* Initialize the computation context. */
+ struct md2_ctx ctx;
md2_init_ctx (&ctx);
/* Iterate over full file contents. */
+ size_t sum;
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
{
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
void *
md2_finish_ctx (struct md2_ctx *ctx, void *resbuf)
{
- unsigned long k;
-
/* pad the message */
- k = 16 - ctx->curlen;
+ unsigned long k = 16 - ctx->curlen;
for (unsigned long i = ctx->curlen; i < 16; i++)
{
ctx->buf[i] = (unsigned char) k;
md2_process_bytes (const void *buffer, size_t len, struct md2_ctx *ctx)
{
const char *in = buffer;
- unsigned long n;
while (len > 0)
{
- n = MIN (len, (16 - ctx->curlen));
+ unsigned long n = MIN (len, (16 - ctx->curlen));
memcpy (ctx->buf + ctx->curlen, in, (size_t) n);
ctx->curlen += n;
in += n;
static void
md2_update_chksum (struct md2_ctx *ctx)
{
- unsigned char L;
-
- L = ctx->chksum[15];
+ unsigned char L = ctx->chksum[15];
for (int j = 0; j < 16; j++)
{
/* caution, the RFC says its "C[j] = S[M[i*16+j] xor L]" but the
static void
md2_compress (struct md2_ctx *ctx)
{
- unsigned char t;
-
/* copy block */
for (size_t j = 0; j < 16; j++)
{
ctx->X[32 + j] = ctx->X[j] ^ ctx->X[16 + j];
}
- t = (unsigned char) 0;
+ unsigned char t = (unsigned char) 0;
/* do 18 rounds */
for (size_t j = 0; j < 18; j++)
int
md4_stream (FILE * stream, void *resblock)
{
- struct md4_ctx ctx;
- size_t sum;
-
char *buffer = malloc (BLOCKSIZE + 72);
if (!buffer)
return 1;
/* Initialize the computation context. */
+ struct md4_ctx ctx;
md4_init_ctx (&ctx);
/* Iterate over full file contents. */
+ size_t sum;
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
{
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
{
/* Take yet unprocessed bytes into account. */
uint32_t bytes = ctx->buflen;
- size_t pad;
/* Now count remaining bytes. */
ctx->total[0] += bytes;
if (ctx->total[0] < bytes)
++ctx->total[1];
- pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
+ size_t pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
memcpy (&((char*)ctx->buffer)[bytes], fillbuf, pad);
/* Put the 64-bit file length in *bits* at the end of the buffer. */
const uint32_t *words = buffer;
size_t nwords = len / sizeof (uint32_t);
const uint32_t *endp = words + nwords;
- uint32_t x[16];
uint32_t A = ctx->A;
uint32_t B = ctx->B;
uint32_t C = ctx->C;
the loop. */
while (words < endp)
{
+ uint32_t x[16];
for (int t = 0; t < 16; t++)
{
x[t] = SWAP (*words);
struct md5_ctx ctx;
md5_init_ctx (&ctx);
- size_t sum;
/* Iterate over full file contents. */
+ size_t sum;
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
if (feof (stream))
goto process_partial_block;
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
static size_t
compute_hashval (const void *key, size_t keylen)
{
- size_t cnt;
- size_t hval;
-
/* Compute the hash value for the given string. The algorithm
is taken from [Aho,Sethi,Ullman], fixed according to
https://haible.de/bruno/hashfunc.html. */
- cnt = 0;
- hval = keylen;
+ size_t cnt = 0;
+ size_t hval = keylen;
while (cnt < keylen)
{
hval = (hval << 9) | (hval >> (sizeof (size_t) * CHAR_BIT - 9));
const void *key, size_t keylen,
size_t hval)
{
- size_t hash;
- size_t idx;
hash_entry *table = htab->table;
/* First hash function: simply take the modul but prevent zero. */
- hash = 1 + hval % htab->size;
+ size_t hash = 1 + hval % htab->size;
- idx = hash;
+ size_t idx = hash;
if (table[idx].used)
{
performance. */
typedef unsigned long int longword;
- const unsigned char *char_ptr;
- const longword *longword_ptr;
- longword repeated_one;
- longword repeated_c;
- unsigned reg_char c;
+ unsigned reg_char c = (unsigned char) c_in;
- c = (unsigned char) c_in;
+ const longword *longword_ptr;
/* Handle the first few bytes by reading one byte at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
- for (char_ptr = (const unsigned char *) s;
- n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
- --n, ++char_ptr)
- if (*char_ptr == c)
- return (void *) char_ptr;
+ {
+ const unsigned char *char_ptr;
+ for (char_ptr = (const unsigned char *) s;
+ n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
+ --n, ++char_ptr)
+ if (*char_ptr == c)
+ return (void *) char_ptr;
- longword_ptr = (const longword *) char_ptr;
+ longword_ptr = (const longword *) char_ptr;
+ }
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
-
- /* Compute auxiliary longword values:
- repeated_one is a value which has a 1 in every byte.
- repeated_c has c in every byte. */
- repeated_one = 0x01010101;
- repeated_c = c | (c << 8);
- repeated_c |= repeated_c << 16;
- if (0xffffffffU < (longword) -1)
- {
- repeated_one |= repeated_one << 31 << 1;
- repeated_c |= repeated_c << 31 << 1;
- if (8 < sizeof (longword))
- for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
- {
- repeated_one |= repeated_one << i;
- repeated_c |= repeated_c << i;
- }
- }
-
- /* Instead of the traditional loop which tests each byte, we will test a
- longword at a time. The tricky part is testing if *any of the four*
- bytes in the longword in question are equal to c. We first use an xor
- with repeated_c. This reduces the task to testing whether *any of the
- four* bytes in longword1 is zero.
-
- We compute tmp =
- ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
- That is, we perform the following operations:
- 1. Subtract repeated_one.
- 2. & ~longword1.
- 3. & a mask consisting of 0x80 in every byte.
- Consider what happens in each byte:
- - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
- and step 3 transforms it into 0x80. A carry can also be propagated
- to more significant bytes.
- - If a byte of longword1 is nonzero, let its lowest 1 bit be at
- position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
- the byte ends in a single bit of value 0 and k bits of value 1.
- After step 2, the result is just k bits of value 1: 2^k - 1. After
- step 3, the result is 0. And no carry is produced.
- So, if longword1 has only non-zero bytes, tmp is zero.
- Whereas if longword1 has a zero byte, call j the position of the least
- significant zero byte. Then the result has a zero at positions 0, ...,
- j-1 and a 0x80 at position j. We cannot predict the result at the more
- significant bytes (positions j+1..3), but it does not matter since we
- already have a non-zero bit at position 8*j+7.
-
- So, the test whether any byte in longword1 is zero is equivalent to
- testing whether tmp is nonzero. */
-
- while (n >= sizeof (longword))
- {
- longword longword1 = *longword_ptr ^ repeated_c;
-
- if ((((longword1 - repeated_one) & ~longword1)
- & (repeated_one << 7)) != 0)
- break;
- longword_ptr++;
- n -= sizeof (longword);
- }
-
- char_ptr = (const unsigned char *) longword_ptr;
-
- /* At this point, we know that either n < sizeof (longword), or one of the
- sizeof (longword) bytes starting at char_ptr is == c. On little-endian
- machines, we could determine the first such byte without any further
- memory accesses, just by looking at the tmp result from the last loop
- iteration. But this does not work on big-endian machines. Choose code
- that works in both cases. */
-
- for (; n > 0; --n, ++char_ptr)
- {
- if (*char_ptr == c)
- return (void *) char_ptr;
- }
+ {
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ longword repeated_one = 0x01010101;
+ longword repeated_c = c | (c << 8);
+ repeated_c |= repeated_c << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c |= repeated_c << 31 << 1;
+ if (8 < sizeof (longword))
+ for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c |= repeated_c << i;
+ }
+ }
+
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c. We first use an xor
+ with repeated_c. This reduces the task to testing whether *any of the
+ four* bytes in longword1 is zero.
+
+ We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ So, the test whether any byte in longword1 is zero is equivalent to
+ testing whether tmp is nonzero. */
+
+ while (n >= sizeof (longword))
+ {
+ longword longword1 = *longword_ptr ^ repeated_c;
+
+ if ((((longword1 - repeated_one) & ~longword1)
+ & (repeated_one << 7)) != 0)
+ break;
+ longword_ptr++;
+ n -= sizeof (longword);
+ }
+ }
+
+ {
+ const unsigned char *char_ptr = (const unsigned char *) longword_ptr;
+
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c. On little-endian
+ machines, we could determine the first such byte without any further
+ memory accesses, just by looking at the tmp result from the last loop
+ iteration. But this does not work on big-endian machines. Choose code
+ that works in both cases. */
+
+ for (; n > 0; --n, ++char_ptr)
+ {
+ if (*char_ptr == c)
+ return (void *) char_ptr;
+ }
+ }
return NULL;
}
performance. */
typedef unsigned long int longword;
- const unsigned char *char_ptr;
- void const *void_ptr;
- const longword *longword_ptr;
- longword repeated_one;
- longword repeated_c1;
- longword repeated_c2;
- unsigned char c1;
- unsigned char c2;
-
- c1 = (unsigned char) c1_in;
- c2 = (unsigned char) c2_in;
+ unsigned char c1 = (unsigned char) c1_in;
+ unsigned char c2 = (unsigned char) c2_in;
if (c1 == c2)
return (void *) memchr (s, c1, n);
/* Handle the first few bytes by reading one byte at a time.
Do this until VOID_PTR is aligned on a longword boundary. */
+ void const *void_ptr;
for (void_ptr = s;
n > 0 && (uintptr_t) void_ptr % sizeof (longword) != 0;
--n)
{
- char_ptr = void_ptr;
+ const unsigned char *char_ptr = void_ptr;
if (*char_ptr == c1 || *char_ptr == c2)
return (void *) void_ptr;
void_ptr = char_ptr + 1;
}
- longword_ptr = void_ptr;
+ const longword *longword_ptr = void_ptr;
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
-
- /* Compute auxiliary longword values:
- repeated_one is a value which has a 1 in every byte.
- repeated_c1 has c1 in every byte.
- repeated_c2 has c2 in every byte. */
- repeated_one = 0x01010101;
- repeated_c1 = c1 | (c1 << 8);
- repeated_c2 = c2 | (c2 << 8);
- repeated_c1 |= repeated_c1 << 16;
- repeated_c2 |= repeated_c2 << 16;
- if (0xffffffffU < (longword) -1)
- {
- repeated_one |= repeated_one << 31 << 1;
- repeated_c1 |= repeated_c1 << 31 << 1;
- repeated_c2 |= repeated_c2 << 31 << 1;
- if (8 < sizeof (longword))
- for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
- {
- repeated_one |= repeated_one << i;
- repeated_c1 |= repeated_c1 << i;
- repeated_c2 |= repeated_c2 << i;
- }
- }
-
- /* Instead of the traditional loop which tests each byte, we will test a
- longword at a time. The tricky part is testing if *any of the four*
- bytes in the longword in question are equal to c1 or c2. We first use
- an xor with repeated_c1 and repeated_c2, respectively. This reduces
- the task to testing whether *any of the four* bytes in longword1 or
- longword2 is zero.
-
- Let's consider longword1. We compute tmp1 =
- ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
- That is, we perform the following operations:
- 1. Subtract repeated_one.
- 2. & ~longword1.
- 3. & a mask consisting of 0x80 in every byte.
- Consider what happens in each byte:
- - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
- and step 3 transforms it into 0x80. A carry can also be propagated
- to more significant bytes.
- - If a byte of longword1 is nonzero, let its lowest 1 bit be at
- position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
- the byte ends in a single bit of value 0 and k bits of value 1.
- After step 2, the result is just k bits of value 1: 2^k - 1. After
- step 3, the result is 0. And no carry is produced.
- So, if longword1 has only non-zero bytes, tmp1 is zero.
- Whereas if longword1 has a zero byte, call j the position of the least
- significant zero byte. Then the result has a zero at positions 0, ...,
- j-1 and a 0x80 at position j. We cannot predict the result at the more
- significant bytes (positions j+1..3), but it does not matter since we
- already have a non-zero bit at position 8*j+7.
-
- Similarly, we compute tmp2 =
- ((longword2 - repeated_one) & ~longword2) & (repeated_one << 7).
-
- The test whether any byte in longword1 or longword2 is zero is equivalent
- to testing whether tmp1 is nonzero or tmp2 is nonzero. We can combine
- this into a single test, whether (tmp1 | tmp2) is nonzero. */
-
- while (n >= sizeof (longword))
- {
- longword longword1 = *longword_ptr ^ repeated_c1;
- longword longword2 = *longword_ptr ^ repeated_c2;
-
- if (((((longword1 - repeated_one) & ~longword1)
- | ((longword2 - repeated_one) & ~longword2))
- & (repeated_one << 7)) != 0)
- break;
- longword_ptr++;
- n -= sizeof (longword);
- }
-
- char_ptr = (const unsigned char *) longword_ptr;
-
- /* At this point, we know that either n < sizeof (longword), or one of the
- sizeof (longword) bytes starting at char_ptr is == c1 or == c2. On
- little-endian machines, we could determine the first such byte without
- any further memory accesses, just by looking at the (tmp1 | tmp2) result
- from the last loop iteration. But this does not work on big-endian
- machines. Choose code that works in both cases. */
-
- for (; n > 0; --n, ++char_ptr)
- {
- if (*char_ptr == c1 || *char_ptr == c2)
- return (void *) char_ptr;
- }
+ {
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c1 has c1 in every byte.
+ repeated_c2 has c2 in every byte. */
+ longword repeated_one = 0x01010101;
+ longword repeated_c1 = c1 | (c1 << 8);
+ longword repeated_c2 = c2 | (c2 << 8);
+ repeated_c1 |= repeated_c1 << 16;
+ repeated_c2 |= repeated_c2 << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c1 |= repeated_c1 << 31 << 1;
+ repeated_c2 |= repeated_c2 << 31 << 1;
+ if (8 < sizeof (longword))
+ for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c1 |= repeated_c1 << i;
+ repeated_c2 |= repeated_c2 << i;
+ }
+ }
+
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c1 or c2. We first use
+ an xor with repeated_c1 and repeated_c2, respectively. This reduces
+ the task to testing whether *any of the four* bytes in longword1 or
+ longword2 is zero.
+
+ Let's consider longword1. We compute tmp1 =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp1 is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ Similarly, we compute tmp2 =
+ ((longword2 - repeated_one) & ~longword2) & (repeated_one << 7).
+
+ The test whether any byte in longword1 or longword2 is zero is equivalent
+ to testing whether tmp1 is nonzero or tmp2 is nonzero. We can combine
+ this into a single test, whether (tmp1 | tmp2) is nonzero. */
+
+ while (n >= sizeof (longword))
+ {
+ longword longword1 = *longword_ptr ^ repeated_c1;
+ longword longword2 = *longword_ptr ^ repeated_c2;
+
+ if (((((longword1 - repeated_one) & ~longword1)
+ | ((longword2 - repeated_one) & ~longword2))
+ & (repeated_one << 7)) != 0)
+ break;
+ longword_ptr++;
+ n -= sizeof (longword);
+ }
+ }
+
+ {
+ const unsigned char *char_ptr = (const unsigned char *) longword_ptr;
+
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c1 or == c2. On
+ little-endian machines, we could determine the first such byte without
+ any further memory accesses, just by looking at the (tmp1 | tmp2) result
+ from the last loop iteration. But this does not work on big-endian
+ machines. Choose code that works in both cases. */
+
+ for (; n > 0; --n, ++char_ptr)
+ {
+ if (*char_ptr == c1 || *char_ptr == c2)
+ return (void *) char_ptr;
+ }
+ }
return NULL;
}
performance. */
typedef unsigned long int longword;
- const unsigned char *char_ptr;
- const longword *longword_ptr;
- longword repeated_one;
- longword repeated_c;
- unsigned reg_char c;
+ unsigned reg_char c = (unsigned char) c_in;
- c = (unsigned char) c_in;
+ const longword *longword_ptr;
/* Handle the last few bytes by reading one byte at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
- for (char_ptr = (const unsigned char *) s + n;
- n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
- --n)
- if (*--char_ptr == c)
- return (void *) char_ptr;
+ {
+ const unsigned char *char_ptr;
+ for (char_ptr = (const unsigned char *) s + n;
+ n > 0 && (size_t) char_ptr % sizeof (longword) != 0;
+ --n)
+ if (*--char_ptr == c)
+ return (void *) char_ptr;
- longword_ptr = (const void *) char_ptr;
+ longword_ptr = (const void *) char_ptr;
+ }
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
-
- /* Compute auxiliary longword values:
- repeated_one is a value which has a 1 in every byte.
- repeated_c has c in every byte. */
- repeated_one = 0x01010101;
- repeated_c = c | (c << 8);
- repeated_c |= repeated_c << 16;
- if (0xffffffffU < (longword) -1)
- {
- repeated_one |= repeated_one << 31 << 1;
- repeated_c |= repeated_c << 31 << 1;
- if (8 < sizeof (longword))
- for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
- {
- repeated_one |= repeated_one << i;
- repeated_c |= repeated_c << i;
- }
- }
-
- /* Instead of the traditional loop which tests each byte, we will test a
- longword at a time. The tricky part is testing if *any of the four*
- bytes in the longword in question are equal to c. We first use an xor
- with repeated_c. This reduces the task to testing whether *any of the
- four* bytes in longword1 is zero.
-
- We compute tmp =
- ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
- That is, we perform the following operations:
- 1. Subtract repeated_one.
- 2. & ~longword1.
- 3. & a mask consisting of 0x80 in every byte.
- Consider what happens in each byte:
- - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
- and step 3 transforms it into 0x80. A carry can also be propagated
- to more significant bytes.
- - If a byte of longword1 is nonzero, let its lowest 1 bit be at
- position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
- the byte ends in a single bit of value 0 and k bits of value 1.
- After step 2, the result is just k bits of value 1: 2^k - 1. After
- step 3, the result is 0. And no carry is produced.
- So, if longword1 has only non-zero bytes, tmp is zero.
- Whereas if longword1 has a zero byte, call j the position of the least
- significant zero byte. Then the result has a zero at positions 0, ...,
- j-1 and a 0x80 at position j. We cannot predict the result at the more
- significant bytes (positions j+1..3), but it does not matter since we
- already have a non-zero bit at position 8*j+7.
+ {
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ longword repeated_one = 0x01010101;
+ longword repeated_c = c | (c << 8);
+ repeated_c |= repeated_c << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c |= repeated_c << 31 << 1;
+ if (8 < sizeof (longword))
+ for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c |= repeated_c << i;
+ }
+ }
+
+ /* Instead of the traditional loop which tests each byte, we will test a
+ longword at a time. The tricky part is testing if *any of the four*
+ bytes in the longword in question are equal to c. We first use an xor
+ with repeated_c. This reduces the task to testing whether *any of the
+ four* bytes in longword1 is zero.
+
+ We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
So, the test whether any byte in longword1 is zero is equivalent to
testing whether tmp is nonzero. */
- while (n >= sizeof (longword))
- {
- longword longword1 = *--longword_ptr ^ repeated_c;
-
- if ((((longword1 - repeated_one) & ~longword1)
- & (repeated_one << 7)) != 0)
- {
- longword_ptr++;
- break;
- }
- n -= sizeof (longword);
- }
-
- char_ptr = (const unsigned char *) longword_ptr;
-
- /* At this point, we know that either n < sizeof (longword), or one of the
- sizeof (longword) bytes starting at char_ptr is == c. On little-endian
- machines, we could determine the first such byte without any further
- memory accesses, just by looking at the tmp result from the last loop
- iteration. But this does not work on big-endian machines. Choose code
- that works in both cases. */
-
- while (n-- > 0)
- {
- if (*--char_ptr == c)
- return (void *) char_ptr;
- }
+ while (n >= sizeof (longword))
+ {
+ longword longword1 = *--longword_ptr ^ repeated_c;
+
+ if ((((longword1 - repeated_one) & ~longword1)
+ & (repeated_one << 7)) != 0)
+ {
+ longword_ptr++;
+ break;
+ }
+ n -= sizeof (longword);
+ }
+ }
+
+ {
+ const unsigned char *char_ptr = (const unsigned char *) longword_ptr;
+
+ /* At this point, we know that either n < sizeof (longword), or one of the
+ sizeof (longword) bytes starting at char_ptr is == c. On little-endian
+ machines, we could determine the first such byte without any further
+ memory accesses, just by looking at the tmp result from the last loop
+ iteration. But this does not work on big-endian machines. Choose code
+ that works in both cases. */
+ while (n-- > 0)
+ {
+ if (*--char_ptr == c)
+ return (void *) char_ptr;
+ }
+ }
return NULL;
}
int
mgetgroups (char const *username, gid_t gid, gid_t **groups)
{
- int max_n_groups;
- int ng;
- gid_t *g;
-
#if HAVE_GETGROUPLIST
/* We prefer to use getgrouplist if available, because it has better
performance characteristics.
if (username)
{
enum { N_GROUPS_INIT = 10 };
- max_n_groups = N_GROUPS_INIT;
+ int max_n_groups = N_GROUPS_INIT;
- g = realloc_groupbuf (NULL, max_n_groups);
+ gid_t *g = realloc_groupbuf (NULL, max_n_groups);
if (g == NULL)
return -1;
while (1)
{
- gid_t *h;
int last_n_groups = max_n_groups;
/* getgrouplist updates max_n_groups to num required. */
- ng = getgrouplist (username, gid, g, &max_n_groups);
+ int ng = getgrouplist (username, gid, g, &max_n_groups);
/* Some systems (like Darwin) have a bug where they
never increase max_n_groups. */
if (ng < 0 && last_n_groups == max_n_groups)
max_n_groups *= 2;
- if ((h = realloc_groupbuf (g, max_n_groups)) == NULL)
+ gid_t *h = realloc_groupbuf (g, max_n_groups);
+ if (h == NULL)
{
free (g);
return -1;
/* else no username, so fall through and use getgroups. */
#endif
- max_n_groups = (username
- ? getugroups (0, NULL, username, gid)
- : getgroups (0, NULL));
+ int max_n_groups = (username
+ ? getugroups (0, NULL, username, gid)
+ : getgroups (0, NULL));
/* If we failed to count groups because there is no supplemental
group support, then return an array containing just GID.
Otherwise, we fail for the same reason. */
if (max_n_groups < 0)
{
- if (errno == ENOSYS && (g = realloc_groupbuf (NULL, 1)))
+ if (errno == ENOSYS)
{
- *groups = g;
- *g = gid;
- return gid != (gid_t) -1;
+ gid_t *g = realloc_groupbuf (NULL, 1);
+ if (g)
+ {
+ *groups = g;
+ *g = gid;
+ return gid != (gid_t) -1;
+ }
}
return -1;
}
if (max_n_groups == 0 || (!username && gid != (gid_t) -1))
max_n_groups++;
- g = realloc_groupbuf (NULL, max_n_groups);
+ gid_t *g = realloc_groupbuf (NULL, max_n_groups);
if (g == NULL)
return -1;
- ng = (username
- ? getugroups (max_n_groups, g, username, gid)
- : getgroups (max_n_groups - (gid != (gid_t) -1),
- g + (gid != (gid_t) -1)));
+ int ng = (username
+ ? getugroups (max_n_groups, g, username, gid)
+ : getgroups (max_n_groups - (gid != (gid_t) -1),
+ g + (gid != (gid_t) -1)));
if (ng < 0)
{
affect the algorithm. */
if (! (sep - component == 1 && component[0] == '.'))
{
- int make_dir_errno = 0;
- int savewd_chdir_options = 0;
- int chdir_result;
-
/* Temporarily modify FILE to isolate this file name
component. */
*sep = '\0';
/* Invoke MAKE_DIR on this component, except don't bother
with ".." since it must exist if its "parent" does. */
+ int make_dir_errno = 0;
if (sep - component == 2
&& component[0] == '.' && component[1] == '.')
made_dir = false;
else
made_dir = true;
+ int savewd_chdir_options = 0;
if (made_dir)
savewd_chdir_options |= SAVEWD_CHDIR_NOFOLLOW;
- chdir_result =
+ int chdir_result =
savewd_chdir (wd, component, savewd_chdir_options, NULL);
/* Undo the temporary modification to FILE, unless there
if (mkdir_errno == 0)
{
- ptrdiff_t prefix_len = 0;
int savewd_chdir_options = (HAVE_FCHMOD ? SAVEWD_CHDIR_SKIP_READABLE : 0);
+ ptrdiff_t prefix_len = 0;
if (make_ancestor)
{
prefix_len = mkancesdirs (dir, wd, make_ancestor, options);
int
rpl_mkdir (char const *dir, maybe_unused mode_t mode)
{
- int ret_val;
- char *tmp_dir;
size_t len = strlen (dir);
+ char *tmp_dir;
if (len && dir[len - 1] == '/')
{
tmp_dir = strdup (dir);
{
tmp_dir = (char *) dir;
}
+
#if FUNC_MKDIR_DOT_BUG
/* Additionally, cygwin 1.5 mistakenly creates a directory "d/./". */
{
}
#endif /* FUNC_MKDIR_DOT_BUG */
- ret_val = mkdir (tmp_dir, mode);
+ int ret_val = mkdir (tmp_dir, mode);
if (tmp_dir != dir)
free (tmp_dir);
struct mode_change *
mode_compile (char const *mode_string)
{
- /* The array of mode-change directives to be returned. */
- struct mode_change *mc;
- size_t used = 0;
-
if ('0' <= *mode_string && *mode_string < '8')
{
char const *p;
return make_node_op_equals (mode, mentioned);
}
+ /* The array of mode-change directives to be returned. */
+ struct mode_change *mc;
+
/* Allocate enough space to hold the result. */
{
size_t needed = 1;
/* One loop iteration for each
'[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'. */
+ size_t used = 0;
char const *p;
for (p = mode_string; ; p++)
{
mode_t value;
mode_t mentioned = 0;
char flag = MODE_COPY_EXISTING;
- struct mode_change *change;
switch (*p)
{
no_more_values:;
}
+ struct mode_change *change;
change = &mc[used++];
change->op = op;
change->flag = flag;
static char *
fstype_to_string (int t)
{
- struct vfs_ent *e;
-
- e = getvfsbytype (t);
+ struct vfs_ent *e = getvfsbytype (t);
if (!e || !e->vfsent_name)
return "none";
else
char const *optval = devopt + sizeof dev_pattern - 1;
if (c_isxdigit (*optval))
{
- char *optvalend;
- unsigned long int dev;
errno = 0;
- dev = strtoul (optval, &optvalend, 16);
+ char *optvalend;
+ unsigned long int dev = strtoul (optval, &optvalend, 16);
if (optval != optvalend
&& (*optvalend == '\0' || *optvalend == ',')
&& ! (dev == ULONG_MAX && errno == ERANGE)
#ifdef MOUNTED_GETMNTENT1 /* glibc, HP-UX, Cygwin, Android,
also (obsolete) 4.3BSD, SunOS */
{
- FILE *fp;
-
# if defined __linux__ || defined __ANDROID__
/* Try parsing mountinfo first, as that make device IDs available.
Note we could use libmount routines to simplify this parsing a little
(and that code is in previous versions of this function), however
libmount depends on libselinux which pulls in many dependencies. */
char const *mountinfo = "/proc/self/mountinfo";
- fp = fopen (mountinfo, "re");
+ FILE *fp = fopen (mountinfo, "re");
if (fp != NULL)
{
char *line = NULL;
else /* fallback to /proc/self/mounts (/etc/mtab). */
# endif /* __linux__ || __ANDROID__ */
{
- struct mntent *mnt;
char const *table = MOUNTED;
- fp = setmntent (table, "r");
- if (fp == NULL)
+ FILE *mfp = setmntent (table, "r");
+ if (mfp == NULL)
return NULL;
- while ((mnt = getmntent (fp)))
+ struct mntent *mnt;
+ while ((mnt = getmntent (mfp)))
{
bool bind = hasmntopt (mnt, "bind");
mtail = &me->me_next;
}
- if (endmntent (fp) == 0)
+ if (endmntent (mfp) == 0)
goto free_then_fail;
}
}
#ifdef MOUNTED_GETMNTINFO /* Mac OS X, FreeBSD, OpenBSD, also (obsolete) 4.4BSD */
{
struct statfs *fsp;
- int entries;
-
- entries = getmntinfo (&fsp, MNT_NOWAIT);
+ int entries = getmntinfo (&fsp, MNT_NOWAIT);
if (entries < 0)
return NULL;
for (; entries-- > 0; fsp++)
#ifdef MOUNTED_GETMNTINFO2 /* NetBSD, Minix */
{
struct statvfs *fsp;
- int entries;
-
- entries = getmntinfo (&fsp, MNT_NOWAIT);
+ int entries = getmntinfo (&fsp, MNT_NOWAIT);
if (entries < 0)
return NULL;
for (; entries-- > 0; fsp++)
We therefore get the list of subdirectories of /, and the list
of all file systems, and match the two lists. */
- DIR *dirp;
struct rootdir_entry
{
char *name;
ino_t ino;
struct rootdir_entry *next;
};
- struct rootdir_entry *rootdir_list;
- struct rootdir_entry **rootdir_tail;
- int32 pos;
- dev_t dev;
- fs_info fi;
/* All volumes are mounted in the rootfs, directly under /. */
- rootdir_list = NULL;
- rootdir_tail = &rootdir_list;
- dirp = opendir ("/");
+ struct rootdir_entry *rootdir_list = NULL;
+ struct rootdir_entry **rootdir_tail = &rootdir_list;
+ DIR *dirp = opendir ("/");
if (dirp)
{
struct dirent *d;
}
*rootdir_tail = NULL;
- for (pos = 0; (dev = next_dev (&pos)) >= 0; )
- if (fs_stat_dev (dev, &fi) >= 0)
- {
- /* Note: fi.dev == dev. */
- for (struct rootdir_entry *re = rootdir_list; re; re = re->next)
- if (re->dev == fi.dev && re->ino == fi.root)
- break;
-
- me = xmalloc (sizeof *me);
- me->me_devname = xstrdup (fi.device_name[0] != '\0'
- ? fi.device_name : fi.fsh_name);
- me->me_mountdir = xstrdup (re != NULL ? re->name : fi.fsh_name);
- me->me_mntroot = NULL;
- me->me_type = xstrdup (fi.fsh_name);
- me->me_type_malloced = 1;
- me->me_dev = fi.dev;
- me->me_dummy = 0;
- me->me_remote = (fi.flags & B_FS_IS_SHARED) != 0;
-
- /* Add to the linked list. */
- *mtail = me;
- mtail = &me->me_next;
- }
+ dev_t dev;
+ for (int32 pos = 0; (dev = next_dev (&pos)) >= 0; )
+ {
+ fs_info fi;
+ if (fs_stat_dev (dev, &fi) >= 0)
+ {
+ /* Note: fi.dev == dev. */
+ for (struct rootdir_entry *re = rootdir_list; re; re = re->next)
+ if (re->dev == fi.dev && re->ino == fi.root)
+ break;
+
+ me = xmalloc (sizeof *me);
+ me->me_devname = xstrdup (fi.device_name[0] != '\0'
+ ? fi.device_name : fi.fsh_name);
+ me->me_mountdir = xstrdup (re != NULL ? re->name : fi.fsh_name);
+ me->me_mntroot = NULL;
+ me->me_type = xstrdup (fi.fsh_name);
+ me->me_type_malloced = 1;
+ me->me_dev = fi.dev;
+ me->me_dummy = 0;
+ me->me_remote = (fi.flags & B_FS_IS_SHARED) != 0;
+
+ /* Add to the linked list. */
+ *mtail = me;
+ mtail = &me->me_next;
+ }
+ }
*mtail = NULL;
while (rootdir_list != NULL)
#if defined MOUNTED_GETFSSTAT /* (obsolete) Apple Darwin 1.3 */
{
- int numsys;
- size_t bufsize;
- struct statfs *stats;
- numsys = getfsstat (NULL, 0L, MNT_NOWAIT);
+ int numsys = getfsstat (NULL, 0L, MNT_NOWAIT);
if (numsys < 0)
return NULL;
+
+ struct statfs *stats;
if (SIZE_MAX / sizeof *stats <= numsys)
xalloc_die ();
-
- bufsize = (1 + numsys) * sizeof *stats;
+ size_t bufsize = (1 + numsys) * sizeof *stats;
stats = xmalloc (bufsize);
numsys = getfsstat (stats, bufsize, MNT_NOWAIT);
#if defined MOUNTED_FREAD_FSTYP /* (obsolete) SVR3 */
{
- struct mnttab mnt;
char *table = "/etc/mnttab";
- FILE *fp;
- fp = fopen (table, "re");
+ FILE *fp = fopen (table, "re");
if (fp == NULL)
return NULL;
+ struct mnttab mnt;
while (fread (&mnt, sizeof mnt, 1, fp) > 0)
{
me = xmalloc (sizeof *me);
#ifdef MOUNTED_GETEXTMNTENT /* Solaris >= 8 */
{
- struct extmnttab mnt;
const char *table = MNTTAB;
- FILE *fp;
- int ret;
/* No locking is needed, because the contents of /etc/mnttab is generated
by the kernel. */
errno = 0;
- fp = fopen (table, "re");
+ FILE *fp = fopen (table, "re");
+ int ret;
if (fp == NULL)
ret = errno;
else
{
+ struct extmnttab mnt;
while ((ret = getextmntent (fp, &mnt, 1)) == 0)
{
me = xmalloc (sizeof *me);
#ifdef MOUNTED_GETMNTENT2 /* Solaris < 8, also (obsolete) SVR4 */
{
- struct mnttab mnt;
const char *table = MNTTAB;
- FILE *fp;
- int ret;
int lockfd = -1;
# if defined F_RDLCK && defined F_SETLKW
# endif
errno = 0;
- fp = fopen (table, "re");
+ FILE *fp = fopen (table, "re");
+ int ret;
if (fp == NULL)
ret = errno;
else
{
+ struct mnttab mnt;
while ((ret = getmntent (fp, &mnt)) == 0)
{
me = xmalloc (sizeof *me);
#ifdef MOUNTED_VMOUNT /* AIX */
{
- int bufsize;
- void *entries;
- char *thisent;
- struct vmount *vmp;
- int n_entries;
- int i;
-
/* Ask how many bytes to allocate for the mounted file system info. */
- entries = &bufsize;
- if (mntctl (MCTL_QUERY, sizeof bufsize, entries) != 0)
+ int bufsize;
+ if (mntctl (MCTL_QUERY, sizeof bufsize, &bufsize) != 0)
return NULL;
- entries = xmalloc (bufsize);
+ void *entries = xmalloc (bufsize);
/* Get the list of mounted file systems. */
- n_entries = mntctl (MCTL_QUERY, bufsize, entries);
+ int n_entries = mntctl (MCTL_QUERY, bufsize, entries);
if (n_entries < 0)
{
free (entries);
return NULL;
}
- for (i = 0, thisent = entries;
- i < n_entries;
- i++, thisent += vmp->vmt_length)
+ char *thisent = entries;
+ for (int i = 0; i < n_entries; i++)
{
- char *options, *ignore;
-
- vmp = (struct vmount *) thisent;
+ struct vmount *vmp = (struct vmount *) thisent;
me = xmalloc (sizeof *me);
if (vmp->vmt_flags & MNT_REMOTE)
{
me->me_mntroot = NULL;
me->me_type = xstrdup (fstype_to_string (vmp->vmt_gfstype));
me->me_type_malloced = 1;
- options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off;
- ignore = strstr (options, "ignore");
+ char *options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off;
+ char *ignore = strstr (options, "ignore");
me->me_dummy = (ignore
&& (ignore == options || ignore[-1] == ',')
&& (ignore[sizeof "ignore" - 1] == ','
/* Add to the linked list. */
*mtail = me;
mtail = &me->me_next;
+
+ thisent += vmp->vmt_length;
}
free (entries);
}
#ifdef MOUNTED_INTERIX_STATVFS /* Interix */
{
DIR *dirp = opendir ("/dev/fs");
- char node[9 + NAME_MAX];
-
if (!dirp)
goto free_then_fail;
while (1)
{
- struct statvfs dev;
- struct dirent entry;
- struct dirent *result;
-
/* FIXME: readdir_r is planned to be withdrawn from POSIX and
marked obsolescent in glibc. Use readdir instead. */
+ struct dirent entry;
+ struct dirent *result;
if (readdir_r (dirp, &entry, &result) || result == NULL)
break;
+ char node[9 + NAME_MAX];
strcpy (node, "/dev/fs/");
strcat (node, entry.d_name);
+ struct statvfs dev;
if (statvfs (node, &dev) == 0)
{
me = xmalloc (sizeof *me);
if (value & (1U << i))
{
char mountdir[4];
- char fs_name[MAX_PATH + 1];
mountdir[0] = 'A' + i;
mountdir[1] = ':';
mountdir[2] = '\\';
mountdir[3] = '\0';
+
+ char fs_name[MAX_PATH + 1];
/* Test whether the drive actually exists, and
get the name of the file system. See:
<https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumeinformationa>. */
For testing of SUBST: <https://ss64.com/nt/subst.html>
For testing of NET USE: <https://ss64.com/nt/net-use.html> */
wchar_t drive[3];
- wchar_t mapping[MAX_PATH + 1];
drive[0] = L'A' + i;
drive[1] = L':';
drive[2] = L'\0';
+ wchar_t mapping[MAX_PATH + 1];
DWORD mapping_len = QueryDosDeviceW (drive, mapping, sizeof (mapping) / sizeof (mapping[0]));
if (mapping_len > 4 && wcsncmp (mapping, L"\\??\\", 4) == 0)
{
size_t alim = n1;
size_t b = n1;
size_t blim = n;
- void const *ba;
- void const *bb;
mpsort_with_tmp (base + n1, n2, tmp, cmp);
mpsort_with_tmp (base, n1, tmp, cmp);
- ba = base[a];
- bb = base[b];
+ void const *ba = base[a];
+ void const *bb = base[b];
for (;;)
if (cmp (ba, bb) <= 0)
size_t tlim = n1;
size_t b = n1;
size_t blim = n;
- void const *bb;
- void const *tt;
mpsort_with_tmp (base + n1, n2, tmp, cmp);
else
mpsort_into_tmp (base, n1, tmp, cmp);
- tt = tmp[t];
- bb = base[b];
+ void const *tt = tmp[t];
+ void const *bb = base[b];
for (size_t i = 0; ; )
if (cmp (tt, bb) <= 0)
# define TRY_MSVC_INVAL \
do \
{ \
- struct gl_msvc_inval_per_thread *msvc_inval_current; \
gl_msvc_inval_ensure_handler (); \
- msvc_inval_current = gl_msvc_inval_current (); \
+ struct gl_msvc_inval_per_thread *msvc_inval_current = \
+ gl_msvc_inval_current (); \
/* First, initialize gl_msvc_inval_restart. */ \
if (setjmp (msvc_inval_current->restart) == 0) \
{ \
if ((type & mtx_recursive) != 0)
{
pthread_mutexattr_t attributes;
- int err;
-
- err = pthread_mutexattr_init (&attributes);
- if (err != 0)
- return thrd_error;
- err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
- if (err != 0)
- {
- pthread_mutexattr_destroy (&attributes);
+ {
+ int err = pthread_mutexattr_init (&attributes);
+ if (err != 0)
return thrd_error;
- }
- err = pthread_mutex_init (mutex, &attributes);
- if (err != 0)
- {
- pthread_mutexattr_destroy (&attributes);
+ }
+ {
+ int err = pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return thrd_error;
+ }
+ }
+ {
+ int err = pthread_mutex_init (mutex, &attributes);
+ if (err != 0)
+ {
+ pthread_mutexattr_destroy (&attributes);
+ return thrd_error;
+ }
+ }
+ {
+ int err = pthread_mutexattr_destroy (&attributes);
+ if (err != 0)
return thrd_error;
- }
- err = pthread_mutexattr_destroy (&attributes);
- if (err != 0)
- return thrd_error;
+ }
}
else
{
while (limit < seconds)
{
- int result;
intermediate.tv_sec = limit;
- result = nanosleep (&intermediate, remaining_delay);
+ int result = nanosleep (&intermediate, remaining_delay);
seconds -= limit;
if (result)
{
/* This function is only used on platforms which don't have uselocale().
Therefore we don't need to look at the per-thread locale first, here. */
static char result[2 + 10 + 1];
- char buf[2 + 10 + 1];
- char locale[SETLOCALE_NULL_MAX];
- char *codeset;
- size_t codesetlen;
+ char locale[SETLOCALE_NULL_MAX];
if (setlocale_null_r (LC_CTYPE, locale, sizeof (locale)))
locale[0] = '\0';
- codeset = buf;
+ char buf[2 + 10 + 1];
+ char *codeset = buf;
codeset[0] = '\0';
if (locale[0])
codeset = codeset_start;
else
{
- codesetlen = modifier - codeset_start;
+ size_t codesetlen = modifier - codeset_start;
if (codesetlen < sizeof buf)
{
codeset = memcpy (buf, codeset_start, codesetlen);
GetACP, which returns the locale's codepage as a number (although
this doesn't change according to what the 'setlocale' call specified).
Either way, prepend "CP" to make it a valid codeset name. */
- codesetlen = strlen (codeset);
+ size_t codesetlen = strlen (codeset);
if (0 < codesetlen && codesetlen < sizeof buf - 2)
memmove (buf + 2, codeset, codesetlen + 1);
else
nl_langinfo_with_lock (nl_item item)
{
CRITICAL_SECTION *lock = gl_get_nl_langinfo_lock ();
- char *ret;
EnterCriticalSection (lock);
- ret = nl_langinfo_unlocked (item);
+ char *ret = nl_langinfo_unlocked (item);
LeaveCriticalSection (lock);
return ret;
if (pthread_in_use())
{
pthread_mutex_t *lock = gl_get_nl_langinfo_lock ();
- char *ret;
if (pthread_mutex_lock (lock))
abort ();
- ret = nl_langinfo_unlocked (item);
+ char *ret = nl_langinfo_unlocked (item);
if (pthread_mutex_unlock (lock))
abort ();
nl_langinfo_with_lock (nl_item item)
{
mtx_t *lock = gl_get_nl_langinfo_lock ();
- char *ret;
if (mtx_lock (lock) != thrd_success)
abort ();
- ret = nl_langinfo_unlocked (item);
+ char *ret = nl_langinfo_unlocked (item);
if (mtx_unlock (lock) != thrd_success)
abort ();
int
get_nonblocking_flag (int desc)
{
- int fcntl_flags;
-
- fcntl_flags = fcntl (desc, F_GETFL, 0);
+ int fcntl_flags = fcntl (desc, F_GETFL, 0);
if (fcntl_flags < 0)
return -1;
return (fcntl_flags & O_NONBLOCK) != 0;
int
set_nonblocking_flag (int desc, bool value)
{
- int fcntl_flags;
-
- fcntl_flags = fcntl (desc, F_GETFL, 0);
+ int fcntl_flags = fcntl (desc, F_GETFL, 0);
if (fcntl_flags < 0)
return -1;
if (((fcntl_flags & O_NONBLOCK) != 0) == value)
}
#elif HAVE_PTHREAD_GETAFFINITY_NP && defined __NetBSD__ && 0
{
- cpuset_t *set;
-
- set = cpuset_create ();
+ cpuset_t *set = cpuset_create ();
if (set != NULL)
{
unsigned long count = 0;
}
#elif HAVE_SCHED_GETAFFINITY_NP /* NetBSD >= 5 */
{
- cpuset_t *set;
-
- set = cpuset_create ();
+ cpuset_t *set = cpuset_create ();
if (set != NULL)
{
unsigned long count = 0;
static char *
cgroup2_mount (void)
{
- FILE *fp;
- char *ret = NULL;
/* Check the usual location first. */
if (access ("/sys/fs/cgroup/cgroup.controllers", F_OK) == 0)
return strdup ("/sys/fs/cgroup");
+ char *ret = NULL;
+
#if HAVE_SETMNTENT
/* Otherwise look for the mount point. */
- struct mntent *mnt;
- if (! (fp = setmntent ("/proc/mounts", "r")))
+ FILE *fp = setmntent ("/proc/mounts", "r");
+ if (! fp)
return NULL;
+ struct mntent *mnt;
while ((mnt = getmntent (fp)) != NULL)
{
if (streq (mnt->mnt_type, "cgroup2"))
get_cgroup2_cpu_quota (void)
{
unsigned long int cpu_quota = ULONG_MAX;
- FILE *fp;
- fp = fopen ("/proc/self/cgroup", "r");
+ FILE *fp = fopen ("/proc/self/cgroup", "r");
if (! fp)
return cpu_quota;
static unsigned long int
parse_omp_threads (char const* threads)
{
- unsigned long int ret = 0;
-
if (threads == NULL)
- return ret;
+ return 0;
/* The OpenMP spec says that the value assigned to the environment variables
"may have leading and trailing white space". */
return value;
}
- return ret;
+ return 0;
}
unsigned long int
programs that are based on OpenMP. */
if (query == NPROC_CURRENT_OVERRIDABLE)
{
- unsigned long int omp_env_threads, omp_env_limit;
- omp_env_threads = parse_omp_threads (getenv ("OMP_NUM_THREADS"));
- omp_env_limit = parse_omp_threads (getenv ("OMP_THREAD_LIMIT"));
+ unsigned long int omp_env_threads =
+ parse_omp_threads (getenv ("OMP_NUM_THREADS"));
+
+ unsigned long int omp_env_limit =
+ parse_omp_threads (getenv ("OMP_THREAD_LIMIT"));
if (! omp_env_limit)
omp_env_limit = ULONG_MAX;
_obstack_newchunk (struct obstack *h, _OBSTACK_INDEX_T length)
{
struct _obstack_chunk *old_chunk = h->chunk;
- struct _obstack_chunk *new_chunk;
size_t obj_size = h->next_free - h->object_base;
- char *object_base;
/* Compute size for new chunk. */
_OBSTACK_CHUNK_SIZE_T s, new_size;
new_size = h->chunk_size;
/* Allocate and initialize the new chunk. */
- new_chunk = v ? NULL : call_chunkfun (h, new_size);
+ struct _obstack_chunk *new_chunk =
+ v ? NULL : call_chunkfun (h, new_size);
if (!new_chunk)
(*obstack_alloc_failed_handler)();
h->chunk = new_chunk;
h->alignment_mask);
/* Compute an aligned object_base in the new chunk */
- object_base =
+ char *object_base =
__PTR_ALIGN ((char *) new_chunk, new_chunk->contents, h->alignment_mask);
/* Move the existing object to the new chunk. */
int
_obstack_allocated_p (struct obstack *h, void *obj)
{
- struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
- struct _obstack_chunk *plp; /* point to previous chunk if any */
-
- lp = (h)->chunk;
+ struct _obstack_chunk *lp = /* below addr of any objects in this chunk */
+ h->chunk;
/* We use >= rather than > since the object cannot be exactly at
the beginning of the chunk but might be an empty object exactly
at the end of an adjacent chunk. */
while (lp != NULL && ((void *) lp >= obj || (void *) (lp)->limit < obj))
{
- plp = lp->prev;
+ struct _obstack_chunk *plp = lp->prev; /* point to previous chunk */
lp = plp;
}
return lp != NULL;
void
__obstack_free (struct obstack *h, void *obj)
{
- struct _obstack_chunk *lp; /* below addr of any objects in this chunk */
- struct _obstack_chunk *plp; /* point to previous chunk if any */
-
- lp = h->chunk;
+ struct _obstack_chunk *lp = /* below addr of any objects in this chunk */
+ h->chunk;
/* We use >= because there cannot be an object at the beginning of a chunk.
But there can be an empty object at that address
at the end of another chunk. */
while (lp != NULL && ((void *) lp >= obj || (void *) (lp)->limit < obj))
{
- plp = lp->prev;
+ struct _obstack_chunk *plp = lp->prev; /* point to previous chunk */
call_freefun (h, lp);
lp = plp;
/* If we switch chunks, we can't tell whether the new current
OBSTACK_PRINTF (struct obstack *obs, const char *format, ...)
{
va_list args;
- RESULT_TYPE result;
-
va_start (args, format);
- result = OBSTACK_VPRINTF (obs, format, args);
+ RESULT_TYPE result = OBSTACK_VPRINTF (obs, format, args);
va_end (args);
return result;
}
char buf[CUTOFF];
char *base = obstack_next_free (obs);
size_t len = obstack_room (obs);
- char *str;
if (len < CUTOFF)
{
base = buf;
len = CUTOFF;
}
- str = vasnprintf (base, &len, format, args);
+ char *str = vasnprintf (base, &len, format, args);
if (!str)
{
if (errno == ENOMEM)
static unsigned long int
parse_omp_threads (char const* threads)
{
- unsigned long int ret = 0;
-
if (threads == NULL)
- return ret;
+ return 0;
/* The OpenMP spec says that the value assigned to the environment variables
"may have leading and trailing white space". */
return value;
}
- return ret;
+ return 0;
}
#endif
char *
openat_proc_name (char buf[OPENAT_BUFFER_SIZE], int fd, char const *file)
{
- char *result = buf;
- int dirlen;
-
/* Make sure the caller gets ENOENT when appropriate. */
if (!*file)
{
return buf;
}
+ char *result = buf;
+ int dirlen;
+
#if !(defined __KLIBC__ || defined __MVS__)
/* Generic code for Linux, Solaris, and similar platforms. */
# define PROC_SELF_FD_FORMAT "/proc/self/fd/%d/"
int flags, char resolve, mode_t mode,
char **buf, idx_t bufsize)
{
- int dfd = *fd;
-
/* RESOLVED_CACHED cannot be implemented properly in user space,
so pretend nothing is cached. */
if (resolve & RESOLVE_CACHED)
long int maxlinks = resolve & RESOLVE_NO_SYMLINKS ? 0 : __eloop_threshold ();
+ int dfd = *fd;
+
/* Iterates through file name components, possibly expanded by
symlink contents. */
while (true)
openat2 (int dfd, char const *filename,
struct open_how const *how, size_t howsize)
{
- int r;
-
#ifdef SYS_openat2
- r = syscall (SYS_openat2, dfd, filename, how, howsize);
- if (! (r < 0 && errno == ENOSYS))
- return r;
+ {
+ int r = syscall (SYS_openat2, dfd, filename, how, howsize);
+ if (! (r < 0 && errno == ENOSYS))
+ return r;
+ }
/* Keep going, to support the dubious practice of compiling for an
older kernel. The openat2 syscall was introduced in Linux 5.6.
we can simply return the syscall result instead of continuing. */
#endif
+ int r;
+
/* Check for invalid arguments. Once the size test has succeeded,
*HOW's members are safe to access, so use & and | as there is
little point to using && or || when invalid arguments are rare.
char resolve = how->resolve;
mode_t mode = how->mode;
- int fd;
-
/* For speed use a single openat if it suffices. */
if (O_RESOLVE_BENEATH ? !(resolve & ~RESOLVE_BENEATH) : !resolve)
{
- fd = openat (dfd, filename,
- flags | (resolve ? O_RESOLVE_BENEATH : 0), mode);
+ int fd = openat (dfd, filename,
+ flags | (resolve ? O_RESOLVE_BENEATH : 0), mode);
/* Return FD now unless openat failed with an errno that might
be an O_RESOLVE_BENEATH failure. On platforms with
return fd;
}
- fd = dfd;
+ int fd = dfd;
char stackbuf[256];
char *buf = stackbuf;
#else
- char dir_name_mask[MAX_PATH + 1 + 1 + 1];
- int status;
- HANDLE current;
- WIN32_FIND_DATA entry;
- struct gl_directory *dirp;
-
if (dir_name[0] == '\0')
{
errno = ENOENT;
/* Make the dir_name absolute, so that we continue reading the same
directory if the current directory changed between this opendir()
call and a subsequent rewinddir() call. */
+ char dir_name_mask[MAX_PATH + 1 + 1 + 1];
if (!GetFullPathName (dir_name, MAX_PATH, dir_name_mask, NULL))
{
errno = EINVAL;
}
/* Start searching the directory. */
- status = -1;
- current = FindFirstFile (dir_name_mask, &entry);
+ int status = -1;
+ WIN32_FIND_DATA entry;
+ HANDLE current = FindFirstFile (dir_name_mask, &entry);
if (current == INVALID_HANDLE_VALUE)
{
switch (GetLastError ())
}
/* Allocate the result. */
- dirp =
+ struct gl_directory *dirp =
(struct gl_directory *)
malloc (offsetof (struct gl_directory, dir_name_mask[0])
+ strlen (dir_name_mask) + 1);
openpty (int *amaster, int *aslave, char *name,
struct termios const *termp, struct winsize const *winp)
{
- int master;
- char *slave_name;
- int slave;
-
/* This call uses the 'posix_openpt' module. */
- master = posix_openpt (O_RDWR | O_NOCTTY);
+ int master = posix_openpt (O_RDWR | O_NOCTTY);
if (master < 0)
return -1;
if (unlockpt (master))
goto fail;
- slave_name = ptsname (master);
+ char *slave_name = ptsname (master);
if (slave_name == NULL)
goto fail;
- slave = open (slave_name, O_RDWR | O_NOCTTY);
+ int slave = open (slave_name, O_RDWR | O_NOCTTY);
if (slave == -1)
goto fail;
const char **
prepare_spawn (const char * const *argv, char **mem_to_free)
{
- size_t argc;
- const char **new_argv;
-
/* Count number of arguments. */
+ size_t argc;
for (argc = 0; argv[argc] != NULL; argc++)
;
/* Allocate new argument vector. */
- new_argv = (const char **) malloc ((1 + argc + 1) * sizeof (const char *));
+ const char **new_argv =
+ (const char **) malloc ((1 + argc + 1) * sizeof (const char *));
if (new_argv == NULL)
return NULL;
static int libcx_spawn2_loaded = 0;
#endif
- int saved_stdin = STDIN_FILENO;
- int saved_stdout = STDOUT_FILENO;
- int saved_stderr = STDERR_FILENO;
- int ret = -1;
-
#if HAVE_LIBCX_SPAWN2_H
if (libcx_spawn2_loaded == -1)
{
/* Save standard file handles. */
/* 0 means no changes. This is a behavior of spawn2(). */
+ int saved_stdin = STDIN_FILENO;
if (new_stdin != 0)
saved_stdin = dup_safer_noinherit (STDIN_FILENO);
+ int saved_stdout = STDOUT_FILENO;
if (!(new_stdout == 0 || new_stdout == 1))
saved_stdout = dup_safer_noinherit (STDOUT_FILENO);
+ int saved_stderr = STDERR_FILENO;
if (!(new_stderr == 0 || new_stderr == 2))
saved_stderr = dup_safer_noinherit (STDERR_FILENO);
+ int ret = -1;
if ((saved_stdin == STDIN_FILENO || dup2 (new_stdin, STDIN_FILENO) >= 0)
&& (saved_stdout == STDOUT_FILENO
|| dup2 (new_stdout, STDOUT_FILENO) >= 0)
void *
pagealign_alloc (size_t size)
{
- void *ret;
- pagealign_impl_t impl;
-
- impl = pagealign_impl;
+ pagealign_impl_t impl = pagealign_impl;
if (impl == PA_IMPL_DEFAULT)
impl = get_default_impl ();
+ void *ret;
switch (impl)
{
case PA_IMPL_MALLOC:
void *
pagealign_xalloc (size_t size)
{
- void *ret;
-
- ret = pagealign_alloc (size);
+ void *ret = pagealign_alloc (size);
if (ret == NULL)
xalloc_die ();
return ret;
void
pagealign_free (void *aligned_ptr)
{
- pagealign_impl_t impl;
-
- impl = pagealign_impl;
+ pagealign_impl_t impl = pagealign_impl;
if (impl == PA_IMPL_DEFAULT)
impl = get_default_impl ();
parse_scaled_value (time_t base, cch_t ** ppz, cch_t * endp, int scale)
{
cch_t * pz = *ppz;
- time_t val;
if (base == BAD_TIME)
return base;
errno = 0;
- val = str_const_to_ul (pz, &pz, 10);
+ time_t val = str_const_to_ul (pz, &pz, 10);
if (errno != 0)
return BAD_TIME;
while (isspace ((unsigned char)*pz))
static time_t
parse_year_month_day (cch_t * pz, cch_t * ps)
{
- time_t res = 0;
-
- res = parse_scaled_value (0, &pz, ps, SEC_PER_YEAR);
+ time_t res = parse_scaled_value (0, &pz, ps, SEC_PER_YEAR);
pz++; /* over the first '-' */
ps = strchr (pz, '-');
static time_t
parse_yearmonthday (cch_t * in_pz)
{
- time_t res = 0;
- char buf[8];
- cch_t * pz;
-
if (strlen (in_pz) != 8)
{
errno = EINVAL;
return BAD_TIME;
}
+ char buf[8];
+
memcpy (buf, in_pz, 4);
buf[4] = NUL;
- pz = buf;
- res = parse_scaled_value (0, &pz, buf + 4, SEC_PER_YEAR);
+ cch_t *pz = buf;
+ time_t res = parse_scaled_value (0, &pz, buf + 4, SEC_PER_YEAR);
memcpy (buf, in_pz + 4, 2);
buf[2] = NUL;
parse_YMWD (cch_t * pz)
{
time_t res = 0;
- cch_t * ps = strchr (pz, 'Y');
- if (ps != NULL)
- {
- res = parse_scaled_value (0, &pz, ps, SEC_PER_YEAR);
- pz++;
- }
- ps = strchr (pz, 'M');
- if (ps != NULL)
- {
- res = parse_scaled_value (res, &pz, ps, SEC_PER_MONTH);
- pz++;
- }
-
- ps = strchr (pz, 'W');
- if (ps != NULL)
- {
- res = parse_scaled_value (res, &pz, ps, SEC_PER_WEEK);
- pz++;
- }
-
- ps = strchr (pz, 'D');
- if (ps != NULL)
- {
- res = parse_scaled_value (res, &pz, ps, SEC_PER_DAY);
- pz++;
- }
+ {
+ cch_t *ps = strchr (pz, 'Y');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (0, &pz, ps, SEC_PER_YEAR);
+ pz++;
+ }
+ }
+ {
+ cch_t *ps = strchr (pz, 'M');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (res, &pz, ps, SEC_PER_MONTH);
+ pz++;
+ }
+ }
+ {
+ cch_t *ps = strchr (pz, 'W');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (res, &pz, ps, SEC_PER_WEEK);
+ pz++;
+ }
+ }
+ {
+ cch_t *ps = strchr (pz, 'D');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (res, &pz, ps, SEC_PER_DAY);
+ pz++;
+ }
+ }
while (isspace ((unsigned char)*pz))
pz++;
static time_t
parse_hour_minute_second (cch_t * pz, cch_t * ps)
{
- time_t res = 0;
-
- res = parse_scaled_value (0, &pz, ps, SEC_PER_HR);
+ time_t res = parse_scaled_value (0, &pz, ps, SEC_PER_HR);
pz++;
ps = strchr (pz, ':');
static time_t
parse_hourminutesecond (cch_t * in_pz)
{
- time_t res = 0;
- char buf[4];
- cch_t * pz;
-
if (strlen (in_pz) != 6)
{
errno = EINVAL;
return BAD_TIME;
}
+ char buf[4];
+
memcpy (buf, in_pz, 2);
buf[2] = NUL;
- pz = buf;
- res = parse_scaled_value (0, &pz, buf + 2, SEC_PER_HR);
+ cch_t *pz = buf;
+ time_t res = parse_scaled_value (0, &pz, buf + 2, SEC_PER_HR);
memcpy (buf, in_pz + 2, 2);
buf[2] = NUL;
- pz = buf;
+ pz = buf;
res = parse_scaled_value (res, &pz, buf + 2, SEC_PER_MIN);
memcpy (buf, in_pz + 4, 2);
buf[2] = NUL;
- pz = buf;
+ pz = buf;
return parse_scaled_value (res, &pz, buf + 2, 1);
}
parse_HMS (cch_t * pz)
{
time_t res = 0;
- cch_t * ps = strchr (pz, 'H');
- if (ps != NULL)
- {
- res = parse_scaled_value (0, &pz, ps, SEC_PER_HR);
- pz++;
- }
- ps = strchr (pz, 'M');
- if (ps != NULL)
- {
- res = parse_scaled_value (res, &pz, ps, SEC_PER_MIN);
- pz++;
- }
-
- ps = strchr (pz, 'S');
- if (ps != NULL)
- {
- res = parse_scaled_value (res, &pz, ps, 1);
- pz++;
- }
+ {
+ cch_t *ps = strchr (pz, 'H');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (0, &pz, ps, SEC_PER_HR);
+ pz++;
+ }
+ }
+ {
+ cch_t *ps = strchr (pz, 'M');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (res, &pz, ps, SEC_PER_MIN);
+ pz++;
+ }
+ }
+ {
+ cch_t *ps = strchr (pz, 'S');
+ if (ps != NULL)
+ {
+ res = parse_scaled_value (res, &pz, ps, 1);
+ pz++;
+ }
+ }
while (isspace ((unsigned char)*pz))
pz++;
static time_t
parse_time (cch_t * pz)
{
- cch_t * ps;
time_t res;
/*
* Scan for a hyphen
*/
- ps = strchr (pz, ':');
+ cch_t *ps = strchr (pz, ':');
if (ps != NULL)
{
res = parse_hour_minute_second (pz, ps);
static time_t
parse_period (cch_t * in_pz)
{
- char * pT;
- char * ps;
- char * pz = strdup (in_pz);
- void * fptr = pz;
- time_t res = 0;
+ char *pz = strdup (in_pz);
if (pz == NULL)
{
return BAD_TIME;
}
- pT = strchr (pz, 'T');
+ void * fptr = pz;
+
+ char *pT = strchr (pz, 'T');
if (pT != NULL)
{
*(pT++) = NUL;
pT = trim (pT);
}
+ time_t res;
+
/*
* Scan for a hyphen
*/
- ps = strchr (pz, '-');
+ char *ps = strchr (pz, '-');
if (ps != NULL)
{
res = parse_year_month_day (pz, ps);
time_t res = 0;
do {
- time_t val;
-
errno = 0;
- val = str_const_to_l (pz, &pz, 10);
+ time_t val = str_const_to_l (pz, &pz, 10);
if (errno != 0)
goto bad_time;
int
sendfd (int sock, int fd)
{
+ /* send at least one char */
char byte = 0;
struct iovec iov;
- struct msghdr msg;
-# if defined CMSG_FIRSTHDR
- struct cmsghdr *cmsg;
- char buf[CMSG_SPACE (sizeof fd)];
-# endif
-
- /* send at least one char */
- memset (&msg, 0, sizeof msg);
iov.iov_base = &byte;
iov.iov_len = 1;
+ struct msghdr msg;
+ memset (&msg, 0, sizeof msg);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_name = NULL;
msg.msg_namelen = 0;
# if defined CMSG_FIRSTHDR
+ char buf[CMSG_SPACE (sizeof fd)];
msg.msg_control = buf;
msg.msg_controllen = sizeof buf;
- cmsg = CMSG_FIRSTHDR (&msg);
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR (&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN (sizeof fd);
int
recvfd (int sock, int flags)
{
- char byte = 0;
- struct iovec iov;
- struct msghdr msg;
- int fd = -1;
- ssize_t len;
-# if defined CMSG_FIRSTHDR
- struct cmsghdr *cmsg;
- char buf[CMSG_SPACE (sizeof fd)];
- int flags_recvmsg = flags & O_CLOEXEC ? MSG_CMSG_CLOEXEC : 0;
-# endif
-
if ((flags & ~O_CLOEXEC) != 0)
{
errno = EINVAL;
return -1;
}
- /* send at least one char */
- memset (&msg, 0, sizeof msg);
+ int fd = -1;
+
+ /* receive at least one char */
+ char byte = 0;
+ struct iovec iov;
iov.iov_base = &byte;
iov.iov_len = 1;
+ struct msghdr msg;
+ memset (&msg, 0, sizeof msg);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_name = NULL;
msg.msg_namelen = 0;
# if defined CMSG_FIRSTHDR
+ char buf[CMSG_SPACE (sizeof fd)];
msg.msg_control = buf;
msg.msg_controllen = sizeof buf;
- cmsg = CMSG_FIRSTHDR (&msg);
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR (&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN (sizeof fd);
memcpy (CMSG_DATA (cmsg), &fd, sizeof fd);
msg.msg_controllen = CMSG_SPACE (sizeof fd);
- len = recvmsg (sock, &msg, flags_recvmsg);
+ ssize_t len = recvmsg (sock, &msg, flags & O_CLOEXEC ? MSG_CMSG_CLOEXEC : 0);
if (len < 0)
return -1;
if (len == 0)
perror (const char *string)
{
char stackbuf[STACKBUF_LEN];
- int ret;
/* Our implementation guarantees that this will be a non-empty
string, even if it returns EINVAL; and stackbuf should be sized
large enough to avoid ERANGE. */
- ret = strerror_r (errno, stackbuf, sizeof stackbuf);
+ int ret = strerror_r (errno, stackbuf, sizeof stackbuf);
if (ret == ERANGE)
abort ();
#if defined _WIN32
{ /* this works on windows */
- PFN_MS_EX pfnex;
HMODULE h = GetModuleHandle ("kernel32.dll");
-
if (!h)
return 0.0;
/* Use GlobalMemoryStatusEx if available. */
- if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx")))
+ PFN_MS_EX pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx");
+ if (pfnex)
{
lMEMORYSTATUSEX lms_ex;
lms_ex.dwLength = sizeof lms_ex;
#if defined _WIN32
{ /* this works on windows */
- PFN_MS_EX pfnex;
HMODULE h = GetModuleHandle ("kernel32.dll");
if (!h)
return 0.0;
/* Use GlobalMemoryStatusEx if available. */
- if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx")))
+ PFN_MS_EX pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx");
+ if (pfnex)
{
lMEMORYSTATUSEX lms_ex;
lms_ex.dwLength = sizeof lms_ex;
{
for (;;)
{
- ssize_t nwritten;
-
/* Allow the reader thread to continue. */
LeaveCriticalSection (&filter->lock);
- nwritten =
+ ssize_t nwritten =
write (filter->fd[1], wbuf, count > SSIZE_MAX ? SSIZE_MAX : count);
/* Get the lock back from the reader thread. */
/* Here, if done_writing, filter->reader_terminated is false. When
filter->reader_terminated becomes true, this loop is terminated. */
# if HAVE_SELECT
- int n, retval;
-
/* See whether reading or writing is possible. */
- n = 1;
+ int n = 1;
if (!filter->reader_terminated)
{
FD_SET (filter->fd[0], &filter->readfds);
/* Do EINTR handling here instead of in pipe-filter-aux.h,
because select() cannot be referred to from an inline
function on AIX 7.1. */
- do
- retval = select (n,
- (!filter->reader_terminated ? &filter->readfds : NULL),
- (!done_writing ? &filter->writefds : NULL),
- NULL, NULL);
- while (retval < 0 && errno == EINTR);
- n = retval;
+ {
+ int retval;
+ do
+ retval = select (n,
+ (!filter->reader_terminated ? &filter->readfds : NULL),
+ (!done_writing ? &filter->writefds : NULL),
+ NULL, NULL);
+ while (retval < 0 && errno == EINTR);
+ n = retval;
+ }
if (n < 0)
{
done_read_fn done_read,
void *private_data)
{
- struct pipe_filter_gi *filter;
-
- filter =
+ struct pipe_filter_gi *filter =
(struct pipe_filter_gi *) xmalloc (sizeof (struct pipe_filter_gi));
/* Open a bidirectional pipe to a subprocess. */
int
pipe_filter_gi_close (struct pipe_filter_gi *filter)
{
- int ret;
-
filter_terminate (filter);
- ret = filter_retcode (filter);
+ int ret = filter_retcode (filter);
free (filter);
return ret;
}
_beginthreadex (void *s, unsigned n, unsigned int WINAPI (*start) (void *),
void *arg, unsigned fl, unsigned *th)
{
- HANDLE h;
-
- h = malloc (sizeof (*h));
+ HANDLE h = malloc (sizeof (*h));
if (!h)
return NULL;
DosCloseEventSem (h->hevDone);
}
- free (h);
+ free (h);
return NULL;
}
WaitForMultipleObjects (DWORD nCount, const HANDLE *pHandles, BOOL bWaitAll,
DWORD ms)
{
- HMUX hmux;
- PSEMRECORD psr;
- ULONG ulUser;
- ULONG rc = (ULONG) -1;
-
- psr = malloc (sizeof (*psr) * nCount);
+ PSEMRECORD psr = malloc (sizeof (*psr) * nCount);
if (!psr)
return (DWORD) -1;
psr[i].ulUser = WAIT_OBJECT_0 + i;
}
+ HMUX hmux;
if (! DosCreateMuxWaitSem (NULL, &hmux, nCount, psr,
bWaitAll ? DCMW_WAIT_ALL : DCMW_WAIT_ANY))
{
- rc = DosWaitMuxWaitSem (hmux, ms, &ulUser);
+ ULONG ulUser;
+ ULONG rc = DosWaitMuxWaitSem (hmux, ms, &ulUser);
DosCloseMuxWaitSem (hmux);
free (psr);
return rc ? (DWORD) -1 : ulUser;
HANDLE handles[2];
#define writer_thread_handle handles[0]
#define reader_thread_handle handles[1]
- bool writer_cleaned_up;
- bool reader_cleaned_up;
l.prepare_write = prepare_write;
l.done_write = done_write;
CloseHandle (writer_thread_handle);
goto fail;
}
- writer_cleaned_up = false;
- reader_cleaned_up = false;
+ bool writer_cleaned_up = false;
+ bool reader_cleaned_up = false;
for (;;)
{
- DWORD ret;
-
/* Here !(writer_cleaned_up && reader_cleaned_up). */
+ DWORD ret;
if (writer_cleaned_up)
ret = WaitForSingleObject (reader_thread_handle, INFINITE);
else if (reader_cleaned_up)
}
{
-# if HAVE_SELECT
- fd_set readfds; /* All bits except fd[0] are always cleared. */
- fd_set writefds; /* All bits except fd[1] are always cleared. */
-# endif
- bool done_writing;
-
/* Enable non-blocking I/O. This permits the read() and write() calls
to return -1/EAGAIN without blocking; this is important for polling
if HAVE_SELECT is not defined. It also permits the read() and write()
}
# if HAVE_SELECT
+ fd_set readfds; /* All bits except fd[0] are always cleared. */
FD_ZERO (&readfds);
+ fd_set writefds; /* All bits except fd[1] are always cleared. */
FD_ZERO (&writefds);
# endif
- done_writing = false;
+ bool done_writing = false;
for (;;)
{
# if HAVE_SELECT
- int n, retval;
-
FD_SET (fd[0], &readfds);
- n = fd[0] + 1;
+ int n = fd[0] + 1;
if (!done_writing)
{
FD_SET (fd[1], &writefds);
/* Do EINTR handling here instead of in pipe-filter-aux.h,
because select() cannot be referred to from an inline
function on AIX 7.1. */
- do
- retval = select (n, &readfds, (!done_writing ? &writefds : NULL),
- NULL, NULL);
- while (retval < 0 && errno == EINTR);
- n = retval;
+ {
+ int retval;
+ do
+ retval = select (n, &readfds, (!done_writing ? &writefds : NULL),
+ NULL, NULL);
+ while (retval < 0 && errno == EINTR);
+ n = retval;
+ }
if (n < 0)
{
static BOOL
IsSocketHandle (HANDLE h)
{
- WSANETWORKEVENTS ev;
-
if (IsConsoleHandle (h))
return FALSE;
/* Under Wine, it seems that getsockopt returns 0 for pipes too.
WSAEnumNetworkEvents instead distinguishes the two correctly. */
+ WSANETWORKEVENTS ev;
ev.lNetworkEvents = 0xDEADBEEF;
WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
return ev.lNetworkEvents != 0xDEADBEEF;
static int
windows_compute_revents (HANDLE h, int *p_sought)
{
- int ret, happened;
- INPUT_RECORD *irbuffer;
- DWORD avail, nbuffer;
- BOOL bRet;
- IO_STATUS_BLOCK iosb;
- FILE_PIPE_LOCAL_INFORMATION fpli;
static PNtQueryInformationFile NtQueryInformationFile;
static BOOL once_only;
once_only = TRUE;
}
- happened = 0;
- if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
- {
- if (avail)
- happened |= *p_sought & (POLLIN | POLLRDNORM);
- }
- else if (GetLastError () == ERROR_BROKEN_PIPE)
- happened |= POLLHUP;
-
- else
- {
- /* It was the write-end of the pipe. Check if it is writable.
- If NtQueryInformationFile fails, optimistically assume the pipe is
- writable. This could happen on Windows 9x, where
- NtQueryInformationFile is not available, or if we inherit a pipe
- that doesn't permit FILE_READ_ATTRIBUTES access on the write end
- (I think this should not happen since Windows XP SP2; WINE seems
- fine too). Otherwise, ensure that enough space is available for
- atomic writes. */
- memset (&iosb, 0, sizeof (iosb));
- memset (&fpli, 0, sizeof (fpli));
-
- if (!NtQueryInformationFile
- || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
- FilePipeLocalInformation)
- || fpli.WriteQuotaAvailable >= PIPE_BUF
- || (fpli.OutboundQuota < PIPE_BUF &&
- fpli.WriteQuotaAvailable == fpli.OutboundQuota))
- happened |= *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
- }
- return happened;
+ {
+ int happened = 0;
+ DWORD avail;
+ if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
+ {
+ if (avail)
+ happened |= *p_sought & (POLLIN | POLLRDNORM);
+ }
+ else if (GetLastError () == ERROR_BROKEN_PIPE)
+ happened |= POLLHUP;
+ else
+ {
+ /* It was the write-end of the pipe. Check if it is writable.
+ If NtQueryInformationFile fails, optimistically assume the pipe is
+ writable. This could happen on Windows 9x, where
+ NtQueryInformationFile is not available, or if we inherit a pipe
+ that doesn't permit FILE_READ_ATTRIBUTES access on the write end
+ (I think this should not happen since Windows XP SP2; WINE seems
+ fine too). Otherwise, ensure that enough space is available for
+ atomic writes. */
+ IO_STATUS_BLOCK iosb;
+ memset (&iosb, 0, sizeof (iosb));
+ FILE_PIPE_LOCAL_INFORMATION fpli;
+ memset (&fpli, 0, sizeof (fpli));
+
+ if (!NtQueryInformationFile
+ || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
+ FilePipeLocalInformation)
+ || fpli.WriteQuotaAvailable >= PIPE_BUF
+ || (fpli.OutboundQuota < PIPE_BUF &&
+ fpli.WriteQuotaAvailable == fpli.OutboundQuota))
+ happened |= *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
+ }
+ return happened;
+ }
case FILE_TYPE_CHAR:
- ret = WaitForSingleObject (h, 0);
- if (!IsConsoleHandle (h))
- return ret == WAIT_OBJECT_0 ? *p_sought & ~(POLLPRI | POLLRDBAND) : 0;
-
- nbuffer = avail = 0;
- bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
- if (bRet)
+ {
+ int ret = WaitForSingleObject (h, 0);
+ if (!IsConsoleHandle (h))
+ return ret == WAIT_OBJECT_0 ? *p_sought & ~(POLLPRI | POLLRDBAND) : 0;
+ }
+
+ DWORD nbuffer = 0;
+ if (GetNumberOfConsoleInputEvents (h, &nbuffer))
{
/* Input buffer. */
*p_sought &= POLLIN | POLLRDNORM;
if (!*p_sought)
return 0;
- irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
- bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
- if (!bRet || avail == 0)
+ INPUT_RECORD *irbuffer =
+ (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
+ DWORD avail = 0;
+ if (! PeekConsoleInput (h, irbuffer, nbuffer, &avail) || avail == 0)
return POLLHUP;
for (int i = 0; i < avail; i++)
}
default:
- ret = WaitForSingleObject (h, 0);
- if (ret == WAIT_OBJECT_0)
- return *p_sought & ~(POLLPRI | POLLRDBAND);
+ {
+ int ret = WaitForSingleObject (h, 0);
+ if (ret == WAIT_OBJECT_0)
+ return *p_sought & ~(POLLPRI | POLLRDBAND);
+ }
return *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
}
if ((lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) == FD_ACCEPT)
happened |= (POLLIN | POLLRDNORM) & sought;
-
else if (lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
{
- int r, error;
-
char data[64];
WSASetLastError (0);
- r = recv (h, data, sizeof (data), MSG_PEEK);
- error = WSAGetLastError ();
+ int r = recv (h, data, sizeof (data), MSG_PEEK);
+ int error = WSAGetLastError ();
WSASetLastError (0);
if (r > 0 || error == WSAENOTCONN)
return happened;
}
-#else /* !MinGW */
+#else /* !WINDOWS_NATIVE */
/* Convert select(2) returned fd_sets into poll(2) revents values. */
static int
return happened;
}
-#endif /* !MinGW */
+#endif /* !WINDOWS_NATIVE */
int
poll (struct pollfd *pfd, nfds_t nfd, int timeout)
{
#ifndef WINDOWS_NATIVE
- fd_set rfds, wfds, efds;
- struct timeval tv;
- struct timeval *ptv;
- int maxfd, rc;
- nfds_t i;
-
if (nfd > INT_MAX)
{
errno = EINVAL;
}
/* convert timeout number into a timeval structure */
+ struct timeval tv;
+ struct timeval *ptv;
if (timeout == 0)
{
ptv = &tv;
}
/* create fd sets and determine max fd */
- maxfd = -1;
+ int maxfd = -1;
+ fd_set rfds;
FD_ZERO (&rfds);
+ fd_set wfds;
FD_ZERO (&wfds);
+ fd_set efds;
FD_ZERO (&efds);
for (int i = 0; i < nfd; i++)
{
}
/* examine fd sets */
- rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
- if (rc < 0)
- return rc;
+ {
+ int rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
+ if (rc < 0)
+ return rc;
+ }
/* establish results */
- rc = 0;
+ int rc = 0;
for (int i = 0; i < nfd; i++)
{
pfd[i].revents = (pfd[i].fd < 0
#else
static struct timeval tv0;
static HANDLE hEvent;
- WSANETWORKEVENTS ev;
- HANDLE h, handle_array[FD_SETSIZE + 2];
- DWORD ret, wait_timeout, nhandles;
- fd_set rfds, wfds, xfds;
- BOOL poll_again;
- MSG msg;
- int rc = 0;
if (nfd > INT_MAX || timeout < -1)
{
if (!hEvent)
hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
+ HANDLE handle_array[FD_SETSIZE + 2];
+
restart:
handle_array[0] = hEvent;
- nhandles = 1;
+ DWORD nhandles = 1;
+ fd_set rfds;
FD_ZERO (&rfds);
+ fd_set wfds;
FD_ZERO (&wfds);
+ fd_set xfds;
FD_ZERO (&xfds);
/* Classify socket handles and create fd sets. */
&& (sought & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM | POLLWRBAND
| POLLPRI | POLLRDBAND)))
{
- h = (HANDLE) _get_osfhandle (pfd[i].fd);
+ HANDLE h = (HANDLE) _get_osfhandle (pfd[i].fd);
assure (h != NULL);
if (IsSocketHandle (h))
{
}
}
+ BOOL poll_again;
+ DWORD wait_timeout;
if (select (0, &rfds, &wfds, &xfds, &tv0) > 0)
{
/* Do MsgWaitForMultipleObjects anyway to dispatch messages, but
for (;;)
{
- ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
- wait_timeout, QS_ALLINPUT);
+ DWORD ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
+ wait_timeout, QS_ALLINPUT);
if (ret == WAIT_OBJECT_0 + nhandles)
{
/* new input of some other kind */
- BOOL bRet;
- while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
+ MSG msg;
+ while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE) != 0)
{
TranslateMessage (&msg);
DispatchMessage (&msg);
if (poll_again)
select (0, &rfds, &wfds, &xfds, &tv0);
+ int rc = 0;
+
/* Place a sentinel at the end of the array. */
handle_array[nhandles] = NULL;
nhandles = 1;
&& (pfd[i].events & (POLLIN | POLLRDNORM |
POLLOUT | POLLWRNORM | POLLWRBAND)))
{
- h = (HANDLE) _get_osfhandle (pfd[i].fd);
+ HANDLE h = (HANDLE) _get_osfhandle (pfd[i].fd);
if (h != handle_array[nhandles])
{
/* It's a socket. */
+ WSANETWORKEVENTS ev;
WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
WSAEventSelect ((SOCKET) h, 0, 0);
temporarily marking them cloexec around the real popen call, but
we would also have to override pclose, and the bookkeeping seems
extreme given that cygwin 1.7 no longer has the bug. */
- FILE *result;
int cloexec0 = fcntl (STDIN_FILENO, F_GETFD);
int cloexec1 = fcntl (STDOUT_FILENO, F_GETFD);
- int saved_errno;
/* If either stdin or stdout was closed (that is, fcntl failed),
then we open a dummy close-on-exec fd to occupy that slot. That
fcntl (STDOUT_FILENO, F_GETFD) | FD_CLOEXEC) == -1)
abort ();
}
- result = popen (filename, mode);
+ FILE *result = popen (filename, mode);
/* Now, close any dummy fd's created in the parent. */
- saved_errno = errno;
- if (cloexec0 < 0)
- close (STDIN_FILENO);
- if (cloexec1 < 0)
- close (STDOUT_FILENO);
- errno = saved_errno;
+ {
+ int saved_errno = errno;
+ if (cloexec0 < 0)
+ close (STDIN_FILENO);
+ if (cloexec1 < 0)
+ close (STDOUT_FILENO);
+ errno = saved_errno;
+ }
return result;
}
/* On OpenBSD, master and slave of a pseudo-terminal are allocated together,
by opening /dev/ptm and applying the PTMGET ioctl to it. */
- int fd;
- struct ptmget data;
-
- fd = open (PATH_PTMDEV, O_RDWR);
+ int fd = open (PATH_PTMDEV, O_RDWR);
if (fd >= 0)
{
+ struct ptmget data;
if (ioctl (fd, PTMGET, &data) >= 0)
{
master = data.cfd;
static bool
posix_time_parse (struct tm *tm, const char *s, unsigned int syntax_bits)
{
- const char *dot = NULL;
- int pair[6];
idx_t s_len = strlen (s);
- idx_t len = s_len;
+ const char *dot = NULL;
+ idx_t len = s_len;
if (syntax_bits & PDS_SECONDS)
{
dot = strchr (s, '.');
return false;
len /= 2;
+
+ int pair[6];
for (idx_t i = 0; i < len; i++)
pair[i] = 10 * (s[2*i] - '0') + s[2*i + 1] - '0';
posixtime (time_t *p, const char *s, unsigned int syntax_bits)
{
struct tm tm0;
- bool leapsec = false;
if (! posix_time_parse (&tm0, s, syntax_bits))
return false;
+ bool leapsec = false;
while (true)
{
struct tm tm1;
{
/* Since we must not change the file pointer preserve the value so that
we can restore it later. */
- int saved_errno;
- ssize_t result;
off_t old_offset = __libc_lseek (fd, 0, SEEK_CUR);
if (old_offset == (off_t) -1)
return -1;
return -1;
/* Write out the data. */
- result = __libc_read (fd, buf, nbyte);
+ ssize_t result = __libc_read (fd, buf, nbyte);
/* Now we have to restore the position. If this fails we have to
return this as an error. But if the writing also failed we
return this error. */
- saved_errno = errno;
+ int saved_errno = errno;
if (__libc_lseek (fd, old_offset, SEEK_SET) == (off_t) -1)
{
if (result == -1)
DOUBLE
FUNC (DOUBLE x, int *expptr)
{
- int exponent;
DECL_ROUNDING
BEGIN_ROUNDING ();
+ int exponent;
+
#ifdef USE_FREXP_LDEXP
/* frexp and ldexp are usually faster than the loop below. */
x = FREXP (x, &exponent);
}
{
- arg_type type;
-
/* Parse argument type/size specifiers. */
/* Relevant for the conversion characters d, i. */
arg_type signed_type = TYPE_INT;
(void) pointer_type;
/* Read the conversion character. */
+ arg_type type;
c = *cp++;
switch (c)
{
d->count++;
if (d->count >= d_allocated)
{
- size_t memory_size;
- DIRECTIVE *memory;
-
d_allocated = xtimes (d_allocated, 2);
- memory_size = xtimes (d_allocated, sizeof (DIRECTIVE));
+ size_t memory_size = xtimes (d_allocated, sizeof (DIRECTIVE));
if (size_overflow_p (memory_size))
/* Overflow, would lead to out of memory. */
goto out_of_memory;
- memory = (DIRECTIVE *) (d->dir != d->direct_alloc_dir
- ? realloc (d->dir, memory_size)
- : malloc (memory_size));
+ DIRECTIVE *memory = (DIRECTIVE *) (d->dir != d->direct_alloc_dir
+ ? realloc (d->dir, memory_size)
+ : malloc (memory_size));
if (memory == NULL)
/* Out of memory. */
goto out_of_memory;
int
printf (const char *format, ...)
{
- int retval;
va_list args;
-
va_start (args, format);
- retval = vfprintf (stdout, format, args);
+ int retval = vfprintf (stdout, format, args);
va_end (args);
return retval;
/* If we already have an executable_fd, check that filename points to
the same inode. */
struct stat statexe;
- struct stat statfile;
if (fstat (executable_fd, &statexe) >= 0)
- return (stat (filename, &statfile) >= 0
- && statfile.st_dev
- && statfile.st_dev == statexe.st_dev
- && statfile.st_ino == statexe.st_ino);
+ {
+ struct stat statfile;
+ return (stat (filename, &statfile) >= 0
+ && statfile.st_dev
+ && statfile.st_dev == statexe.st_dev
+ && statfile.st_ino == statexe.st_ino);
+ }
}
# endif
return NULL;
return xstrdup (location);
#elif defined __EMX__
- PPIB ppib;
- char location[CCHMAXPATH];
-
/* See http://cyberkinetica.homeunix.net/os2tk45/cp1/619_L2H_DosGetInfoBlocksSynt.html
for specification of DosGetInfoBlocks(). */
+ PPIB ppib;
if (DosGetInfoBlocks (NULL, &ppib))
return NULL;
/* See http://cyberkinetica.homeunix.net/os2tk45/cp1/1247_L2H_DosQueryModuleNameSy.html
for specification of DosQueryModuleName(). */
+ char location[CCHMAXPATH];
if (DosQueryModuleName (ppib->pib_hmte, sizeof (location), location))
return NULL;
to the true pathname; older Linux versions give only device and ino,
enclosed in brackets, which we cannot use here. */
{
- char *link;
-
- link = xreadlink ("/proc/self/exe");
+ char *link = xreadlink ("/proc/self/exe");
if (link != NULL && link[0] != '[')
return link;
if (executable_fd < 0)
executable_fd = open ("/proc/self/exe", O_EXEC | O_CLOEXEC, 0);
-
- {
- char buf[6+10+5];
- sprintf (buf, "/proc/%d/exe", getpid ());
- link = xreadlink (buf);
- if (link != NULL && link[0] != '[')
- return link;
- if (executable_fd < 0)
- executable_fd = open (buf, O_EXEC | O_CLOEXEC, 0);
+ }
+ {
+ char buf[6+10+5];
+ sprintf (buf, "/proc/%d/exe", getpid ());
+ char *link = xreadlink (buf);
+ if (link != NULL && link[0] != '[')
+ return link;
}
+ if (executable_fd < 0)
+ executable_fd = open (buf, O_EXEC | O_CLOEXEC, 0);
}
# endif
# if defined __ANDROID__ || defined __FreeBSD_kernel__
/* On Android and GNU/kFreeBSD, the executable is accessible as
/proc/<pid>/exe and /proc/self/exe. */
{
- char *link;
-
- link = xreadlink ("/proc/self/exe");
+ char *link = xreadlink ("/proc/self/exe");
if (link != NULL)
return link;
}
/* In FreeBSD >= 5.0, the executable is accessible as /proc/<pid>/file and
/proc/curproc/file. */
{
- char *link;
-
- link = xreadlink ("/proc/curproc/file");
+ char *link = xreadlink ("/proc/curproc/file");
if (link != NULL)
{
if (!streq (link, "unknown"))
/* In NetBSD >= 4.0, the executable is accessible as /proc/<pid>/exe and
/proc/curproc/exe. */
{
- char *link;
-
- link = xreadlink ("/proc/curproc/exe");
+ char *link = xreadlink ("/proc/curproc/exe");
if (link != NULL)
return link;
}
/* The executable is accessible as /proc/<pid>/exe, at least in
Cygwin >= 1.5. */
{
- char *link;
-
- link = xreadlink ("/proc/self/exe");
+ char *link = xreadlink ("/proc/self/exe");
if (link != NULL)
return link;
if (executable_fd < 0)
for (const char *p = path; *p; p = p_next)
{
- const char *q;
size_t p_len;
- char *concat_name;
- for (q = p; *q; q++)
- if (*q == ':')
- break;
- p_len = q - p;
- p_next = (*q == '\0' ? q : q + 1);
+ {
+ const char *q;
+ for (q = p; *q; q++)
+ if (*q == ':')
+ break;
+ p_len = q - p;
+ p_next = (*q == '\0' ? q : q + 1);
+ }
/* We have a path item at p, of length p_len.
Now concatenate the path item and argv0. */
- concat_name = (char *) xmalloc (p_len + strlen (argv0) + 2);
+ char *concat_name =
+ (char *) xmalloc (p_len + strlen (argv0) + 2);
# ifdef NO_XMALLOC
if (concat_name == NULL)
return NULL;
prepare_relocate (const char *orig_installprefix, const char *orig_installdir,
const char *argv0)
{
- char *curr_prefix;
-
/* Determine the full pathname of the current executable. */
executable_fullname = find_executable (argv0);
/* Determine the current installation prefix from it. */
- curr_prefix = compute_curr_prefix (orig_installprefix, orig_installdir,
- executable_fullname);
+ char *curr_prefix = compute_curr_prefix (orig_installprefix, orig_installdir,
+ executable_fullname);
if (curr_prefix != NULL)
{
/* Now pass this prefix to all copies of the relocate.c source file. */
mbsstr_trimmed_wordbounded (const char *string, const char *sub)
{
char *tsub = trim (sub);
- bool found = false;
bool multibyte_locale = MB_CUR_MAX > 1;
+
size_t tsublen;
if (! multibyte_locale)
tsublen = strlen (tsub);
+ bool found = false;
while (*string != '\0')
{
const char *tsub_in_string = mbsstr (string, tsub);
break;
string = tsub_in_string + mcel_scanz (tsub_in_string).len;
#else
- mbui_iterator_t string_iter;
bool word_boundary_before;
- bool word_boundary_after;
+ {
+ mbui_iterator_t string_iter;
+ mbui_init (string_iter, string);
+ word_boundary_before = true;
+ if (mbui_cur_ptr (string_iter) < tsub_in_string)
+ {
+ mbchar_t last_char_before_tsub;
+ do
+ {
+ if (!mbui_avail (string_iter))
+ abort ();
+ last_char_before_tsub = mbui_cur (string_iter);
+ mbui_advance (string_iter);
+ }
+ while (mbui_cur_ptr (string_iter) < tsub_in_string);
+ if (mb_isalnum (last_char_before_tsub))
+ word_boundary_before = false;
+ }
+ }
- mbui_init (string_iter, string);
- word_boundary_before = true;
- if (mbui_cur_ptr (string_iter) < tsub_in_string)
+ bool word_boundary_after;
+ {
+ mbui_iterator_t string_iter;
+ mbui_init (string_iter, tsub_in_string);
{
- mbchar_t last_char_before_tsub;
- do
+ mbui_iterator_t tsub_iter;
+
+ for (mbui_init (tsub_iter, tsub);
+ mbui_avail (tsub_iter);
+ mbui_advance (tsub_iter))
{
if (!mbui_avail (string_iter))
abort ();
- last_char_before_tsub = mbui_cur (string_iter);
mbui_advance (string_iter);
}
- while (mbui_cur_ptr (string_iter) < tsub_in_string);
- if (mb_isalnum (last_char_before_tsub))
- word_boundary_before = false;
}
-
- mbui_init (string_iter, tsub_in_string);
- {
- mbui_iterator_t tsub_iter;
-
- for (mbui_init (tsub_iter, tsub);
- mbui_avail (tsub_iter);
- mbui_advance (tsub_iter))
+ word_boundary_after = true;
+ if (mbui_avail (string_iter))
{
- if (!mbui_avail (string_iter))
- abort ();
- mbui_advance (string_iter);
+ mbchar_t first_char_after_tsub = mbui_cur (string_iter);
+ if (mb_isalnum (first_char_after_tsub))
+ word_boundary_after = false;
}
}
- word_boundary_after = true;
- if (mbui_avail (string_iter))
- {
- mbchar_t first_char_after_tsub = mbui_cur (string_iter);
- if (mb_isalnum (first_char_after_tsub))
- word_boundary_after = false;
- }
if (word_boundary_before && word_boundary_after)
{
break;
}
+ mbui_iterator_t string_iter;
mbui_init (string_iter, tsub_in_string);
if (!mbui_avail (string_iter))
break;
char *alloc_name_converted_translit = NULL;
const char *name_converted = NULL;
const char *name_converted_translit = NULL;
- const char *name;
if (c_strcasecmp (locale_code, "UTF-8") != 0)
{
}
/* The name in locale encoding. */
- name = (name_converted != NULL ? name_converted :
- name_converted_translit != NULL ? name_converted_translit :
- name_ascii);
+ const char *name =
+ (name_converted != NULL ? name_converted :
+ name_converted_translit != NULL ? name_converted_translit :
+ name_ascii);
/* See whether we have a translation. Some translators have not understood
that they should use the UTF-8 form of the name, if possible. So if the
struct timespec const *restrict timeout,
sigset_t const *restrict sigmask)
{
- int select_result;
- sigset_t origmask;
- struct timeval tv, *tvp;
-
if (nfds < 0 || nfds > FD_SETSIZE)
{
errno = EINVAL;
return -1;
}
+ struct timeval tv;
+ struct timeval *tvp;
if (timeout)
{
if (! (0 <= timeout->tv_nsec && timeout->tv_nsec < 1000000000))
else
tvp = NULL;
+ sigset_t origmask;
/* Signal mask munging should be atomic, but this is the best we can
do in this emulation. */
if (sigmask)
pthread_sigmask (SIG_SETMASK, sigmask, &origmask);
- select_result = select (nfds, rfds, wfds, xfds, tvp);
+ int select_result = select (nfds, rfds, wfds, xfds, tvp);
if (sigmask)
{
static int
do_pt_chown (void)
{
- char *pty;
- struct stat st;
- struct group *p;
- gid_t gid;
-
/* Check that PTY_FILENO is a valid master pseudo terminal. */
- pty = ptsname (PTY_FILENO);
+ char *pty = ptsname (PTY_FILENO);
if (pty == NULL)
return errno == EBADF ? FAIL_EBADF : FAIL_EINVAL;
/* Check that the returned slave pseudo terminal is a
character device. */
+ struct stat st;
if (stat (pty, &st) < 0 || !S_ISCHR (st.st_mode))
return FAIL_EINVAL;
/* Get the group ID of the special 'tty' group. */
- p = getgrnam (TTY_GROUP);
- gid = p ? p->gr_gid : getgid ();
+ struct group *p = getgrnam (TTY_GROUP);
+ gid_t gid = p ? p->gr_gid : getgid ();
/* Set the owner to the real user ID, and the group to that special
group ID. */
for (;;)
{
struct timeval currtime;
- unsigned long remaining;
-
gettimeofday (&currtime, NULL);
+ unsigned long remaining;
if (currtime.tv_sec > abstime->tv_sec)
remaining = 0;
else
pthread_rwlockattr_init (pthread_rwlockattr_t *attr)
# undef pthread_rwlockattr_init
{
- int err;
-
- err = pthread_rwlockattr_init (attr);
- if (err != 0)
- return err;
- err = pthread_rwlockattr_setkind_np (attr,
- PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
- if (err != 0)
- {
- pthread_rwlockattr_destroy (attr);
+ {
+ int err = pthread_rwlockattr_init (attr);
+ if (err != 0)
return err;
- }
+ }
+ {
+ int err = pthread_rwlockattr_setkind_np (attr,
+ PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
+ if (err != 0)
+ {
+ pthread_rwlockattr_destroy (attr);
+ return err;
+ }
+ }
return 0;
}
pthread_rwlock_init (pthread_rwlock_t *lock,
_GL_UNUSED const pthread_rwlockattr_t *attr)
{
- int err;
-
- err = pthread_mutex_init (&lock->lock, NULL);
- if (err != 0)
- return err;
- err = pthread_cond_init (&lock->waiting_readers, NULL);
- if (err != 0)
- return err;
- err = pthread_cond_init (&lock->waiting_writers, NULL);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_init (&lock->lock, NULL);
+ if (err != 0)
+ return err;
+ }
+ {
+ int err = pthread_cond_init (&lock->waiting_readers, NULL);
+ if (err != 0)
+ return err;
+ }
+ {
+ int err = pthread_cond_init (&lock->waiting_writers, NULL);
+ if (err != 0)
+ return err;
+ }
lock->waiting_writers_count = 0;
lock->runcount = 0;
return 0;
int
pthread_rwlock_rdlock (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether only readers are currently running, and whether the runcount
field will not overflow, and whether no writer is waiting. The latter
condition is because POSIX recommends that "write locks shall take
{
/* This thread has to wait for a while. Enqueue it among the
waiting_readers. */
- err = pthread_cond_wait (&lock->waiting_readers, &lock->lock);
+ int err = pthread_cond_wait (&lock->waiting_readers, &lock->lock);
if (err != 0)
{
pthread_mutex_unlock (&lock->lock);
int
pthread_rwlock_wrlock (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether no readers or writers are currently running. */
while (!(lock->runcount == 0))
{
/* This thread has to wait for a while. Enqueue it among the
waiting_writers. */
lock->waiting_writers_count++;
- err = pthread_cond_wait (&lock->waiting_writers, &lock->lock);
+ int err = pthread_cond_wait (&lock->waiting_writers, &lock->lock);
if (err != 0)
{
lock->waiting_writers_count--;
int
pthread_rwlock_tryrdlock (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether only readers are currently running, and whether the runcount
field will not overflow, and whether no writer is waiting. The latter
condition is because POSIX recommends that "write locks shall take
int
pthread_rwlock_trywrlock (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether no readers or writers are currently running. */
if (!(lock->runcount == 0))
{
pthread_rwlock_timedrdlock (pthread_rwlock_t *lock,
const struct timespec *abstime)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether only readers are currently running, and whether the runcount
field will not overflow, and whether no writer is waiting. The latter
condition is because POSIX recommends that "write locks shall take
{
/* This thread has to wait for a while. Enqueue it among the
waiting_readers. */
- err = pthread_cond_timedwait (&lock->waiting_readers, &lock->lock,
- abstime);
+ int err = pthread_cond_timedwait (&lock->waiting_readers, &lock->lock,
+ abstime);
if (err != 0)
{
pthread_mutex_unlock (&lock->lock);
pthread_rwlock_timedwrlock (pthread_rwlock_t *lock,
const struct timespec *abstime)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
/* Test whether no readers or writers are currently running. */
while (!(lock->runcount == 0))
{
/* This thread has to wait for a while. Enqueue it among the
waiting_writers. */
lock->waiting_writers_count++;
- err = pthread_cond_timedwait (&lock->waiting_writers, &lock->lock,
- abstime);
+ int err = pthread_cond_timedwait (&lock->waiting_writers, &lock->lock,
+ abstime);
if (err != 0)
{
lock->waiting_writers_count--;
int
pthread_rwlock_unlock (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_lock (&lock->lock);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_lock (&lock->lock);
+ if (err != 0)
+ return err;
+ }
if (lock->runcount < 0)
{
/* Drop a writer lock. */
if (lock->waiting_writers_count > 0)
{
/* Wake up one of the waiting writers. */
- err = pthread_cond_signal (&lock->waiting_writers);
+ int err = pthread_cond_signal (&lock->waiting_writers);
if (err != 0)
{
pthread_mutex_unlock (&lock->lock);
else
{
/* Wake up all waiting readers. */
- err = pthread_cond_broadcast (&lock->waiting_readers);
+ int err = pthread_cond_broadcast (&lock->waiting_readers);
if (err != 0)
{
pthread_mutex_unlock (&lock->lock);
int
pthread_rwlock_destroy (pthread_rwlock_t *lock)
{
- int err;
-
- err = pthread_mutex_destroy (&lock->lock);
- if (err != 0)
- return err;
- err = pthread_cond_destroy (&lock->waiting_readers);
- if (err != 0)
- return err;
- err = pthread_cond_destroy (&lock->waiting_writers);
- if (err != 0)
- return err;
+ {
+ int err = pthread_mutex_destroy (&lock->lock);
+ if (err != 0)
+ return err;
+ }
+ {
+ int err = pthread_cond_destroy (&lock->waiting_readers);
+ if (err != 0)
+ return err;
+ }
+ {
+ int err = pthread_cond_destroy (&lock->waiting_writers);
+ if (err != 0)
+ return err;
+ }
return 0;
}
pthread_rwlock_init (pthread_rwlock_t *lock, const pthread_rwlockattr_t *attr)
# undef pthread_rwlock_init
{
- int err;
-
if (attr != NULL)
- err = pthread_rwlock_init (lock, attr);
+ return pthread_rwlock_init (lock, attr);
else
{
pthread_rwlockattr_t replacement_attr;
-
- err = pthread_rwlockattr_init (&replacement_attr);
- if (err != 0)
- return err;
- err = pthread_rwlockattr_setkind_np (&replacement_attr,
- PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
- if (err != 0)
- {
- pthread_rwlockattr_destroy (&replacement_attr);
+ {
+ int err = pthread_rwlockattr_init (&replacement_attr);
+ if (err != 0)
return err;
- }
- err = pthread_rwlock_init (lock, &replacement_attr);
- pthread_rwlockattr_destroy (&replacement_attr);
+ }
+ {
+ int err = pthread_rwlockattr_setkind_np (&replacement_attr,
+ PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
+ if (err != 0)
+ {
+ pthread_rwlockattr_destroy (&replacement_attr);
+ return err;
+ }
+ }
+ {
+ int err = pthread_rwlock_init (lock, &replacement_attr);
+ pthread_rwlockattr_destroy (&replacement_attr);
+ return err;
+ }
}
- return err;
}
# endif
/* Poll the lock's state in regular intervals. Ugh. */
for (;;)
{
- int err;
- struct timeval currtime;
- unsigned long remaining;
-
- err = pthread_rwlock_tryrdlock (lock);
- if (err != EBUSY)
- return err;
+ {
+ int err = pthread_rwlock_tryrdlock (lock);
+ if (err != EBUSY)
+ return err;
+ }
+ struct timeval currtime;
gettimeofday (&currtime, NULL);
+ unsigned long remaining;
if (currtime.tv_sec > abstime->tv_sec)
remaining = 0;
else
/* Poll the lock's state in regular intervals. Ugh. */
for (;;)
{
- int err;
- struct timeval currtime;
- unsigned long remaining;
-
- err = pthread_rwlock_trywrlock (lock);
- if (err != EBUSY)
- return err;
+ {
+ int err = pthread_rwlock_trywrlock (lock);
+ if (err != EBUSY)
+ return err;
+ }
+ struct timeval currtime;
gettimeofday (&currtime, NULL);
+ unsigned long remaining;
if (currtime.tv_sec > abstime->tv_sec)
remaining = 0;
else
Therefore start the loop with a pthread_mutex_trylock call. */
for (;;)
{
- int err;
- struct timeval currtime;
- unsigned long remaining;
-
- err = pthread_mutex_trylock (mutex);
- if (err != EBUSY)
- return err;
+ {
+ int err = pthread_mutex_trylock (mutex);
+ if (err != EBUSY)
+ return err;
+ }
+ struct timeval currtime;
gettimeofday (&currtime, NULL);
+ unsigned long remaining;
if (currtime.tv_sec > abstime->tv_sec)
remaining = 0;
else
#undef pthread_sigmask
{
#if HAVE_PTHREAD_SIGMASK
- int ret;
-
# if PTHREAD_SIGMASK_INEFFECTIVE
- sigset_t omask, omask_copy;
+ sigset_t omask;
sigset_t *old_mask_ptr = &omask;
sigemptyset (&omask);
/* Add a signal unlikely to be blocked, so that OMASK_COPY
is unlikely to match the actual mask. */
sigaddset (&omask, SIGILL);
+ sigset_t omask_copy;
memcpy (&omask_copy, &omask, sizeof omask);
# else
sigset_t *old_mask_ptr = old_mask;
# endif
- ret = pthread_sigmask (how, new_mask, old_mask_ptr);
+ int ret = pthread_sigmask (how, new_mask, old_mask_ptr);
# if PTHREAD_SIGMASK_INEFFECTIVE
if (ret == 0)
{
#if HAVE_ESSENTIALLY_WORKING_PTSNAME_R
# if defined __NetBSD__ || defined __sun
- char tmpbuf[32];
if (buf == NULL)
return EINVAL;
+ char tmpbuf[32];
if (buflen >= sizeof (tmpbuf))
/* ERANGE should not happen in this case. */
return ptsname_r (fd, buf, buflen);
return errno;
# endif
#elif defined __DragonFly__
- int saved_errno = errno;
- char tmpbuf[5 + 4 + 10 + 1];
- int ret;
- int n;
if (buf == NULL)
{
errno = EINVAL;
return errno;
}
+ int saved_errno = errno;
+ char tmpbuf[5 + 4 + 10 + 1];
/* The result of fdevname_r is typically of the form ptm/N. */
- ret = fdevname_r (fd, tmpbuf + 5, sizeof (tmpbuf) - 5);
+ int ret = fdevname_r (fd, tmpbuf + 5, sizeof (tmpbuf) - 5);
if (ret < 0 || strncmp (tmpbuf + 5, "ptm/", 4) != 0)
{
errno = ENOTTY;
}
/* Turn it into /dev/pts/N. */
memcpy (tmpbuf, "/dev/pts/", 5 + 4);
- n = strlen (tmpbuf);
+ int n = strlen (tmpbuf);
if (n >= buflen)
{
errno = ERANGE;
errno = saved_errno;
return 0;
#else
- int saved_errno = errno;
- struct stat st;
-
if (buf == NULL)
{
errno = EINVAL;
return errno;
}
+ int saved_errno = errno;
+ struct stat st;
+
# if defined __sun /* Solaris */
if (fstat (fd, &st) < 0)
return errno;
return errno;
}
{
- int ret;
int dev;
- char tmpbuf[9 + 10 + 1];
- int n;
- ret = ioctl (fd, ISPTM, &dev);
+ int ret = ioctl (fd, ISPTM, &dev);
if (ret < 0)
{
errno = ENOTTY;
return errno;
}
- n = sprintf (tmpbuf, "/dev/pts/%u", minor (dev));
+ char tmpbuf[9 + 10 + 1];
+ int n = sprintf (tmpbuf, "/dev/pts/%u", minor (dev));
if (n >= buflen)
{
errno = ERANGE;
/* _putenv ("NAME=") unsets NAME, so invoke _putenv ("NAME= ")
to allocate the environ vector and then replace the new
entry with "NAME=". */
- int putenv_result;
char *name_x = malloc (name_end - string + sizeof "= ");
if (!name_x)
return -1;
memcpy (name_x, string, name_end - string + 1);
name_x[name_end - string + 1] = ' ';
name_x[name_end - string + 2] = 0;
- putenv_result = _putenv (name_x);
+ int putenv_result = _putenv (name_x);
for (char **ep = environ; *ep; ep++)
if (streq (*ep, name_x))
{
{
/* Since we must not change the file pointer preserve the value so that
we can restore it later. */
- int saved_errno;
- ssize_t result;
off_t old_offset = __libc_lseek (fd, 0, SEEK_CUR);
if (old_offset == (off_t) -1)
return -1;
return -1;
/* Write out the data. */
- result = __libc_write (fd, buf, nbyte);
+ ssize_t result = __libc_write (fd, buf, nbyte);
/* Now we have to restore the position. If this fails we have to
return this as an error. But if the writing also failed we
return this error. */
- saved_errno = errno;
+ int saved_errno = errno;
if (__libc_lseek (fd, old_offset, SEEK_SET) == (off_t) -1)
{
if (result == -1)
#else
/* no XATTR, so we proceed the old dusty way */
struct permission_context ctx;
-
- ret = get_permissions (src_name, source_desc, mode, &ctx);
- if (ret != 0)
+ if (get_permissions (src_name, source_desc, mode, &ctx) != 0)
return -2;
+
ret = set_permissions (&ctx, dst_name, dest_desc);
+
free_permission_context (&ctx);
#endif
return ret;
qset_acl (char const *name, int desc, mode_t mode)
{
struct permission_context ctx;
- int ret;
-
memset (&ctx, 0, sizeof ctx);
ctx.mode = mode;
- ret = set_permissions (&ctx, name, desc);
+
+ int ret = set_permissions (&ctx, name, desc);
+
free_permission_context (&ctx);
+
return ret;
}
_quicksort (void *const pbase, size_t total_elems, size_t size,
__compar_d_fn_t cmp, void *arg)
{
- char *base_ptr = (char *) pbase;
-
- const size_t max_thresh = MAX_THRESH * size;
-
if (total_elems == 0)
/* Avoid lossage with unsigned arithmetic below. */
return;
+ char *base_ptr = (char *) pbase;
+
+ const size_t max_thresh = MAX_THRESH * size;
+
if (total_elems > MAX_THRESH)
{
char *lo = base_ptr;
{
char *const end_ptr = &base_ptr[size * (total_elems - 1)];
char *tmp_ptr = base_ptr;
- char *thresh = min(end_ptr, base_ptr + max_thresh);
+ char *thresh = min (end_ptr, base_ptr + max_thresh);
/* Find smallest element in first threshold and place it at the
array's beginning. This is the smallest array element,
tmp_ptr += size;
if (tmp_ptr != run_ptr)
{
- char *trav;
-
- trav = run_ptr + size;
+ char *trav = run_ptr + size;
while (--trav >= run_ptr)
{
char c = *trav;
int
set_quoting_flags (struct quoting_options *o, int i)
{
- int r;
if (!o)
o = &default_quoting_options;
- r = o->flags;
+ int r = o->flags;
o->flags = i;
return r;
}
char const *left_quote,
char const *right_quote)
{
+ bool unibyte_locale = MB_CUR_MAX == 1;
+
size_t len = 0;
size_t orig_buffersize = 0;
char const *quote_string = NULL;
size_t quote_string_len = 0;
bool backslash_escapes = false;
- bool unibyte_locale = MB_CUR_MAX == 1;
bool elide_outer_quotes = (flags & QA_ELIDE_OUTER_QUOTES) != 0;
bool encountered_single_quote = false;
bool all_c_and_shell_quote_compat = true;
right_quote = gettext_quote (N_("'"), quoting_style);
}
if (!elide_outer_quotes)
- for (quote_string = left_quote; *quote_string; quote_string++)
- STORE (*quote_string);
+ for (char const *lq = left_quote; *lq; lq++)
+ STORE (*lq);
backslash_escapes = true;
quote_string = right_quote;
quote_string_len = strlen (quote_string);
for (size_t i = 0; ! (argsize == SIZE_MAX ? arg[i] == '\0' : i == argsize); i++)
{
- unsigned char c;
- unsigned char esc;
bool is_right_quote = false;
bool escaping = false;
bool c_and_shell_quote_compat = false;
is_right_quote = true;
}
- c = arg[i];
+ unsigned char c = arg[i];
switch (c)
{
case '\0':
}
break;
- case '\a': esc = 'a'; goto c_escape;
- case '\b': esc = 'b'; goto c_escape;
- case '\f': esc = 'f'; goto c_escape;
- case '\n': esc = 'n'; goto c_and_shell_escape;
- case '\r': esc = 'r'; goto c_and_shell_escape;
- case '\t': esc = 't'; goto c_and_shell_escape;
- case '\v': esc = 'v'; goto c_escape;
- case '\\': esc = c;
- /* Never need to escape '\' in shell case. */
- if (quoting_style == shell_always_quoting_style)
- {
- if (elide_outer_quotes)
- goto force_outer_quoting_style;
- goto store_c;
- }
+ {
+ unsigned char esc;
+
+ case '\a': esc = 'a'; goto c_escape;
+ case '\b': esc = 'b'; goto c_escape;
+ case '\f': esc = 'f'; goto c_escape;
+ case '\n': esc = 'n'; goto c_and_shell_escape;
+ case '\r': esc = 'r'; goto c_and_shell_escape;
+ case '\t': esc = 't'; goto c_and_shell_escape;
+ case '\v': esc = 'v'; goto c_escape;
+ case '\\': esc = c;
+ /* Never need to escape '\' in shell case. */
+ if (quoting_style == shell_always_quoting_style)
+ {
+ if (elide_outer_quotes)
+ goto force_outer_quoting_style;
+ goto store_c;
+ }
- /* No need to escape the escape if we are trying to elide
- outer quotes and nothing else is problematic. */
- if (backslash_escapes && elide_outer_quotes && quote_string_len)
- goto store_c;
+ /* No need to escape the escape if we are trying to elide
+ outer quotes and nothing else is problematic. */
+ if (backslash_escapes && elide_outer_quotes && quote_string_len)
+ goto store_c;
- c_and_shell_escape:
- if (quoting_style == shell_always_quoting_style
- && elide_outer_quotes)
- goto force_outer_quoting_style;
- /* fall through */
- c_escape:
- if (backslash_escapes)
- {
- c = esc;
- goto store_escape;
- }
- break;
+ c_and_shell_escape:
+ if (quoting_style == shell_always_quoting_style
+ && elide_outer_quotes)
+ goto force_outer_quoting_style;
+ /* fall through */
+ c_escape:
+ if (backslash_escapes)
+ {
+ c = esc;
+ goto store_escape;
+ }
+ break;
+ }
case '{': case '}': /* sometimes special if isolated */
if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1))
char *
__initstate (unsigned int seed, char *arg_state, size_t n)
{
- int32_t *ostate;
- int ret;
-
__libc_lock_lock (lock);
- ostate = &unsafe_state.state[-1];
+ int32_t *ostate = &unsafe_state.state[-1];
- ret = __initstate_r (seed, arg_state, n, &unsafe_state);
+ int ret = __initstate_r (seed, arg_state, n, &unsafe_state);
__libc_lock_unlock (lock);
char *
__setstate (char *arg_state)
{
- int32_t *ostate;
-
__libc_lock_lock (lock);
- ostate = &unsafe_state.state[-1];
+ int32_t *ostate = &unsafe_state.state[-1];
if (__setstate_r (arg_state, &unsafe_state) < 0)
ostate = NULL;
long int
__random (void)
{
- int32_t retval;
-
__libc_lock_lock (lock);
+ int32_t retval;
(void) __random_r (&unsafe_state, &retval);
__libc_lock_unlock (lock);
int
__srandom_r (unsigned int seed, struct random_data *buf)
{
- int type;
- int32_t *state;
- int32_t word;
- int32_t *dst;
- int kc;
-
if (buf == NULL)
goto fail;
- type = buf->rand_type;
+ int type = buf->rand_type;
if ((unsigned int) type >= MAX_TYPES)
goto fail;
- state = buf->state;
+ int32_t *state = buf->state;
/* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */
if (seed == 0)
seed = 1;
if (type == TYPE_0)
goto done;
- dst = state;
- word = seed;
- kc = buf->rand_deg;
+ int32_t *dst = state;
+ int32_t word = seed;
+ int kc = buf->rand_deg;
for (long int i = 1; i < kc; ++i)
{
/* This does:
__setstate_r (char *arg_state, struct random_data *buf)
{
int32_t *new_state = 1 + (int32_t *) arg_state;
- int type;
- int old_type;
- int32_t *old_state;
- int degree;
- int separation;
if (arg_state == NULL || buf == NULL)
goto fail;
- old_type = buf->rand_type;
- old_state = buf->state;
+ int old_type = buf->rand_type;
+ int32_t *old_state = buf->state;
set_int32 (&old_state[-1],
(old_type == TYPE_0
? TYPE_0
: (MAX_TYPES * (buf->rptr - old_state)) + old_type));
- type = get_int32 (&new_state[-1]) % MAX_TYPES;
+ int type = get_int32 (&new_state[-1]) % MAX_TYPES;
if (type < TYPE_0 || type > TYPE_4)
goto fail;
- buf->rand_deg = degree = random_poly_info.degrees[type];
- buf->rand_sep = separation = random_poly_info.seps[type];
+ int degree = random_poly_info.degrees[type];
+ int separation = random_poly_info.seps[type];
+
+ buf->rand_deg = degree;
+ buf->rand_sep = separation;
buf->rand_type = type;
if (type != TYPE_0)
int
__random_r (struct random_data *buf, int32_t *result)
{
- int32_t *state;
-
if (buf == NULL || result == NULL)
goto fail;
- state = buf->state;
+ int32_t *state = buf->state;
if (buf->rand_type == TYPE_0)
{
/* Verify that the longword type lacks padding bits. */
static_assert (UINTPTR_WIDTH == UCHAR_WIDTH * sizeof (uintptr_t));
- const unsigned char *char_ptr;
unsigned char c = c_in;
- /* Handle the first few bytes by reading one byte at a time.
- Do this until CHAR_PTR is aligned on a natural longword boundary,
- as using alignof (longword) might be slower. */
- for (char_ptr = (const unsigned char *) s;
- (uintptr_t) char_ptr % sizeof (longword) != 0;
- ++char_ptr)
- if (*char_ptr == c)
- return (void *) char_ptr;
-
- longword const *longword_ptr = s = char_ptr;
-
- /* Compute auxiliary longword values:
- repeated_one is a value which has a 1 in every byte.
- repeated_c has c in every byte. */
- longword repeated_one = (longword) -1 / UCHAR_MAX;
- longword repeated_c = repeated_one * c;
- longword repeated_hibit = repeated_one * (UCHAR_MAX / 2 + 1);
-
- /* Instead of the traditional loop which tests each byte, we will
- test a longword at a time. The tricky part is testing if any of
- the bytes in the longword in question are equal to
- c. We first use an xor with repeated_c. This reduces the task
- to testing whether any of the bytes in longword1 is zero.
-
- (The following comments assume 8-bit bytes, as POSIX requires;
- the code's use of UCHAR_MAX should work even if bytes have more
- than 8 bits.)
-
- We compute tmp =
- ((longword1 - repeated_one) & ~longword1) & (repeated_one * 0x80).
- That is, we perform the following operations:
- 1. Subtract repeated_one.
- 2. & ~longword1.
- 3. & a mask consisting of 0x80 in every byte.
- Consider what happens in each byte:
- - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
- and step 3 transforms it into 0x80. A carry can also be propagated
- to more significant bytes.
- - If a byte of longword1 is nonzero, let its lowest 1 bit be at
- position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
- the byte ends in a single bit of value 0 and k bits of value 1.
- After step 2, the result is just k bits of value 1: 2^k - 1. After
- step 3, the result is 0. And no carry is produced.
- So, if longword1 has only non-zero bytes, tmp is zero.
- Whereas if longword1 has a zero byte, call j the position of the least
- significant zero byte. Then the result has a zero at positions 0, ...,
- j-1 and a 0x80 at position j. We cannot predict the result at the more
- significant bytes (positions j+1..3), but it does not matter since we
- already have a non-zero bit at position 8*j+7.
-
- The test whether any byte in longword1 is zero is equivalent
- to testing whether tmp is nonzero.
-
- This test can read beyond the end of a string, depending on where
- C_IN is encountered. However, this is considered safe since the
- initialization phase ensured that the read will be aligned,
- therefore, the read will not cross page boundaries and will not
- cause a fault. */
-
- while (1)
- {
- longword longword1 = *longword_ptr ^ repeated_c;
-
- if ((((longword1 - repeated_one) & ~longword1) & repeated_hibit) != 0)
- break;
- longword_ptr++;
- }
-
- char_ptr = s = longword_ptr;
-
- /* At this point, we know that one of the sizeof (longword) bytes
- starting at char_ptr is == c. If we knew endianness, we
- could determine the first such byte without any further memory
- accesses, just by looking at the tmp result from the last loop
- iteration. However, the following simple and portable code does
- not attempt this potential optimization. */
-
- while (*char_ptr != c)
- char_ptr++;
- return (void *) char_ptr;
+ {
+ const unsigned char *char_ptr;
+
+ /* Handle the first few bytes by reading one byte at a time.
+ Do this until CHAR_PTR is aligned on a natural longword boundary,
+ as using alignof (longword) might be slower. */
+ for (char_ptr = (const unsigned char *) s;
+ (uintptr_t) char_ptr % sizeof (longword) != 0;
+ ++char_ptr)
+ if (*char_ptr == c)
+ return (void *) char_ptr;
+
+ s = char_ptr;
+ }
+
+ {
+ longword const *longword_ptr = s;
+
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ longword repeated_one = (longword) -1 / UCHAR_MAX;
+ longword repeated_c = repeated_one * c;
+ longword repeated_hibit = repeated_one * (UCHAR_MAX / 2 + 1);
+
+ /* Instead of the traditional loop which tests each byte, we will
+ test a longword at a time. The tricky part is testing if any of
+ the bytes in the longword in question are equal to
+ c. We first use an xor with repeated_c. This reduces the task
+ to testing whether any of the bytes in longword1 is zero.
+
+ (The following comments assume 8-bit bytes, as POSIX requires;
+ the code's use of UCHAR_MAX should work even if bytes have more
+ than 8 bits.)
+
+ We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one * 0x80).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ The test whether any byte in longword1 is zero is equivalent
+ to testing whether tmp is nonzero.
+
+ This test can read beyond the end of a string, depending on where
+ C_IN is encountered. However, this is considered safe since the
+ initialization phase ensured that the read will be aligned,
+ therefore, the read will not cross page boundaries and will not
+ cause a fault. */
+
+ while (1)
+ {
+ longword longword1 = *longword_ptr ^ repeated_c;
+
+ if ((((longword1 - repeated_one) & ~longword1) & repeated_hibit) != 0)
+ break;
+ longword_ptr++;
+ }
+
+ s = longword_ptr;
+ }
+
+ {
+ const unsigned char *char_ptr = s;
+
+ /* At this point, we know that one of the sizeof (longword) bytes
+ starting at char_ptr is == c. If we knew endianness, we
+ could determine the first such byte without any further memory
+ accesses, just by looking at the tmp result from the last loop
+ iteration. However, the following simple and portable code does
+ not attempt this potential optimization. */
+
+ while (*char_ptr != c)
+ char_ptr++;
+ return (void *) char_ptr;
+ }
# endif
}
char *
fread_file (FILE *stream, int flags, size_t *length)
{
- char *buf;
size_t alloc = BUFSIZ;
/* For a regular file, allocate a buffer that has exactly the right
}
}
- if (!(buf = malloc (alloc)))
+ char *buf = malloc (alloc);
+ if (!buf)
return NULL; /* errno is ENOMEM. */
{
{
const char *mode = (flags & RF_BINARY) ? "rbe" : "re";
FILE *stream = fopen (filename, mode);
- char *out;
if (!stream)
return NULL;
if (flags & RF_SENSITIVE)
setvbuf (stream, NULL, _IONBF, 0);
- out = fread_file (stream, flags, length);
+ char *out = fread_file (stream, flags, length);
if (fclose (stream) != 0)
{
#if HAVE_DIRENT_H /* equivalent to HAVE_READDIR */
return readdir (dirp->real_dirp);
#else
- char type;
- struct dirent *result;
-
/* There is no need to add code to produce entries for "." and "..".
According to the POSIX:2008 section "4.12 Pathname Resolution"
<https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html>
dirp->status = 0;
+ char type;
if (dirp->entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
type = DT_DIR;
else if (dirp->entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
type = DT_UNKNOWN;
/* Reuse the memory of dirp->entry for the result. */
- result =
+ struct dirent *result =
(struct dirent *)
((char *) dirp->entry.cFileName - offsetof (struct dirent, d_name[0]));
result->d_type = type;
char *
readline (const char *prompt)
{
- char *out = NULL;
- size_t size = 0;
-
if (prompt)
{
fputs (prompt, stdout);
fflush (stdout);
}
+ char *out = NULL;
+ size_t size = 0;
if (getline (&out, &size, stdin) < 0)
{
free (out);
size_t n_delim,
token_buffer *tokenbuffer)
{
- int c;
word isdelim[(UCHAR_MAX + bits_per_word) / bits_per_word];
-
memset (isdelim, 0, sizeof isdelim);
for (idx_t i = 0; i < n_delim; i++)
{
set_nth_bit (ch, isdelim);
}
+ int c;
+
/* skip over any leading delimiters */
for (c = getc (stream); c >= 0 && get_nth_bit (c, isdelim); c = getc (stream))
{
char ***tokens_out,
size_t **token_lengths)
{
- token_buffer tb, *token = &tb;
- char **tokens;
- size_t *lengths;
- idx_t sz, n_tokens;
if (projected_n_tokens == 0)
projected_n_tokens = 64;
else
projected_n_tokens++; /* add one for trailing NULL pointer */
- sz = projected_n_tokens;
- tokens = xnmalloc (sz, sizeof *tokens);
- lengths = xnmalloc (sz, sizeof *lengths);
+ idx_t sz = projected_n_tokens;
+ char **tokens = xnmalloc (sz, sizeof *tokens);
+ size_t *lengths = xnmalloc (sz, sizeof *lengths);
- n_tokens = 0;
+ token_buffer tb;
+ token_buffer *token = &tb;
init_tokenbuffer (token);
+ idx_t n_tokens = 0;
for (;;)
{
- char *tmp;
size_t token_length = readtoken (stream, delim, n_delim, token);
if (n_tokens >= sz)
{
lengths[n_tokens] = 0;
break;
}
- tmp = xnmalloc (token_length + 1, sizeof *tmp);
+ char *tmp = xnmalloc (token_length + 1, sizeof *tmp);
lengths[n_tokens] = token_length;
tokens[n_tokens] = memcpy (tmp, token->buffer, token_length + 1);
n_tokens++;
regex_quote_spec_gnu (unsigned long /*reg_syntax_t*/ syntax, bool anchored)
{
struct regex_quote_spec result;
- char *p;
-
- p = result.special;
- memcpy (p, bre_special, sizeof (bre_special) - 1);
- p += sizeof (bre_special) - 1;
- if ((syntax & RE_LIMITED_OPS) == 0 && (syntax & RE_BK_PLUS_QM) == 0)
- {
- *p++ = '+';
- *p++ = '?';
- }
- if ((syntax & RE_INTERVALS) != 0 && (syntax & RE_NO_BK_BRACES) != 0)
- {
- *p++ = '{';
- *p++ = '}';
- }
- if ((syntax & RE_NO_BK_PARENS) != 0)
- {
- *p++ = '(';
- *p++ = ')';
- }
- if ((syntax & RE_LIMITED_OPS) == 0 && (syntax & RE_NO_BK_VBAR) != 0)
- *p++ = '|';
- if ((syntax & RE_NEWLINE_ALT) != 0)
- *p++ = '\n';
- *p = '\0';
-
+ {
+ char *p = result.special;
+ memcpy (p, bre_special, sizeof (bre_special) - 1);
+ p += sizeof (bre_special) - 1;
+ if ((syntax & RE_LIMITED_OPS) == 0 && (syntax & RE_BK_PLUS_QM) == 0)
+ {
+ *p++ = '+';
+ *p++ = '?';
+ }
+ if ((syntax & RE_INTERVALS) != 0 && (syntax & RE_NO_BK_BRACES) != 0)
+ {
+ *p++ = '{';
+ *p++ = '}';
+ }
+ if ((syntax & RE_NO_BK_PARENS) != 0)
+ {
+ *p++ = '(';
+ *p++ = ')';
+ }
+ if ((syntax & RE_LIMITED_OPS) == 0 && (syntax & RE_NO_BK_VBAR) != 0)
+ *p++ = '|';
+ if ((syntax & RE_NEWLINE_ALT) != 0)
+ *p++ = '\n';
+ *p = '\0';
+ }
result.multibyte = true;
result.anchored = anchored;
regex_quote_spec_pcre (int options, bool anchored)
{
struct regex_quote_spec result;
- char *p;
-
- p = result.special;
- memcpy (p, pcre_special, sizeof (pcre_special) - 1);
- p += sizeof (pcre_special) - 1;
- if (options & PCRE_EXTENDED)
- {
- *p++ = ' ';
- *p++ = '\t';
- *p++ = '\n';
- *p++ = '\v';
- *p++ = '\f';
- *p++ = '\r';
- *p++ = '#';
- }
- *p = '\0';
-
+ {
+ char *p = result.special;
+ memcpy (p, pcre_special, sizeof (pcre_special) - 1);
+ p += sizeof (pcre_special) - 1;
+ if (options & PCRE_EXTENDED)
+ {
+ *p++ = ' ';
+ *p++ = '\t';
+ *p++ = '\n';
+ *p++ = '\v';
+ *p++ = '\f';
+ *p++ = '\r';
+ *p++ = '#';
+ }
+ *p = '\0';
+ }
/* PCRE regular expressions consist of UTF-8 characters of options contains
PCRE_UTF8 and of single bytes otherwise. */
result.multibyte = false;
regex_quote_length (const char *string, const struct regex_quote_spec *spec)
{
const char *special = spec->special;
- size_t length;
- length = 0;
+ size_t length = 0;
if (spec->anchored)
length += 2; /* for '^' at the beginning and '$' at the end */
if (spec->multibyte)
{
#if GNULIB_MCEL_PREFER
char const *iter = string;
- for (mcel_t g; *iter; iter += g.len)
+ for (; *iter; )
{
- g = mcel_scanz (iter);
+ mcel_t g = mcel_scanz (iter);
/* We know that special contains only ASCII characters. */
length += g.len == 1 && strchr (special, *iter);
+ iter += g.len;
}
length += iter - string;
#else
{
size_t length = regex_quote_length (string, spec);
char *result = XNMALLOC (length + 1, char);
- char *p;
-
- p = result;
- p = regex_quote_copy (p, string, spec);
- *p = '\0';
+ {
+ char *p = regex_quote_copy (result, string, spec);
+ *p = '\0';
+ }
return result;
}
&& strcmp (orig_prefix_arg, curr_prefix_arg) != 0)
{
/* Duplicate the argument strings. */
- char *memory;
-
orig_prefix_len = strlen (orig_prefix_arg);
curr_prefix_len = strlen (curr_prefix_arg);
- memory = (char *) xmalloc (orig_prefix_len + 1 + curr_prefix_len + 1);
+ char *memory = (char *) xmalloc (orig_prefix_len + 1 + curr_prefix_len + 1);
#ifdef NO_XMALLOC
if (memory != NULL)
#endif
const char *orig_installdir,
const char *curr_pathname)
{
- char *curr_installdir;
- const char *rel_installdir;
-
if (curr_pathname == NULL)
return NULL;
!= 0)
/* Shouldn't happen - nothing should be installed outside $(prefix). */
return NULL;
- rel_installdir = orig_installdir + strlen (orig_installprefix);
+ const char *rel_installdir = orig_installdir + strlen (orig_installprefix);
/* Determine the current installation directory. */
+ char *curr_installdir;
{
const char *p_base = curr_pathname + FILE_SYSTEM_PREFIX_LEN (curr_pathname);
const char *p = curr_pathname + strlen (curr_pathname);
/* Linux has /proc/self/maps. glibc 2 and uClibc have the getline()
function.
But it is costly: ca. 0.3 ms. */
- FILE *fp;
/* Open the current process' maps file. It describes one VMA per line. */
- fp = fopen ("/proc/self/maps", "r");
+ FILE *fp = fopen ("/proc/self/maps", "r");
if (fp)
{
unsigned long address = (unsigned long) &find_shared_library_fullname;
for (;;)
{
unsigned long start, end;
- int c;
if (fscanf (fp, "%lx-%lx", &start, &end) != 2)
break;
if (address >= start && address <= end - 1)
{
/* Found it. Now see if this line contains a filename. */
+ int c;
while (c = getc (fp), c != EOF && c != '\n' && c != '/')
continue;
if (c == '/')
{
- size_t size;
- int len;
-
ungetc (c, fp);
- shared_library_fullname = NULL; size = 0;
- len = getline (&shared_library_fullname, &size, fp);
+ shared_library_fullname = NULL;
+ size_t size = 0;
+ int len = getline (&shared_library_fullname, &size, fp);
if (len >= 0)
{
/* Success: filled shared_library_fullname. */
}
break;
}
+ int c;
while (c = getc (fp), c != EOF && c != '\n')
continue;
}
orig_prefix. */
const char *orig_installprefix = INSTALLPREFIX;
const char *orig_installdir = INSTALLDIR;
- char *curr_prefix_better;
-
- curr_prefix_better =
+ char *curr_prefix_better =
compute_curr_prefix (orig_installprefix, orig_installdir,
get_shared_library_fullname ());
static void
activate_libdirs ()
{
- const char *old_value;
- size_t total;
- char *value;
- char *p;
-
- old_value = getenv (LIBPATHVAR);
+ const char *old_value = getenv (LIBPATHVAR);
if (old_value == NULL)
old_value = "";
- total = 0;
+ size_t total = 0;
for (size_t i = 0; i < sizeof (libdirs) / sizeof (libdirs[0]) - 1; i++)
total += strlen (libdirs[i]) + 1;
total += strlen (old_value) + 1;
- value = (char *) malloc (total);
+ char *value = (char *) malloc (total);
if (value == NULL)
{
fprintf (stderr, "%s: %s\n", program_name, "memory exhausted");
exit (1);
}
- p = value;
- for (size_t i = 0; i < sizeof (libdirs) / sizeof (libdirs[0]) - 1; i++)
- {
- size_t len = strlen (libdirs[i]);
- memcpy (p, libdirs[i], len);
- p += len;
- *p++ = ':';
- }
- if (old_value[0] != '\0')
- strcpy (p, old_value);
- else
- p[-1] = '\0';
-
+ {
+ char *p = value;
+ for (size_t i = 0; i < sizeof (libdirs) / sizeof (libdirs[0]) - 1; i++)
+ {
+ size_t len = strlen (libdirs[i]);
+ memcpy (p, libdirs[i], len);
+ p += len;
+ *p++ = ':';
+ }
+ if (old_value[0] != '\0')
+ strcpy (p, old_value);
+ else
+ p[-1] = '\0';
+ }
if (setenv (LIBPATHVAR, value, 1) < 0)
{
fprintf (stderr, "%s: %s\n", program_name, "memory exhausted");
int
main (int argc, char *argv[])
{
- char *full_program_name;
-
/* Set the program name and perform preparations for
get_full_program_name() and relocate(). */
set_program_name_and_installdir (argv[0], INSTALLPREFIX, INSTALLDIR);
/* Get the full program path. (Important if accessed through a symlink.) */
- full_program_name = get_full_program_name ();
+ char *full_program_name = get_full_program_name ();
if (full_program_name == NULL)
full_program_name = argv[0];
int
rpl_rename (char const *src, char const *dst)
{
- int error;
size_t src_len = strlen (src);
size_t dst_len = strlen (dst);
- char *src_base = last_component (src);
- char *dst_base = last_component (dst);
- bool src_slash;
- bool dst_slash;
- bool dst_exists;
- struct stat src_st;
- struct stat dst_st;
- /* Filter out dot as last component. */
if (!src_len || !dst_len)
{
errno = ENOENT;
return -1;
}
- if (*src_base == '.')
- {
- size_t len = base_len (src_base);
- if (len == 1 || (len == 2 && src_base[1] == '.'))
- {
- errno = EINVAL;
- return -1;
- }
- }
- if (*dst_base == '.')
- {
- size_t len = base_len (dst_base);
- if (len == 1 || (len == 2 && dst_base[1] == '.'))
- {
- errno = EINVAL;
- return -1;
- }
- }
+
+ /* Filter out dot as last component. */
+ {
+ char *src_base = last_component (src);
+ char *dst_base = last_component (dst);
+ if (*src_base == '.')
+ {
+ size_t len = base_len (src_base);
+ if (len == 1 || (len == 2 && src_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ if (*dst_base == '.')
+ {
+ size_t len = base_len (dst_base);
+ if (len == 1 || (len == 2 && dst_base[1] == '.'))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ }
/* Presence of a trailing slash requires directory semantics. If
the source does not exist, or if the destination cannot be turned
into a directory, give up now. Otherwise, strip trailing slashes
before calling rename. There are no symlinks on mingw, so stat
works instead of lstat. */
- src_slash = ISSLASH (src[src_len - 1]);
- dst_slash = ISSLASH (dst[dst_len - 1]);
+ bool src_slash = ISSLASH (src[src_len - 1]);
+ bool dst_slash = ISSLASH (dst[dst_len - 1]);
+ struct stat src_st;
if (stat (src, &src_st))
return -1;
+ bool dst_exists;
+ struct stat dst_st;
if (stat (dst, &dst_st))
{
if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash))
if (dst_exists && S_ISDIR (dst_st.st_mode))
{
char *cwd = getcwd (NULL, 0);
- char *src_temp;
- char *dst_temp;
if (!cwd || chdir (cwd))
return -1;
+ char *src_temp;
+ char *dst_temp;
if (IS_ABSOLUTE_FILE_NAME (src))
{
dst_temp = chdir (dst) ? NULL : getcwd (NULL, 0);
if (strncmp (src_temp, dst_temp, src_len) == 0
&& (ISSLASH (dst_temp[src_len]) || dst_temp[src_len] == '\0'))
{
- error = dst_temp[src_len];
+ int error = dst_temp[src_len];
free (src_temp);
free (dst_temp);
if (error)
/* Retry with MOVEFILE_REPLACE_EXISTING if the move failed
due to the destination already existing. */
- error = GetLastError ();
+ int error = GetLastError ();
if (error == ERROR_FILE_EXISTS || error == ERROR_ALREADY_EXISTS)
{
if (MoveFileEx (src, dst, MOVEFILE_REPLACE_EXISTING))
{
size_t src_len = strlen (src);
size_t dst_len = strlen (dst);
- char *src_temp = (char *) src;
- char *dst_temp = (char *) dst;
- bool src_slash;
- bool dst_slash;
- _GL_UNUSED bool dst_exists;
- int ret_val = -1;
- int rename_errno = ENOTDIR;
- struct stat src_st;
- struct stat dst_st;
if (!src_len || !dst_len)
return rename (src, dst); /* Let strace see the ENOENT failure. */
}
# endif /* RENAME_DEST_EXISTS_BUG */
- src_slash = src[src_len - 1] == '/';
- dst_slash = dst[dst_len - 1] == '/';
+ bool src_slash = src[src_len - 1] == '/';
+ bool dst_slash = dst[dst_len - 1] == '/';
# if !RENAME_HARD_LINK_BUG && !RENAME_DEST_EXISTS_BUG
/* If there are no trailing slashes, then trust the native
the source does not exist, or if the destination cannot be turned
into a directory, give up now. Otherwise, strip trailing slashes
before calling rename. */
+ struct stat src_st;
if (lstat (src, &src_st))
return -1;
+ struct stat dst_st;
+ _GL_UNUSED bool dst_exists;
if (lstat (dst, &dst_st))
{
if (errno != ENOENT || (!S_ISDIR (src_st.st_mode) && dst_slash))
dst_exists = true;
}
+ char *src_temp = (char *) src;
+ char *dst_temp = (char *) dst;
+ int ret_val = -1;
+ int rename_errno = ENOTDIR;
+
# if (RENAME_TRAILING_SLASH_SOURCE_BUG || RENAME_DEST_EXISTS_BUG \
|| RENAME_HARD_LINK_BUG)
/* If the only bug was that a trailing slash was allowed on a
return ret_val;
#if HAVE_RENAMEAT
- {
- size_t src_len;
- size_t dst_len;
- char *src_temp = (char *) src;
- char *dst_temp = (char *) dst;
- bool src_slash;
- bool dst_slash;
- int rename_errno = ENOTDIR;
- struct stat src_st;
- struct stat dst_st;
bool dst_found_nonexistent = false;
-
switch (flags)
{
case 0:
is defined, because RENAME_EXCL is buggy on macOS 11.2:
renameatx_np (fd, "X", fd, "X", RENAME_EXCL) incorrectly
succeeds when X exists. */
- if (fstatat (fd2, dst, &dst_st, AT_SYMLINK_NOFOLLOW) == 0
- || errno == EOVERFLOW)
- return errno_fail (EEXIST);
- if (errno != ENOENT)
- return -1;
- dst_found_nonexistent = true;
+ {
+ struct stat dst_st;
+ if (fstatat (fd2, dst, &dst_st, AT_SYMLINK_NOFOLLOW) == 0
+ || errno == EOVERFLOW)
+ return errno_fail (EEXIST);
+ if (errno != ENOENT)
+ return -1;
+ dst_found_nonexistent = true;
+ }
break;
case RENAME_EXCHANGE:
}
/* Let strace see any ENOENT failure. */
- src_len = strlen (src);
- dst_len = strlen (dst);
+ size_t src_len = strlen (src);
+ size_t dst_len = strlen (dst);
if (!src_len || !dst_len)
return renameat2ish (fd1, src, fd2, dst, flags);
- src_slash = src[src_len - 1] == '/';
- dst_slash = dst[dst_len - 1] == '/';
+ bool src_slash = src[src_len - 1] == '/';
+ bool dst_slash = dst[dst_len - 1] == '/';
if (!src_slash && !dst_slash)
return renameat2ish (fd1, src, fd2, dst, flags);
the source does not exist, or if the destination cannot be turned
into a directory, give up now. Otherwise, strip trailing slashes
before calling rename. */
+ struct stat src_st;
+ struct stat dst_st;
if (fstatat (fd1, src, &src_st, AT_SYMLINK_NOFOLLOW))
return -1;
if (dst_found_nonexistent)
else if (!S_ISDIR (src_st.st_mode))
return errno_fail (EISDIR);
+ int rename_errno = ENOTDIR;
+
+ char *src_temp = (char *) src;
+ char *dst_temp = (char *) dst;
# if RENAME_TRAILING_SLASH_SOURCE_BUG
/* See the lengthy comment in rename.c why Solaris 9 is forced to
GNU behavior, while Solaris 10 is left with POSIX behavior,
free (dst_temp);
errno = rename_errno;
return ret_val;
- }
#else /* !HAVE_RENAMEAT */
/* RENAME_NOREPLACE is the only flag currently supported. */
const char cipherKey[], size_t keyBits)
{
size_t i = 0;
- uint32_t temp;
rk[0] = GETU32 (cipherKey);
rk[1] = GETU32 (cipherKey + 4);
{
for (;;)
{
- temp = rk[3];
+ uint32_t temp = rk[3];
rk[4] = rk[0] ^
(Te4[(temp >> 16) & 0xff] & 0xff000000) ^
(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
{
for (;;)
{
- temp = rk[5];
+ uint32_t temp = rk[5];
rk[6] = rk[0] ^
(Te4[(temp >> 16) & 0xff] & 0xff000000) ^
(Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
{
for (;;)
{
- temp = rk[7];
- rk[8] = rk[0] ^
- (Te4[(temp >> 16) & 0xff] & 0xff000000) ^
- (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
- (Te4[(temp) & 0xff] & 0x0000ff00) ^
- (Te4[(temp >> 24)] & 0x000000ff) ^ rcon[i];
- rk[9] = rk[1] ^ rk[8];
- rk[10] = rk[2] ^ rk[9];
- rk[11] = rk[3] ^ rk[10];
- if (++i == 7)
- {
- return 14;
- }
- temp = rk[11];
- rk[12] = rk[4] ^
- (Te4[(temp >> 24)] & 0xff000000) ^
- (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^
- (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^
- (Te4[(temp) & 0xff] & 0x000000ff);
- rk[13] = rk[5] ^ rk[12];
- rk[14] = rk[6] ^ rk[13];
- rk[15] = rk[7] ^ rk[14];
+ {
+ uint32_t temp = rk[7];
+ rk[8] = rk[0] ^
+ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp >> 24)] & 0x000000ff) ^ rcon[i];
+ rk[9] = rk[1] ^ rk[8];
+ rk[10] = rk[2] ^ rk[9];
+ rk[11] = rk[3] ^ rk[10];
+ if (++i == 7)
+ {
+ return 14;
+ }
+ }
+ {
+ uint32_t temp = rk[11];
+ rk[12] = rk[4] ^
+ (Te4[(temp >> 24)] & 0xff000000) ^
+ (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^
+ (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^
+ (Te4[(temp) & 0xff] & 0x000000ff);
+ rk[13] = rk[5] ^ rk[12];
+ rk[14] = rk[6] ^ rk[13];
+ rk[15] = rk[7] ^ rk[14];
+ }
rk += 8;
}
rijndaelKeySetupDec (uint32_t rk[ /*4*(Nr + 1) */ ],
const char cipherKey[], size_t keyBits)
{
- size_t Nr, i, j;
- uint32_t temp;
-
/* expand the cipher key: */
- Nr = rijndaelKeySetupEnc (rk, cipherKey, keyBits);
+ size_t Nr = rijndaelKeySetupEnc (rk, cipherKey, keyBits);
/* invert the order of the round keys: */
- for (i = 0, j = 4 * Nr; i < j; i += 4, j -= 4)
- {
- temp = rk[i];
- rk[i] = rk[j];
- rk[j] = temp;
- temp = rk[i + 1];
- rk[i + 1] = rk[j + 1];
- rk[j + 1] = temp;
- temp = rk[i + 2];
- rk[i + 2] = rk[j + 2];
- rk[j + 2] = temp;
- temp = rk[i + 3];
- rk[i + 3] = rk[j + 3];
- rk[j + 3] = temp;
- }
+ {
+ size_t i, j;
+ for (i = 0, j = 4 * Nr; i < j; i += 4, j -= 4)
+ {
+ {
+ uint32_t temp = rk[i];
+ rk[i] = rk[j];
+ rk[j] = temp;
+ }
+ {
+ uint32_t temp = rk[i + 1];
+ rk[i + 1] = rk[j + 1];
+ rk[j + 1] = temp;
+ }
+ {
+ uint32_t temp = rk[i + 2];
+ rk[i + 2] = rk[j + 2];
+ rk[j + 2] = temp;
+ }
+ {
+ uint32_t temp = rk[i + 3];
+ rk[i + 3] = rk[j + 3];
+ rk[j + 3] = temp;
+ }
+ }
+ }
/* apply the inverse MixColumn transform to all round keys but the
first and the last: */
- for (i = 1; i < Nr; i++)
+ for (size_t i = 1; i < Nr; i++)
{
rk += 4;
rk[0] =
rijndaelEncrypt (const uint32_t rk[ /*4*(Nr + 1) */ ], size_t Nr,
const char pt[16], char ct[16])
{
- uint32_t s0, s1, s2, s3, t0, t1, t2, t3;
- size_t r;
+ uint32_t t0, t1, t2, t3;
- /*
- * map byte array block to cipher state
- * and add initial round key:
- */
- s0 = GETU32 (pt) ^ rk[0];
- s1 = GETU32 (pt + 4) ^ rk[1];
- s2 = GETU32 (pt + 8) ^ rk[2];
- s3 = GETU32 (pt + 12) ^ rk[3];
- /*
- * Nr - 1 full rounds:
- */
- r = Nr >> 1;
- for (;;)
- {
- t0 =
- Te0[(s0 >> 24)] ^
- Te1[(s1 >> 16) & 0xff] ^
- Te2[(s2 >> 8) & 0xff] ^ Te3[(s3) & 0xff] ^ rk[4];
- t1 =
- Te0[(s1 >> 24)] ^
- Te1[(s2 >> 16) & 0xff] ^
- Te2[(s3 >> 8) & 0xff] ^ Te3[(s0) & 0xff] ^ rk[5];
- t2 =
- Te0[(s2 >> 24)] ^
- Te1[(s3 >> 16) & 0xff] ^
- Te2[(s0 >> 8) & 0xff] ^ Te3[(s1) & 0xff] ^ rk[6];
- t3 =
- Te0[(s3 >> 24)] ^
- Te1[(s0 >> 16) & 0xff] ^
- Te2[(s1 >> 8) & 0xff] ^ Te3[(s2) & 0xff] ^ rk[7];
+ {
+ /*
+ * map byte array block to cipher state
+ * and add initial round key:
+ */
+ uint32_t s0 = GETU32 (pt) ^ rk[0];
+ uint32_t s1 = GETU32 (pt + 4) ^ rk[1];
+ uint32_t s2 = GETU32 (pt + 8) ^ rk[2];
+ uint32_t s3 = GETU32 (pt + 12) ^ rk[3];
+ /*
+ * Nr - 1 full rounds:
+ */
+ size_t r = Nr >> 1;
+ for (;;)
+ {
+ t0 =
+ Te0[(s0 >> 24)] ^
+ Te1[(s1 >> 16) & 0xff] ^
+ Te2[(s2 >> 8) & 0xff] ^ Te3[(s3) & 0xff] ^ rk[4];
+ t1 =
+ Te0[(s1 >> 24)] ^
+ Te1[(s2 >> 16) & 0xff] ^
+ Te2[(s3 >> 8) & 0xff] ^ Te3[(s0) & 0xff] ^ rk[5];
+ t2 =
+ Te0[(s2 >> 24)] ^
+ Te1[(s3 >> 16) & 0xff] ^
+ Te2[(s0 >> 8) & 0xff] ^ Te3[(s1) & 0xff] ^ rk[6];
+ t3 =
+ Te0[(s3 >> 24)] ^
+ Te1[(s0 >> 16) & 0xff] ^
+ Te2[(s1 >> 8) & 0xff] ^ Te3[(s2) & 0xff] ^ rk[7];
- rk += 8;
- if (--r == 0)
- {
- break;
- }
+ rk += 8;
+ if (--r == 0)
+ {
+ break;
+ }
- s0 =
- Te0[(t0 >> 24)] ^
- Te1[(t1 >> 16) & 0xff] ^
- Te2[(t2 >> 8) & 0xff] ^ Te3[(t3) & 0xff] ^ rk[0];
- s1 =
- Te0[(t1 >> 24)] ^
- Te1[(t2 >> 16) & 0xff] ^
- Te2[(t3 >> 8) & 0xff] ^ Te3[(t0) & 0xff] ^ rk[1];
- s2 =
- Te0[(t2 >> 24)] ^
- Te1[(t3 >> 16) & 0xff] ^
- Te2[(t0 >> 8) & 0xff] ^ Te3[(t1) & 0xff] ^ rk[2];
- s3 =
- Te0[(t3 >> 24)] ^
- Te1[(t0 >> 16) & 0xff] ^
- Te2[(t1 >> 8) & 0xff] ^ Te3[(t2) & 0xff] ^ rk[3];
- }
+ s0 =
+ Te0[(t0 >> 24)] ^
+ Te1[(t1 >> 16) & 0xff] ^
+ Te2[(t2 >> 8) & 0xff] ^ Te3[(t3) & 0xff] ^ rk[0];
+ s1 =
+ Te0[(t1 >> 24)] ^
+ Te1[(t2 >> 16) & 0xff] ^
+ Te2[(t3 >> 8) & 0xff] ^ Te3[(t0) & 0xff] ^ rk[1];
+ s2 =
+ Te0[(t2 >> 24)] ^
+ Te1[(t3 >> 16) & 0xff] ^
+ Te2[(t0 >> 8) & 0xff] ^ Te3[(t1) & 0xff] ^ rk[2];
+ s3 =
+ Te0[(t3 >> 24)] ^
+ Te1[(t0 >> 16) & 0xff] ^
+ Te2[(t1 >> 8) & 0xff] ^ Te3[(t2) & 0xff] ^ rk[3];
+ }
+ }
/*
* apply last round and
* map cipher state to byte array block:
*/
- s0 =
+ uint32_t s0 =
(Te4[(t0 >> 24)] & 0xff000000) ^
(Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^
(Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^
(Te4[(t3) & 0xff] & 0x000000ff) ^ rk[0];
PUTU32 (ct, s0);
- s1 =
+ uint32_t s1 =
(Te4[(t1 >> 24)] & 0xff000000) ^
(Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^
(Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^
(Te4[(t0) & 0xff] & 0x000000ff) ^ rk[1];
PUTU32 (ct + 4, s1);
- s2 =
+ uint32_t s2 =
(Te4[(t2 >> 24)] & 0xff000000) ^
(Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^
(Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^
(Te4[(t1) & 0xff] & 0x000000ff) ^ rk[2];
PUTU32 (ct + 8, s2);
- s3 =
+ uint32_t s3 =
(Te4[(t3 >> 24)] & 0xff000000) ^
(Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^
(Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^
rijndaelDecrypt (const uint32_t rk[ /*4*(Nr + 1) */ ], size_t Nr,
const char ct[16], char pt[16])
{
- uint32_t s0, s1, s2, s3, t0, t1, t2, t3;
- size_t r;
+ uint32_t t0, t1, t2, t3;
- /*
- * map byte array block to cipher state
- * and add initial round key:
- */
- s0 = GETU32 (ct) ^ rk[0];
- s1 = GETU32 (ct + 4) ^ rk[1];
- s2 = GETU32 (ct + 8) ^ rk[2];
- s3 = GETU32 (ct + 12) ^ rk[3];
- /*
- * Nr - 1 full rounds:
- */
- r = Nr >> 1;
- for (;;)
- {
- t0 =
- Td0[(s0 >> 24)] ^
- Td1[(s3 >> 16) & 0xff] ^
- Td2[(s2 >> 8) & 0xff] ^ Td3[(s1) & 0xff] ^ rk[4];
- t1 =
- Td0[(s1 >> 24)] ^
- Td1[(s0 >> 16) & 0xff] ^
- Td2[(s3 >> 8) & 0xff] ^ Td3[(s2) & 0xff] ^ rk[5];
- t2 =
- Td0[(s2 >> 24)] ^
- Td1[(s1 >> 16) & 0xff] ^
- Td2[(s0 >> 8) & 0xff] ^ Td3[(s3) & 0xff] ^ rk[6];
- t3 =
- Td0[(s3 >> 24)] ^
- Td1[(s2 >> 16) & 0xff] ^
- Td2[(s1 >> 8) & 0xff] ^ Td3[(s0) & 0xff] ^ rk[7];
+ {
+ /*
+ * map byte array block to cipher state
+ * and add initial round key:
+ */
+ uint32_t s0 = GETU32 (ct) ^ rk[0];
+ uint32_t s1 = GETU32 (ct + 4) ^ rk[1];
+ uint32_t s2 = GETU32 (ct + 8) ^ rk[2];
+ uint32_t s3 = GETU32 (ct + 12) ^ rk[3];
+ /*
+ * Nr - 1 full rounds:
+ */
+ size_t r = Nr >> 1;
+ for (;;)
+ {
+ t0 =
+ Td0[(s0 >> 24)] ^
+ Td1[(s3 >> 16) & 0xff] ^
+ Td2[(s2 >> 8) & 0xff] ^ Td3[(s1) & 0xff] ^ rk[4];
+ t1 =
+ Td0[(s1 >> 24)] ^
+ Td1[(s0 >> 16) & 0xff] ^
+ Td2[(s3 >> 8) & 0xff] ^ Td3[(s2) & 0xff] ^ rk[5];
+ t2 =
+ Td0[(s2 >> 24)] ^
+ Td1[(s1 >> 16) & 0xff] ^
+ Td2[(s0 >> 8) & 0xff] ^ Td3[(s3) & 0xff] ^ rk[6];
+ t3 =
+ Td0[(s3 >> 24)] ^
+ Td1[(s2 >> 16) & 0xff] ^
+ Td2[(s1 >> 8) & 0xff] ^ Td3[(s0) & 0xff] ^ rk[7];
- rk += 8;
- if (--r == 0)
- {
- break;
- }
+ rk += 8;
+ if (--r == 0)
+ {
+ break;
+ }
- s0 =
- Td0[(t0 >> 24)] ^
- Td1[(t3 >> 16) & 0xff] ^
- Td2[(t2 >> 8) & 0xff] ^ Td3[(t1) & 0xff] ^ rk[0];
- s1 =
- Td0[(t1 >> 24)] ^
- Td1[(t0 >> 16) & 0xff] ^
- Td2[(t3 >> 8) & 0xff] ^ Td3[(t2) & 0xff] ^ rk[1];
- s2 =
- Td0[(t2 >> 24)] ^
- Td1[(t1 >> 16) & 0xff] ^
- Td2[(t0 >> 8) & 0xff] ^ Td3[(t3) & 0xff] ^ rk[2];
- s3 =
- Td0[(t3 >> 24)] ^
- Td1[(t2 >> 16) & 0xff] ^
- Td2[(t1 >> 8) & 0xff] ^ Td3[(t0) & 0xff] ^ rk[3];
- }
+ s0 =
+ Td0[(t0 >> 24)] ^
+ Td1[(t3 >> 16) & 0xff] ^
+ Td2[(t2 >> 8) & 0xff] ^ Td3[(t1) & 0xff] ^ rk[0];
+ s1 =
+ Td0[(t1 >> 24)] ^
+ Td1[(t0 >> 16) & 0xff] ^
+ Td2[(t3 >> 8) & 0xff] ^ Td3[(t2) & 0xff] ^ rk[1];
+ s2 =
+ Td0[(t2 >> 24)] ^
+ Td1[(t1 >> 16) & 0xff] ^
+ Td2[(t0 >> 8) & 0xff] ^ Td3[(t3) & 0xff] ^ rk[2];
+ s3 =
+ Td0[(t3 >> 24)] ^
+ Td1[(t2 >> 16) & 0xff] ^
+ Td2[(t1 >> 8) & 0xff] ^ Td3[(t0) & 0xff] ^ rk[3];
+ }
+ }
/*
* apply last round and
* map cipher state to byte array block:
*/
- s0 =
+ uint32_t s0 =
(Td4[(t0 >> 24)] & 0xff000000) ^
(Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^
(Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^
(Td4[(t1) & 0xff] & 0x000000ff) ^ rk[0];
PUTU32 (pt, s0);
- s1 =
+ uint32_t s1 =
(Td4[(t1 >> 24)] & 0xff000000) ^
(Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^
(Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^
(Td4[(t2) & 0xff] & 0x000000ff) ^ rk[1];
PUTU32 (pt + 4, s1);
- s2 =
+ uint32_t s2 =
(Td4[(t2 >> 24)] & 0xff000000) ^
(Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^
(Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^
(Td4[(t3) & 0xff] & 0x000000ff) ^ rk[2];
PUTU32 (pt + 8, s2);
- s3 =
+ uint32_t s3 =
(Td4[(t3 >> 24)] & 0xff000000) ^
(Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^
(Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^
rijndaelMakeKey (rijndaelKeyInstance *key, rijndael_direction direction,
size_t keyLen, const char *keyMaterial)
{
- size_t i;
- char *keyMat;
- char cipherKey[RIJNDAEL_MAXKB];
-
if (key == NULL)
{
return RIJNDAEL_BAD_KEY_INSTANCE;
}
/* initialize key schedule: */
- keyMat = key->keyMaterial;
- for (i = 0; i < key->keyLen / 8; i++)
+ char *keyMat = key->keyMaterial;
+ char cipherKey[RIJNDAEL_MAXKB];
+ for (size_t i = 0; i < key->keyLen / 8; i++)
{
- char t, v;
-
- t = *keyMat++;
- if ((t >= '0') && (t <= '9'))
- v = (t - '0') << 4;
- else if ((t >= 'a') && (t <= 'f'))
- v = (t - 'a' + 10) << 4;
- else if ((t >= 'A') && (t <= 'F'))
- v = (t - 'A' + 10) << 4;
- else
- return RIJNDAEL_BAD_KEY_MAT;
-
- t = *keyMat++;
- if ((t >= '0') && (t <= '9'))
- v ^= (t - '0');
- else if ((t >= 'a') && (t <= 'f'))
- v ^= (t - 'a' + 10);
- else if ((t >= 'A') && (t <= 'F'))
- v ^= (t - 'A' + 10);
- else
- return RIJNDAEL_BAD_KEY_MAT;
+ char v;
+
+ {
+ char t = *keyMat++;
+ if ((t >= '0') && (t <= '9'))
+ v = (t - '0') << 4;
+ else if ((t >= 'a') && (t <= 'f'))
+ v = (t - 'a' + 10) << 4;
+ else if ((t >= 'A') && (t <= 'F'))
+ v = (t - 'A' + 10) << 4;
+ else
+ return RIJNDAEL_BAD_KEY_MAT;
+ }
+
+ {
+ char t = *keyMat++;
+ if ((t >= '0') && (t <= '9'))
+ v ^= (t - '0');
+ else if ((t >= 'a') && (t <= 'f'))
+ v ^= (t - 'a' + 10);
+ else if ((t >= 'A') && (t <= 'F'))
+ v ^= (t - 'A' + 10);
+ else
+ return RIJNDAEL_BAD_KEY_MAT;
+ }
cipherKey[i] = v;
}
}
if (IV != NULL)
{
- int i;
- for (i = 0; i < RIJNDAEL_MAX_IV_SIZE; i++)
+ for (int i = 0; i < RIJNDAEL_MAX_IV_SIZE; i++)
{
- int t, j;
-
- t = IV[2 * i];
- if ((t >= '0') && (t <= '9'))
- j = (t - '0') << 4;
- else if ((t >= 'a') && (t <= 'f'))
- j = (t - 'a' + 10) << 4;
- else if ((t >= 'A') && (t <= 'F'))
- j = (t - 'A' + 10) << 4;
- else
- return RIJNDAEL_BAD_CIPHER_INSTANCE;
-
- t = IV[2 * i + 1];
- if ((t >= '0') && (t <= '9'))
- j ^= (t - '0');
- else if ((t >= 'a') && (t <= 'f'))
- j ^= (t - 'a' + 10);
- else if ((t >= 'A') && (t <= 'F'))
- j ^= (t - 'A' + 10);
- else
- return RIJNDAEL_BAD_CIPHER_INSTANCE;
+ int j;
+
+ {
+ int t = IV[2 * i];
+ if ((t >= '0') && (t <= '9'))
+ j = (t - '0') << 4;
+ else if ((t >= 'a') && (t <= 'f'))
+ j = (t - 'a' + 10) << 4;
+ else if ((t >= 'A') && (t <= 'F'))
+ j = (t - 'A' + 10) << 4;
+ else
+ return RIJNDAEL_BAD_CIPHER_INSTANCE;
+ }
+
+ {
+ int t = IV[2 * i + 1];
+ if ((t >= '0') && (t <= '9'))
+ j ^= (t - '0');
+ else if ((t >= 'a') && (t <= 'f'))
+ j ^= (t - 'a' + 10);
+ else if ((t >= 'A') && (t <= 'F'))
+ j ^= (t - 'A' + 10);
+ else
+ return RIJNDAEL_BAD_CIPHER_INSTANCE;
+ }
cipher->IV[i] = (uint8_t) j;
}
const char *input,
size_t inputLen, char *outBuffer)
{
- size_t i, k, t, numBlocks;
- union { char bytes[16]; uint32_t words[4]; } block;
- char *iv;
-
if (cipher == NULL || key == NULL || key->direction == RIJNDAEL_DIR_DECRYPT)
{
return RIJNDAEL_BAD_CIPHER_STATE;
return 0; /* nothing to do */
}
- numBlocks = inputLen / 128;
+ size_t numBlocks = inputLen / 128;
+ union { char bytes[16]; uint32_t words[4]; } block;
switch (cipher->mode)
{
case RIJNDAEL_MODE_ECB:
- for (i = numBlocks; i > 0; i--)
+ for (size_t i = numBlocks; i > 0; i--)
{
rijndaelEncrypt (key->rk, key->Nr, input, outBuffer);
input += 16;
break;
case RIJNDAEL_MODE_CBC:
- iv = cipher->IV;
- for (i = numBlocks; i > 0; i--)
- {
- block.words[0] = ((uint32_t *) input)[0] ^ ((uint32_t *) iv)[0];
- block.words[1] = ((uint32_t *) input)[1] ^ ((uint32_t *) iv)[1];
- block.words[2] = ((uint32_t *) input)[2] ^ ((uint32_t *) iv)[2];
- block.words[3] = ((uint32_t *) input)[3] ^ ((uint32_t *) iv)[3];
- rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
- memcpy (cipher->IV, outBuffer, 16);
- input += 16;
- outBuffer += 16;
- }
+ {
+ char *iv = cipher->IV;
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ block.words[0] = ((uint32_t *) input)[0] ^ ((uint32_t *) iv)[0];
+ block.words[1] = ((uint32_t *) input)[1] ^ ((uint32_t *) iv)[1];
+ block.words[2] = ((uint32_t *) input)[2] ^ ((uint32_t *) iv)[2];
+ block.words[3] = ((uint32_t *) input)[3] ^ ((uint32_t *) iv)[3];
+ rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
+ memcpy (cipher->IV, outBuffer, 16);
+ input += 16;
+ outBuffer += 16;
+ }
+ }
break;
case RIJNDAEL_MODE_CFB1:
- iv = cipher->IV;
- for (i = numBlocks; i > 0; i--)
- {
- memcpy (outBuffer, input, 16);
- for (k = 0; k < 128; k++)
- {
- rijndaelEncrypt (key->ek, key->Nr, iv, block.bytes);
- outBuffer[k >> 3] ^= (block.bytes[0] & 0x80U) >> (k & 7);
- for (t = 0; t < 15; t++)
- {
- iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7);
- }
- iv[15] = (iv[15] << 1) |
- ((outBuffer[k >> 3] >> (7 - (k & 7))) & 1);
- }
- outBuffer += 16;
- input += 16;
- }
+ {
+ char *iv = cipher->IV;
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ memcpy (outBuffer, input, 16);
+ for (size_t k = 0; k < 128; k++)
+ {
+ rijndaelEncrypt (key->ek, key->Nr, iv, block.bytes);
+ outBuffer[k >> 3] ^= (block.bytes[0] & 0x80U) >> (k & 7);
+ for (size_t t = 0; t < 15; t++)
+ {
+ iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7);
+ }
+ iv[15] = (iv[15] << 1) |
+ ((outBuffer[k >> 3] >> (7 - (k & 7))) & 1);
+ }
+ outBuffer += 16;
+ input += 16;
+ }
+ }
break;
default:
const char *input,
size_t inputOctets, char *outBuffer)
{
- size_t i, numBlocks, padLen;
- union { char bytes[16]; uint32_t words[4]; } block;
- char *iv;
-
if (cipher == NULL || key == NULL || key->direction == RIJNDAEL_DIR_DECRYPT)
{
return RIJNDAEL_BAD_CIPHER_STATE;
return 0; /* nothing to do */
}
- numBlocks = inputOctets / 16;
+ size_t numBlocks = inputOctets / 16;
+ union { char bytes[16]; uint32_t words[4]; } block;
switch (cipher->mode)
{
case RIJNDAEL_MODE_ECB:
- for (i = numBlocks; i > 0; i--)
- {
- rijndaelEncrypt (key->rk, key->Nr, input, outBuffer);
- input += 16;
- outBuffer += 16;
- }
- padLen = 16 - (inputOctets - 16 * numBlocks);
- assert (padLen > 0 && padLen <= 16);
- memcpy (block.bytes, input, 16 - padLen);
- memset (block.bytes + 16 - padLen, padLen, padLen);
- rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
+ {
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ rijndaelEncrypt (key->rk, key->Nr, input, outBuffer);
+ input += 16;
+ outBuffer += 16;
+ }
+ size_t padLen = 16 - (inputOctets - 16 * numBlocks);
+ assert (padLen > 0 && padLen <= 16);
+ memcpy (block.bytes, input, 16 - padLen);
+ memset (block.bytes + 16 - padLen, padLen, padLen);
+ rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
+ }
break;
case RIJNDAEL_MODE_CBC:
- iv = cipher->IV;
- for (i = numBlocks; i > 0; i--)
- {
- block.words[0] = ((uint32_t *) input)[0] ^ ((uint32_t *) iv)[0];
- block.words[1] = ((uint32_t *) input)[1] ^ ((uint32_t *) iv)[1];
- block.words[2] = ((uint32_t *) input)[2] ^ ((uint32_t *) iv)[2];
- block.words[3] = ((uint32_t *) input)[3] ^ ((uint32_t *) iv)[3];
- rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
- memcpy (cipher->IV, outBuffer, 16);
- input += 16;
- outBuffer += 16;
- }
- padLen = 16 - (inputOctets - 16 * numBlocks);
- assert (padLen > 0 && padLen <= 16);
- for (i = 0; i < 16 - padLen; i++)
- {
- block.bytes[i] = input[i] ^ iv[i];
- }
- for (i = 16 - padLen; i < 16; i++)
- {
- block.bytes[i] = (char) padLen ^ iv[i];
- }
- rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
- memcpy (cipher->IV, outBuffer, 16);
+ {
+ char *iv = cipher->IV;
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ block.words[0] = ((uint32_t *) input)[0] ^ ((uint32_t *) iv)[0];
+ block.words[1] = ((uint32_t *) input)[1] ^ ((uint32_t *) iv)[1];
+ block.words[2] = ((uint32_t *) input)[2] ^ ((uint32_t *) iv)[2];
+ block.words[3] = ((uint32_t *) input)[3] ^ ((uint32_t *) iv)[3];
+ rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
+ memcpy (cipher->IV, outBuffer, 16);
+ input += 16;
+ outBuffer += 16;
+ }
+ size_t padLen = 16 - (inputOctets - 16 * numBlocks);
+ assert (padLen > 0 && padLen <= 16);
+ for (size_t i = 0; i < 16 - padLen; i++)
+ {
+ block.bytes[i] = input[i] ^ iv[i];
+ }
+ for (size_t i = 16 - padLen; i < 16; i++)
+ {
+ block.bytes[i] = (char) padLen ^ iv[i];
+ }
+ rijndaelEncrypt (key->rk, key->Nr, block.bytes, outBuffer);
+ memcpy (cipher->IV, outBuffer, 16);
+ }
break;
default:
const char *input,
size_t inputLen, char *outBuffer)
{
- size_t i, k, t, numBlocks;
- union { char bytes[16]; uint32_t words[4]; } block;
- char *iv;
-
if (cipher == NULL
|| key == NULL
|| (cipher->mode != RIJNDAEL_MODE_CFB1
return 0; /* nothing to do */
}
- numBlocks = inputLen / 128;
+ size_t numBlocks = inputLen / 128;
+ union { char bytes[16]; uint32_t words[4]; } block;
switch (cipher->mode)
{
case RIJNDAEL_MODE_ECB:
- for (i = numBlocks; i > 0; i--)
+ for (size_t i = numBlocks; i > 0; i--)
{
rijndaelDecrypt (key->rk, key->Nr, input, outBuffer);
input += 16;
break;
case RIJNDAEL_MODE_CBC:
- iv = cipher->IV;
- for (i = numBlocks; i > 0; i--)
- {
- rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
- block.words[0] ^= ((uint32_t *) iv)[0];
- block.words[1] ^= ((uint32_t *) iv)[1];
- block.words[2] ^= ((uint32_t *) iv)[2];
- block.words[3] ^= ((uint32_t *) iv)[3];
- memcpy (cipher->IV, input, 16);
- memcpy (outBuffer, block.bytes, 16);
- input += 16;
- outBuffer += 16;
- }
+ {
+ char *iv = cipher->IV;
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
+ block.words[0] ^= ((uint32_t *) iv)[0];
+ block.words[1] ^= ((uint32_t *) iv)[1];
+ block.words[2] ^= ((uint32_t *) iv)[2];
+ block.words[3] ^= ((uint32_t *) iv)[3];
+ memcpy (cipher->IV, input, 16);
+ memcpy (outBuffer, block.bytes, 16);
+ input += 16;
+ outBuffer += 16;
+ }
+ }
break;
case RIJNDAEL_MODE_CFB1:
- iv = cipher->IV;
- for (i = numBlocks; i > 0; i--)
- {
- memcpy (outBuffer, input, 16);
- for (k = 0; k < 128; k++)
- {
- rijndaelEncrypt (key->ek, key->Nr, iv, block.bytes);
- for (t = 0; t < 15; t++)
- {
- iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7);
- }
- iv[15] = (iv[15] << 1) | ((input[k >> 3] >> (7 - (k & 7))) & 1);
- outBuffer[k >> 3] ^= (block.bytes[0] & 0x80U) >> (k & 7);
- }
- outBuffer += 16;
- input += 16;
- }
+ {
+ char *iv = cipher->IV;
+ for (size_t i = numBlocks; i > 0; i--)
+ {
+ memcpy (outBuffer, input, 16);
+ for (size_t k = 0; k < 128; k++)
+ {
+ rijndaelEncrypt (key->ek, key->Nr, iv, block.bytes);
+ for (size_t t = 0; t < 15; t++)
+ {
+ iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7);
+ }
+ iv[15] = (iv[15] << 1) | ((input[k >> 3] >> (7 - (k & 7))) & 1);
+ outBuffer[k >> 3] ^= (block.bytes[0] & 0x80U) >> (k & 7);
+ }
+ outBuffer += 16;
+ input += 16;
+ }
+ }
break;
default:
const char *input,
size_t inputOctets, char *outBuffer)
{
- size_t i, numBlocks, padLen;
- union { char bytes[16]; uint32_t words[4]; } block;
- char *iv;
-
if (cipher == NULL || key == NULL || key->direction == RIJNDAEL_DIR_ENCRYPT)
{
return RIJNDAEL_BAD_CIPHER_STATE;
return RIJNDAEL_BAD_DATA;
}
- numBlocks = inputOctets / 16;
+ size_t numBlocks = inputOctets / 16;
+ union { char bytes[16]; uint32_t words[4]; } block;
+ size_t padLen;
switch (cipher->mode)
{
case RIJNDAEL_MODE_ECB:
- /* all blocks but last */
- for (i = numBlocks - 1; i > 0; i--)
- {
- rijndaelDecrypt (key->rk, key->Nr, input, outBuffer);
- input += 16;
- outBuffer += 16;
- }
- /* last block */
- rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
- padLen = block.bytes[15];
- if (padLen >= 16)
- {
- return RIJNDAEL_BAD_DATA;
- }
- for (i = 16 - padLen; i < 16; i++)
- {
- if (block.bytes[i] != padLen)
- {
- return RIJNDAEL_BAD_DATA;
- }
- }
- memcpy (outBuffer, block.bytes, 16 - padLen);
+ {
+ /* all blocks but last */
+ for (size_t i = numBlocks - 1; i > 0; i--)
+ {
+ rijndaelDecrypt (key->rk, key->Nr, input, outBuffer);
+ input += 16;
+ outBuffer += 16;
+ }
+ /* last block */
+ rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
+ padLen = block.bytes[15];
+ if (padLen >= 16)
+ {
+ return RIJNDAEL_BAD_DATA;
+ }
+ for (size_t i = 16 - padLen; i < 16; i++)
+ {
+ if (block.bytes[i] != padLen)
+ {
+ return RIJNDAEL_BAD_DATA;
+ }
+ }
+ memcpy (outBuffer, block.bytes, 16 - padLen);
+ }
break;
case RIJNDAEL_MODE_CBC:
- iv = cipher->IV;
- /* all blocks but last */
- for (i = numBlocks - 1; i > 0; i--)
- {
- rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
- block.words[0] ^= ((uint32_t *) iv)[0];
- block.words[1] ^= ((uint32_t *) iv)[1];
- block.words[2] ^= ((uint32_t *) iv)[2];
- block.words[3] ^= ((uint32_t *) iv)[3];
- memcpy (iv, input, 16);
- memcpy (outBuffer, block.bytes, 16);
- input += 16;
- outBuffer += 16;
- }
- /* last block */
- rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
- block.words[0] ^= ((uint32_t *) iv)[0];
- block.words[1] ^= ((uint32_t *) iv)[1];
- block.words[2] ^= ((uint32_t *) iv)[2];
- block.words[3] ^= ((uint32_t *) iv)[3];
- padLen = block.bytes[15];
- if (padLen <= 0 || padLen > 16)
- {
- return RIJNDAEL_BAD_DATA;
- }
- for (i = 16 - padLen; i < 16; i++)
- {
- if (block.bytes[i] != padLen)
- {
- return RIJNDAEL_BAD_DATA;
- }
- }
- memcpy (outBuffer, block.bytes, 16 - padLen);
+ {
+ char *iv = cipher->IV;
+ /* all blocks but last */
+ for (size_t i = numBlocks - 1; i > 0; i--)
+ {
+ rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
+ block.words[0] ^= ((uint32_t *) iv)[0];
+ block.words[1] ^= ((uint32_t *) iv)[1];
+ block.words[2] ^= ((uint32_t *) iv)[2];
+ block.words[3] ^= ((uint32_t *) iv)[3];
+ memcpy (iv, input, 16);
+ memcpy (outBuffer, block.bytes, 16);
+ input += 16;
+ outBuffer += 16;
+ }
+ /* last block */
+ rijndaelDecrypt (key->rk, key->Nr, input, block.bytes);
+ block.words[0] ^= ((uint32_t *) iv)[0];
+ block.words[1] ^= ((uint32_t *) iv)[1];
+ block.words[2] ^= ((uint32_t *) iv)[2];
+ block.words[3] ^= ((uint32_t *) iv)[3];
+ padLen = block.bytes[15];
+ if (padLen <= 0 || padLen > 16)
+ {
+ return RIJNDAEL_BAD_DATA;
+ }
+ for (size_t i = 16 - padLen; i < 16; i++)
+ {
+ if (block.bytes[i] != padLen)
+ {
+ return RIJNDAEL_BAD_DATA;
+ }
+ }
+ memcpy (outBuffer, block.bytes, 16 - padLen);
+ }
break;
default:
{
/* Work around cygwin 1.5.x bug where rmdir("dir/./") succeeds. */
size_t len = strlen (dir);
- int result;
while (len && ISSLASH (dir[len - 1]))
len--;
if (len && dir[len - 1] == '.' && (1 == len || ISSLASH (dir[len - 2])))
errno = EINVAL;
return -1;
}
- result = rmdir (dir);
+ int result = rmdir (dir);
/* Work around mingw bug, where rmdir("file/") fails with EINVAL
instead of ENOTDIR. We've already filtered out trailing ., the
only reason allowed by POSIX for EINVAL. */
localized_pattern (const char *english_pattern, nl_item nl_index,
bool posixly_correct)
{
- const char *translated_pattern;
-
/* We prefer to get the patterns from a PO file. It would be possible to
always use nl_langinfo (YESEXPR) instead of _("^[yY]"), and
nl_langinfo (NOEXPR) instead of _("^[nN]"), if we could assume that the
/* If the user wants strict POSIX compliance, use nl_langinfo. */
if (posixly_correct)
{
- translated_pattern = nl_langinfo (nl_index);
+ const char *translated_pattern = nl_langinfo (nl_index);
/* Check against a broken system return value. */
if (translated_pattern != NULL && translated_pattern[0] != '\0')
return translated_pattern;
}
/* Look in the gnulib message catalog. */
- translated_pattern = _(english_pattern);
+ const char *translated_pattern = _(english_pattern);
if (translated_pattern == english_pattern)
{
/* The gnulib message catalog provides no translation.
{
if (*lastp == NULL || !streq (pattern, *lastp))
{
- char *safe_pattern;
-
/* The pattern has changed. */
if (*lastp != NULL)
{
}
/* Put the PATTERN into safe memory before calling regcomp.
(regcomp may call nl_langinfo, overwriting PATTERN's storage. */
- safe_pattern = strdup (pattern);
+ char *safe_pattern = strdup (pattern);
if (safe_pattern == NULL)
return -1;
/* Compile the pattern and cache it for future runs. */
bool posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
# endif
- const char *yesexpr, *noexpr;
- int result;
-
- /* TRANSLATORS: A regular expression testing for an affirmative answer
- (english: "yes"). Testing the first character may be sufficient.
- Take care to consider upper and lower case.
- To enquire the regular expression that your system uses for this
- purpose, you can use the command
- locale -k LC_MESSAGES | grep '^yesexpr=' */
- yesexpr = localized_pattern (N_("^[yY]"), YESEXPR, posixly_correct);
- result = try (response, yesexpr, &last_yesexpr, &cached_yesre);
- if (result < 0)
- return -1;
- if (result)
- return 1;
-
- /* TRANSLATORS: A regular expression testing for a negative answer
- (english: "no"). Testing the first character may be sufficient.
- Take care to consider upper and lower case.
- To enquire the regular expression that your system uses for this
- purpose, you can use the command
- locale -k LC_MESSAGES | grep '^noexpr=' */
- noexpr = localized_pattern (N_("^[nN]"), NOEXPR, posixly_correct);
- result = try (response, noexpr, &last_noexpr, &cached_nore);
- if (result < 0)
- return -1;
- if (result)
- return 0;
+ {
+ /* TRANSLATORS: A regular expression testing for an affirmative answer
+ (english: "yes"). Testing the first character may be sufficient.
+ Take care to consider upper and lower case.
+ To enquire the regular expression that your system uses for this
+ purpose, you can use the command
+ locale -k LC_MESSAGES | grep '^yesexpr=' */
+ const char *yesexpr = localized_pattern (N_("^[yY]"), YESEXPR,
+ posixly_correct);
+ int result = try (response, yesexpr, &last_yesexpr, &cached_yesre);
+ if (result < 0)
+ return -1;
+ if (result)
+ return 1;
+ }
+
+ {
+ /* TRANSLATORS: A regular expression testing for a negative answer
+ (english: "no"). Testing the first character may be sufficient.
+ Take care to consider upper and lower case.
+ To enquire the regular expression that your system uses for this
+ purpose, you can use the command
+ locale -k LC_MESSAGES | grep '^noexpr=' */
+ const char *noexpr = localized_pattern (N_("^[nN]"), NOEXPR,
+ posixly_correct);
+ int result = try (response, noexpr, &last_noexpr, &cached_nore);
+ if (result < 0)
+ return -1;
+ if (result)
+ return 0;
+ }
return -1;
#else
if (compare_dirs)
{
- struct stat source_dir_stats;
- struct stat dest_dir_stats;
/* Compare the parent directories (via the device and inode numbers). */
char *source_dirname = dir_name (source);
- int flags = AT_SYMLINK_NOFOLLOW;
- if (fstatat (source_dfd, source_dirname, &source_dir_stats, flags) != 0)
+ struct stat source_dir_stats;
+ if (fstatat (source_dfd, source_dirname, &source_dir_stats,
+ AT_SYMLINK_NOFOLLOW) != 0)
{
/* Shouldn't happen. */
error (1, errno, "%s", source_dirname);
free (source_dirname);
char *dest_dirname = dir_name (dest);
+ struct stat dest_dir_stats;
#if CHECK_TRUNCATION
int destdir_errno = 0;
error (1, destdir_errno, "%s", dest_dirname);
}
#else
- if (fstatat (dest_dfd, dest_dirname, &dest_dir_stats, flags) != 0)
+ if (fstatat (dest_dfd, dest_dirname, &dest_dir_stats,
+ AT_SYMLINK_NOFOLLOW) != 0)
{
/* Shouldn't happen. */
error (1, errno, "%s", dest_dirname);
char *
streamsavedir (DIR *dirp, enum savedir_option option)
{
+ if (dirp == NULL)
+ return NULL;
+
+ comparison_function cmp = comparison_function_table[option];
+
char *name_space = NULL;
idx_t allocated = 0;
direntry_t *entries = NULL;
idx_t entries_allocated = 0;
idx_t entries_used = 0;
idx_t used = 0;
- comparison_function cmp = comparison_function_table[option];
-
- if (dirp == NULL)
- return NULL;
for (;;)
{
- struct dirent const *dp;
- char const *entry;
-
errno = 0;
- dp = readdir (dirp);
+ struct dirent const *dp = readdir (dirp);
if (! dp)
{
/* Some readdir()s do not absorb ENOENT (dir deleted but open).
/* Skip "", ".", and "..". "" is returned by at least one buggy
implementation: Solaris 2.4 readdir on NFS file systems. */
- entry = dp->d_name;
+ char const *entry = dp->d_name;
if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0')
{
idx_t entry_size = _D_EXACT_NAMLEN (dp) + 1;
if (entries_used)
qsort_r (entries, entries_used, sizeof *entries, cmp, name_space);
char *sorted_name_space = ximalloc (used + 1);
- char *p = sorted_name_space;
- for (idx_t i = 0; i < entries_used; i++)
- p = stpcpy (p, name_space + entries[i].name) + 1;
- *p = '\0';
+ {
+ char *p = sorted_name_space;
+ for (idx_t i = 0; i < entries_used; i++)
+ p = stpcpy (p, name_space + entries[i].name) + 1;
+ *p = '\0';
+ }
free (name_space);
name_space = sorted_name_space;
}
#endif
{
DIR *dp = __opendir (dir);
- DIRENT_TYPE **v = NULL;
- size_t vsize = 0;
- struct scandir_cancel_struct c;
- DIRENT_TYPE *d;
- int saved_errno;
if (dp == NULL)
return -1;
- saved_errno = errno;
+ int saved_errno = errno;
__set_errno (0);
+ struct scandir_cancel_struct c;
c.dp = dp;
c.v = NULL;
c.cnt = 0;
__libc_cleanup_push (cancel_handler, &c);
#endif
+ DIRENT_TYPE **v = NULL;
+ size_t vsize = 0;
+
+ DIRENT_TYPE *d;
while ((d = READDIR (dp)) != NULL)
{
int use_it = select == NULL;
if (use_it)
{
- DIRENT_TYPE *vnew;
- size_t dsize;
-
/* Ignore errors from select or readdir */
__set_errno (0);
c.v = (void *) v;
}
- dsize = &d->d_name[_D_ALLOC_NAMLEN (d)] - (char *) d;
- vnew = (DIRENT_TYPE *) malloc (dsize);
+ size_t dsize = &d->d_name[_D_ALLOC_NAMLEN (d)] - (char *) d;
+ DIRENT_TYPE *vnew = (DIRENT_TYPE *) malloc (dsize);
if (vnew == NULL)
break;
static BOOL
IsSocketHandle (HANDLE h)
{
- WSANETWORKEVENTS ev;
-
if (IsConsoleHandle (h))
return FALSE;
/* Under Wine, it seems that getsockopt returns 0 for pipes too.
WSAEnumNetworkEvents instead distinguishes the two correctly. */
+ WSANETWORKEVENTS ev;
ev.lNetworkEvents = 0xDEADBEEF;
WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
return ev.lNetworkEvents != 0xDEADBEEF;
struct bitset *wbits,
struct bitset *xbits)
{
- BOOL read, write, except;
- int ret;
- INPUT_RECORD *irbuffer;
- DWORD avail, nbuffer;
- BOOL bRet;
- IO_STATUS_BLOCK iosb;
- FILE_PIPE_LOCAL_INFORMATION fpli;
static PNtQueryInformationFile NtQueryInformationFile;
static BOOL once_only;
- read = write = except = FALSE;
+ BOOL read = FALSE;
+ BOOL write = FALSE;
+ BOOL except = FALSE;
switch (GetFileType (h))
{
case FILE_TYPE_DISK:
once_only = TRUE;
}
+ DWORD avail;
if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
{
if (avail)
}
else if (GetLastError () == ERROR_BROKEN_PIPE)
;
-
else
{
/* It was the write-end of the pipe. Check if it is writable.
(I think this should not happen since Windows XP SP2; WINE seems
fine too). Otherwise, ensure that enough space is available for
atomic writes. */
+ IO_STATUS_BLOCK iosb;
memset (&iosb, 0, sizeof (iosb));
+ FILE_PIPE_LOCAL_INFORMATION fpli;
memset (&fpli, 0, sizeof (fpli));
if (!NtQueryInformationFile
if (!(rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
break;
- ret = WaitForSingleObject (h, 0);
- if (ret == WAIT_OBJECT_0)
+ if (WaitForSingleObject (h, 0) == WAIT_OBJECT_0)
{
if (!IsConsoleHandle (h))
{
break;
}
- nbuffer = avail = 0;
- bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
-
+ DWORD nbuffer = 0;
+ BOOL bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
/* Screen buffers handles are filtered earlier. */
assert (bRet);
if (nbuffer == 0)
break;
}
- irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
- bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
- if (!bRet || avail == 0)
+ INPUT_RECORD *irbuffer =
+ (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
+ DWORD avail = 0;
+ if (! PeekConsoleInput (h, irbuffer, nbuffer, &avail) || avail == 0)
{
except = TRUE;
break;
break;
default:
- ret = WaitForSingleObject (h, 0);
- write = TRUE;
- if (ret == WAIT_OBJECT_0)
- read = TRUE;
-
+ {
+ int ret = WaitForSingleObject (h, 0);
+ write = TRUE;
+ if (ret == WAIT_OBJECT_0)
+ read = TRUE;
+ }
break;
}
- ret = 0;
+ int ret = 0;
if (read && (rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
{
rbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
{
static struct timeval tv0;
static HANDLE hEvent;
- HANDLE h, handle_array[FD_SETSIZE + 2];
- fd_set handle_rfds, handle_wfds, handle_xfds;
- struct bitset rbits, wbits, xbits;
- unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
- DWORD ret, wait_timeout, nhandles, nsock, nbuffer;
- MSG msg;
- int fd, rc;
- clock_t tend;
if (nfds < 0 || nfds > FD_SETSIZE)
{
return -1;
}
+ DWORD wait_timeout;
if (!timeout)
wait_timeout = INFINITE;
else
if (!hEvent)
hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
- handle_array[0] = hEvent;
- nhandles = 1;
- nsock = 0;
-
/* Copy descriptors to bitsets. At the same time, eliminate
bits in the "wrong" direction for console input buffers
and screen buffers, because screen buffers are waitable
and they will block until a character is available. */
+ struct bitset rbits;
memset (&rbits, 0, sizeof (rbits));
+ struct bitset wbits;
memset (&wbits, 0, sizeof (wbits));
+ struct bitset xbits;
memset (&xbits, 0, sizeof (xbits));
+ unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
memset (anyfds_in, 0, sizeof (anyfds_in));
if (rfds)
for (int i = 0; i < rfds->fd_count; i++)
{
- fd = rfds->fd_array[i];
- h = (HANDLE) _get_osfhandle (fd);
+ int fd = rfds->fd_array[i];
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ DWORD nbuffer;
if (!IsConsoleHandle (h)
|| GetNumberOfConsoleInputEvents (h, &nbuffer))
{
if (wfds)
for (int i = 0; i < wfds->fd_count; i++)
{
- fd = wfds->fd_array[i];
- h = (HANDLE) _get_osfhandle (fd);
+ int fd = wfds->fd_array[i];
+ HANDLE h = (HANDLE) _get_osfhandle (fd);
+ DWORD nbuffer;
if (!IsConsoleHandle (h)
|| !GetNumberOfConsoleInputEvents (h, &nbuffer))
{
if (xfds)
for (int i = 0; i < xfds->fd_count; i++)
{
- fd = xfds->fd_array[i];
+ int fd = xfds->fd_array[i];
xbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
}
FD_ZERO (rfds);
FD_ZERO (wfds);
FD_ZERO (xfds);
+ fd_set handle_rfds;
FD_ZERO (&handle_rfds);
+ fd_set handle_wfds;
FD_ZERO (&handle_wfds);
+ fd_set handle_xfds;
FD_ZERO (&handle_xfds);
+ HANDLE handle_array[FD_SETSIZE + 2];
+ handle_array[0] = hEvent;
+ DWORD nhandles = 1;
+ DWORD nsock = 0;
+
/* Classify handles. Create fd sets for sockets, poll the others. */
for (int i = 0; i < nfds; i++)
{
if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
{
- h = (HANDLE) _get_osfhandle (i);
+ HANDLE h = (HANDLE) _get_osfhandle (i);
if (!h)
{
errno = EBADF;
handle_array[nhandles] = NULL;
/* When will the waiting period expire? */
+ clock_t tend;
if (wait_timeout != INFINITE)
tend = clock () + wait_timeout;
-restart:
+restart: ;
+ int rc;
if (wait_timeout == 0 || nsock == 0)
rc = 0;
else
for (;;)
{
- ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
- wait_timeout, QS_ALLINPUT);
+ DWORD ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
+ wait_timeout, QS_ALLINPUT);
if (ret == WAIT_OBJECT_0 + nhandles)
{
/* new input of some other kind */
- BOOL bRet;
- while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
+ MSG msg;
+ while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE) != 0)
{
TranslateMessage (&msg);
DispatchMessage (&msg);
{
if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
{
- h = (HANDLE) _get_osfhandle (i);
+ HANDLE h = (HANDLE) _get_osfhandle (i);
if (h == handle_array[nhandles])
{
/* Not a socket. */
{
if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
{
- h = (HANDLE) _get_osfhandle (i);
+ HANDLE h = (HANDLE) _get_osfhandle (i);
if (h != handle_array[nhandles])
{
/* Perform handle->descriptor mapping. */
{
ace_t entries[6];
int count;
- int ret;
if (convention)
{
entries[4].a_access_mask |= NEW_ACE_EXECUTE;
count = 6;
}
+
+ int ret;
if (desc != -1)
ret = facl (desc, ACE_SETACL, count, entries);
else
{
aclent_t entries[3];
- int ret;
entries[0].a_type = USER_OBJ;
entries[0].a_id = 0; /* irrelevant */
entries[2].a_id = 0;
entries[2].a_perm = mode & 7;
+ int ret;
if (desc != -1)
ret = facl (desc, SETACL,
sizeof (entries) / sizeof (aclent_t), entries);
context_acl_from_mode (struct permission_context *ctx, const char *name, int desc)
{
struct stat statbuf;
- int ret;
+ int ret;
if (desc != -1)
ret = fstat (desc, &statbuf);
else
static int
context_aclv_from_mode (struct permission_context *ctx)
{
- int ret;
-
ctx->aclv_entries[0].a_type = USER_OBJ;
ctx->aclv_entries[0].a_id = 0; /* irrelevant */
ctx->aclv_entries[0].a_perm = (ctx->mode >> 6) & 7;
ctx->aclv_entries[3].a_perm = ctx->mode & 7;
ctx->aclv_count = 4;
- ret = aclsort (ctx->aclv_count, 1, ctx->aclv_entries);
+ int ret = aclsort (ctx->aclv_count, 1, ctx->aclv_entries);
if (ret > 0)
abort ();
return ret;
{
acl_type_list_t types;
size_t types_size = sizeof (types);
- acl_type_t type;
if (aclx_gettypes (name, &types, &types_size) < 0
|| types.num_entries == 0)
/* XXX Do we need to clear all types of ACLs for the given file, or is it
sufficient to clear the first one? */
- type = types.entries[0];
+ acl_type_t type = types.entries[0];
if (type.u64 == ACL_AIXC)
{
union { struct acl a; char room[128]; } u;
- int ret;
u.a.acl_len = (char *) &u.a.acl_ext[0] - (char *) &u.a; /* no entries */
u.a.acl_mode = mode & ~(S_IXACL | 0777);
u.a.g_access = (mode >> 3) & 7;
u.a.o_access = mode & 7;
+ int ret;
if (desc != -1)
ret = aclx_fput (desc, SET_ACL | SET_MODE_S_BITS,
type, &u.a, u.a.acl_len, mode);
else if (type.u64 == ACL_NFS4)
{
union { nfs4_acl_int_t a; char room[128]; } u;
- nfs4_ace_int_t *ace;
- int ret;
-
u.a.aclVersion = NFS4_ACL_INT_STRUCT_VERSION;
u.a.aclEntryN = 0;
- ace = &u.a.aclEntry[0];
+
+ nfs4_ace_int_t *ace = &u.a.aclEntry[0];
{
ace->flags = ACE4_ID_SPECIAL;
ace->aceWho.special_whoid = ACE4_WHO_OWNER;
}
u.a.aclLength = (char *) ace - (char *) &u.a;
+ int ret;
if (desc != -1)
ret = aclx_fput (desc, SET_ACL | SET_MODE_S_BITS,
type, &u.a, u.a.aclLength, mode);
static int
context_acl_from_mode (struct permission_context *ctx)
{
- int ret;
-
ctx->entries[0].a_type = USER_OBJ;
ctx->entries[0].a_id = 0; /* irrelevant */
ctx->entries[0].a_perm = (ctx->mode >> 6) & 7;
ctx->entries[3].a_perm = ctx->mode & 7;
ctx->count = 4;
- ret = aclsort (ctx->count, 1, entries);
+ int ret = aclsort (ctx->count, 1, entries);
if (ret > 0)
abort ();
return ret;
if (ctx->acl == NULL)
{
- acl_t acl;
-
/* Remove ACLs if the file has ACLs. */
+ acl_t acl;
if (HAVE_ACL_GET_FD && desc != -1)
acl = acl_get_fd (desc);
else
_GL_UNUSED bool acls_set = false;
bool early_chmod;
bool must_chmod = false;
- int ret = 0;
#if USE_ACL
# if HAVE_STATACL
if (early_chmod)
{
- ret = chmod_or_fchmod (name, desc, ctx->mode);
+ int ret = chmod_or_fchmod (name, desc, ctx->mode);
if (ret != 0)
return -1;
}
+ int ret = 0;
#if USE_ACL
ret = set_acls (ctx, name, desc, false, &must_chmod, &acls_set);
if (! acls_set)
__add_to_environ (const char *name, const char *value, const char *combined,
int replace)
{
- char **ep;
- size_t size;
const size_t namelen = strlen (name);
const size_t vallen = value != NULL ? strlen (value) + 1 : 0;
/* We have to get the pointer now that we have the lock and not earlier
since another thread might have created a new environment. */
- ep = __environ;
+ char **ep = __environ;
- size = 0;
+ size_t size = 0;
if (ep != NULL)
{
for (; *ep != NULL; ++ep)
if (ep == NULL || *ep == NULL)
{
- char **new_environ;
-#ifdef USE_TSEARCH
- char *new_value;
-#endif
-
/* We allocated this space; we can extend it. */
- new_environ =
+ char **new_environ =
(char **) (last_environ == NULL
? malloc ((size + 2) * sizeof (char *))
: realloc (last_environ, (size + 2) * sizeof (char *)));
{
/* See whether the value is already known. */
#ifdef USE_TSEARCH
+ char *new_value;
# ifdef _LIBC
new_value = (char *) alloca (namelen + 1 + vallen);
__mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
int
rpl_setenv (const char *name, const char *value, int replace)
{
- int result;
if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
{
errno = EINVAL;
}
/* Call the real setenv even if replace is 0, in case implementation
has underlying data to update, such as when environ changes. */
- result = setenv (name, value, replace);
+ int result = setenv (name, value, replace);
if (result == 0 && replace && *value == '=')
{
char *tmp = getenv (name);
if (!STREQ (tmp, value))
{
- int saved_errno;
size_t len = strlen (value);
tmp = malloca (len + 2);
if (tmp == NULL)
*tmp = '=';
memcpy (tmp + 1, value, len + 1);
result = setenv (name, tmp, replace);
- saved_errno = errno;
+ int saved_errno = errno;
freea (tmp);
errno = saved_errno;
}
# ifdef __minix /* Minix */
{
- FILE *hostf;
- int r = 0;
-
/* glibc returns EFAULT, EINVAL, and EPERM on error. None of
these are appropriate for us to set, even if they may match the
situation, during failed open/write/close operations, so we
leave errno alone and rely on what the system sets up. */
- hostf = fopen ("/etc/hostname.file", "we");
+ FILE *hostf = fopen ("/etc/hostname.file", "we");
+ int r = 0;
if (hostf == NULL)
r = -1;
else
int
sethostname (const char *name, size_t len)
{
- char name_asciz[HOST_NAME_MAX + 1];
- char old_name[HOST_NAME_MAX + 1];
- DWORD old_name_len;
-
/* Ensure the string isn't too long. glibc does allow setting an
empty hostname so no point in enforcing a lower bound. */
if (len > HOST_NAME_MAX)
}
/* Prepare a NUL-terminated copy of name. */
+ char name_asciz[HOST_NAME_MAX + 1];
memcpy (name_asciz, name, len);
name_asciz[len] = '\0';
/* Save the old NetBIOS name. */
- old_name_len = sizeof (old_name) - 1;
+ char old_name[HOST_NAME_MAX + 1];
+ DWORD old_name_len = sizeof (old_name) - 1;
if (! GetComputerNameEx (ComputerNamePhysicalNetBIOS,
old_name, &old_name_len))
old_name_len = 0;
setlocale_unixlike (int category, const char *locale)
{
int is_utf8 = (GetACP () == 65001);
- char *result;
- char llCC_buf[64];
- char ll_buf[64];
- char CC_buf[64];
/* The native Windows implementation of setlocale understands the special
locale name "C", but not "POSIX". Therefore map "POSIX" to "C". */
locale = "English_United States.65001";
/* First, try setlocale with the original argument unchanged. */
- result = setlocale_mtsafe (category, locale);
+ char *result = setlocale_mtsafe (category, locale);
if (result != NULL)
return result;
/* Otherwise, assume the argument is in the form
language[_territory][.codeset][@modifier]
and try to map it using the tables. */
+ char llCC_buf[64];
if (strlen (locale) < sizeof (llCC_buf))
{
/* Second try: Remove the codeset part. */
if (territory_end == NULL)
territory_end = territory_start + strlen (territory_start);
+ char ll_buf[64];
memcpy (ll_buf, llCC_buf, underscore - llCC_buf);
strcpy (ll_buf + (underscore - llCC_buf), territory_end);
+ char CC_buf[64];
memcpy (CC_buf, territory_start, territory_end - territory_start);
CC_buf[territory_end - territory_start] = '\0';
langcmp (const char *locale1, const char *locale2)
{
size_t locale1_len;
- size_t locale2_len;
- int cmp;
-
{
const char *locale1_end = strchr (locale1, '_');
if (locale1_end != NULL)
else
locale1_len = strlen (locale1);
}
+ size_t locale2_len;
{
const char *locale2_end = strchr (locale2, '_');
if (locale2_end != NULL)
locale2_len = strlen (locale2);
}
+ int cmp;
if (locale1_len < locale2_len)
{
cmp = memcmp (locale1, locale2, locale1_len);
LC_MONETARY,
LC_MESSAGES
};
- char *saved_locale;
- const char *base_name;
- unsigned int i;
/* Back up the old locale, in case one of the steps fails. */
- saved_locale = setlocale (LC_ALL, NULL);
+ char *saved_locale = setlocale (LC_ALL, NULL);
if (saved_locale == NULL)
return NULL;
saved_locale = strdup (saved_locale);
/* Set LC_CTYPE category. Set all other categories (except possibly
LC_MESSAGES) to the same value in the same call; this is likely to
save calls. */
- base_name =
+ const char *base_name =
gl_locale_name_environ (LC_CTYPE, category_to_name (LC_CTYPE));
if (base_name == NULL)
base_name = gl_locale_name_default ();
+ unsigned int i;
if (setlocale_unixlike (LC_ALL, base_name) != NULL)
{
/* LC_CTYPE category already set. */
for (; i < sizeof (categories) / sizeof (categories[0]); i++)
{
int cat = categories[i];
- const char *name;
-
- name = gl_locale_name_environ (cat, category_to_name (cat));
+ const char *name =
+ gl_locale_name_environ (cat, category_to_name (cat));
if (name == NULL)
name = gl_locale_name_default ();
setlocale_null_r_with_lock (int category, char *buf, size_t bufsize)
{
CRITICAL_SECTION *lock = gl_get_setlocale_null_lock ();
- int ret;
EnterCriticalSection (lock);
- ret = setlocale_null_r_unlocked (category, buf, bufsize);
+ int ret = setlocale_null_r_unlocked (category, buf, bufsize);
LeaveCriticalSection (lock);
return ret;
if (pthread_in_use())
{
pthread_mutex_t *lock = gl_get_setlocale_null_lock ();
- int ret;
if (pthread_mutex_lock (lock))
abort ();
- ret = setlocale_null_r_unlocked (category, buf, bufsize);
+ int ret = setlocale_null_r_unlocked (category, buf, bufsize);
if (pthread_mutex_unlock (lock))
abort ();
setlocale_null_r_with_lock (int category, char *buf, size_t bufsize)
{
mtx_t *lock = gl_get_setlocale_null_lock ();
- int ret;
if (mtx_lock (lock) != thrd_success)
abort ();
- ret = setlocale_null_r_unlocked (category, buf, bufsize);
+ int ret = setlocale_null_r_unlocked (category, buf, bufsize);
if (mtx_unlock (lock) != thrd_success)
abort ();
i;
char buf[SETLOCALE_NULL_MAX];
static char resultbuf[LC_INDICES_COUNT][SETLOCALE_NULL_MAX];
- int err;
-
- err = setlocale_null_r (category, buf, sizeof (buf));
+ int err = setlocale_null_r (category, buf, sizeof (buf));
if (err == EINVAL)
return NULL;
if (err)
rpl_setsockopt (int fd, int level, int optname, const void *optval, socklen_t optlen)
{
SOCKET sock = FD_TO_SOCKET (fd);
- int r;
-
if (sock == INVALID_SOCKET)
{
errno = EBADF;
}
else
{
+ int r;
+
if (level == SOL_SOCKET
&& (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO))
{
{
if (*argv != NULL)
{
- size_t length;
- char *command;
- char *p;
-
- length = 0;
+ size_t length = 0;
for (const char * const *argp = argv; ; )
{
length += shell_quote_length (*argp) + 1;
break;
}
- command = XNMALLOC (length, char);
-
- p = command;
- for (const char * const *argp = argv; ; )
- {
- p = shell_quote_copy (p, *argp);
- argp++;
- if (*argp == NULL)
- break;
- *p++ = ' ';
- }
- *p = '\0';
+ char *command = XNMALLOC (length, char);
+
+ {
+ char *p = command;
+ for (const char * const *argp = argv; ; )
+ {
+ p = shell_quote_copy (p, *argp);
+ argp++;
+ if (*argp == NULL)
+ break;
+ *p++ = ' ';
+ }
+ *p = '\0';
+ }
return command;
}
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
if (feof (stream))
goto process_partial_block;
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
while (words < endp)
{
- uint32_t tm;
for (int t = 0; t < 16; t++)
{
x[t] = SWAP (*words);
words++;
}
+ uint32_t tm;
+
R( a, b, c, d, e, F1, K1, x[ 0] );
R( e, a, b, c, d, F1, K1, x[ 1] );
R( d, e, a, b, c, F1, K1, x[ 2] );
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
if (feof (stream))
goto process_partial_block;
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
+ S0(x[(I-15)&0x0f]) + x[I&0x0f] \
, x[I&0x0f] = tm )
-#define R(A,B,C,D,E,F,G,H,K,M) do { t0 = SS0(A) + F2(A,B,C); \
- t1 = H + SS1(E) \
+#define R(A,B,C,D,E,F,G,H,K,M) do { uint32_t t0 = SS0(A) + F2(A,B,C); \
+ uint32_t t1 = H + SS1(E) \
+ F1(E,F,G) \
+ K \
+ M; \
while (words < endp)
{
- uint32_t tm;
- uint32_t t0, t1;
/* FIXME: see sha1.c for a better implementation. */
for (int t = 0; t < 16; t++)
{
words++;
}
+ uint32_t tm;
+
R( a, b, c, d, e, f, g, h, K( 0), x[ 0] );
R( h, a, b, c, d, e, f, g, K( 1), x[ 1] );
R( g, h, a, b, c, d, e, f, K( 2), x[ 2] );
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
if (feof (stream))
goto process_partial_block;
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
sha3_read_ctx (const struct sha3_ctx *ctx, void *resbuf)
{
char *r = resbuf;
- int i;
size_t words = ctx->digestlen / sizeof *ctx->state;
size_t bytes = ctx->digestlen % sizeof *ctx->state;
+ int i;
for (i = 0; i < words; ++i, r += sizeof *ctx->state)
set_uint64 (r, SWAP (ctx->state[i]));
if (bytes)
const u64 *words = buffer;
size_t nwords = len / sizeof *words;
const u64 *endp = words + nwords;
- u64 c[5];
- u64 d[5];
- u64 t1;
- u64 t2;
while (words < endp)
{
ctx->state[i] = u64xor (ctx->state[i], SWAP (*words));
for (int i = 0; i < 24; ++i)
{
+ u64 c[5];
+ u64 d[5];
+ u64 t1;
+ u64 t2;
+
/* Theta step 1. */
c[0] = u64xor (u64xor (u64xor (u64xor (a[0], a[5]), a[10]),
a[15]), a[20]);
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
if (feof (stream))
goto process_partial_block;
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
return numname_table[i].num;
{
- char *endp;
int rtmin = SIGRTMIN;
int rtmax = SIGRTMAX;
if (0 < rtmin && strncmp (signame, "RTMIN", 5) == 0)
{
+ char *endp;
long int n = strtol (signame + 5, &endp, 10);
if (! *endp && 0 <= n && n <= rtmax - rtmin)
return rtmin + n;
}
else if (0 < rtmax && strncmp (signame, "RTMAX", 5) == 0)
{
+ char *endp;
long int n = strtol (signame + 5, &endp, 10);
if (! *endp && rtmin - rtmax <= n && n <= 0)
return rtmax + n;
{
int rtmin = SIGRTMIN;
int rtmax = SIGRTMAX;
- int base, delta;
if (! (rtmin <= signum && signum <= rtmax))
return -1;
+ int base;
if (signum <= rtmin + (rtmax - rtmin) / 2)
{
strcpy (signame, "RTMIN");
base = rtmax;
}
- delta = signum - base;
+ int delta = signum - base;
if (delta != 0)
sprintf (signame + 5, "%+d", delta);
return 0;
static void
sigaction_handler (int sig)
{
- handler_t handler;
- sigset_t mask;
- sigset_t oldmask;
int saved_errno = errno;
if (sig < 0 || NSIG <= sig || !action_array[sig].sa_handler)
{
asynchronous instance of the same signal occurring before we
reinstall the handler will trigger the default handler; oh
well. */
- handler = action_array[sig].sa_handler;
+ handler_t handler = action_array[sig].sa_handler;
if ((action_array[sig].sa_flags & SA_RESETHAND) == 0)
signal (sig, sigaction_handler);
else
action_array[sig].sa_handler = NULL;
/* Block appropriate signals. */
- mask = action_array[sig].sa_mask;
+ sigset_t mask = action_array[sig].sa_mask;
if ((action_array[sig].sa_flags & SA_NODEFER) == 0)
sigaddset (&mask, sig);
+ sigset_t oldmask;
sigprocmask (SIG_BLOCK, &mask, &oldmask);
/* Invoke the user's handler, then restore prior mask. */
sigaction (int sig, const struct sigaction *restrict act,
struct sigaction *restrict oact)
{
- sigset_t mask;
- sigset_t oldmask;
- int saved_errno;
-
if (sig < 0 || NSIG <= sig || sig == SIGKILL || sig == SIGSTOP
|| (act && act->sa_handler == SIG_ERR))
{
replacement does not try to use sigaction() from its handler. */
if (!act && !oact)
return 0;
+ sigset_t mask;
sigfillset (&mask);
+ sigset_t oldmask;
sigprocmask (SIG_BLOCK, &mask, &oldmask);
if (oact)
{
return 0;
failure:
- saved_errno = errno;
- sigprocmask (SIG_SETMASK, &oldmask, NULL);
- errno = saved_errno;
- return -1;
+ {
+ int saved_errno = errno;
+ sigprocmask (SIG_SETMASK, &oldmask, NULL);
+ errno = saved_errno;
+ return -1;
+ }
}
sigpending (sigset_t *set)
{
sigset_t pending = 0;
-
for (int sig = 0; sig < NSIG; sig++)
if (pending_array[sig])
pending |= 1U << sig;
+
*set = pending;
return 0;
}
if (set != NULL)
{
sigset_t new_blocked_set;
- sigset_t to_unblock;
- sigset_t to_block;
-
switch (operation)
{
case SIG_BLOCK:
errno = EINVAL;
return -1;
}
- to_unblock = blocked_set & ~new_blocked_set;
- to_block = new_blocked_set & ~blocked_set;
+
+ sigset_t to_unblock = blocked_set & ~new_blocked_set;
+ sigset_t to_block = new_blocked_set & ~blocked_set;
if (to_block != 0)
for (int sig = 0; sig < NSIG; sig++)
if (stack_top)
{
/* Determine stack bounds. */
- int saved_errno;
+ int saved_errno = errno;
struct vma_struct vma;
- int ret;
-
- saved_errno = errno;
- ret = sigsegv_get_vma (stack_top, &vma);
+ int ret = sigsegv_get_vma (stack_top, &vma);
errno = saved_errno;
if (ret >= 0)
{
/* Heuristic BC: If the stack size has reached its maximal size,
and old_sp is near the low end, we consider it a stack
overflow. */
- struct rlimit rl;
-
saved_errno = errno;
+ struct rlimit rl;
ret = getrlimit (RLIMIT_STACK, &rl);
errno = saved_errno;
if (ret >= 0)
if (stack_top)
{
/* Determine stack bounds. */
- int saved_errno;
+ int saved_errno = errno;
struct vma_struct vma;
- int ret;
-
- saved_errno = errno;
- ret = sigsegv_get_vma (stack_top, &vma);
+ int ret = sigsegv_get_vma (stack_top, &vma);
errno = saved_errno;
if (ret >= 0)
{
/* Heuristic BC: If the stack size has reached its maximal size,
and old_sp is near the low end, we consider it a stack
overflow. */
- struct rlimit rl;
-
saved_errno = errno;
+ struct rlimit rl;
ret = getrlimit (RLIMIT_STACK, &rl);
errno = saved_errno;
if (ret >= 0)
long double
kernel_sinl (long double x, long double y, int iy)
{
- long double h, l, z, sin_l, cos_l_m1;
- int index, sign;
-
- sign = 1;
+ int sign = 1;
if (x < 0)
{
x = -x;
if (!((int) x))
return x * sign; /* generate inexact */
- z = x * x;
+ long double z = x * x;
return (x + x * (z * (SIN1 + z *
(SIN2 + z *
(SIN3 + z *
sinl(k+l) = sinl(k)cosl(l) + cosl(k)sinl(l).
Furthermore write k = 0.1484375 + h. */
x -= 0.1484375L;
- index = (int) (x * 128L + 0.5L);
- h = index / 128.0L;
+ int index = (int) (x * 128L + 0.5L);
+ long double h = index / 128.0L;
+ long double l;
if (iy)
l = y - (h - x);
else
l = x - h;
- z = l * l;
- sin_l =
+ long double z = l * l;
+ long double sin_l =
l * (ONE +
z * (SSIN1 +
z * (SSIN2 + z * (SSIN3 + z * (SSIN4 + z * SSIN5)))));
- cos_l_m1 =
+ long double cos_l_m1 =
z * (SCOS1 + z * (SCOS2 + z * (SCOS3 + z * (SCOS4 + z * SCOS5))));
index *= 4;
long double
kernel_cosl (long double x, long double y)
{
- long double h, l, z, sin_l, cos_l_m1;
- int index;
-
if (x < 0)
x = -x;
if (x < 0.000000000000000006938893903907228377647697925567626953125L) /* |x| < 2^-57 */
if (!((int) x))
return ONE; /* generate inexact */
- z = x * x;
+ long double z = x * x;
return ONE + (z * (COS1 + z * (COS2 + z * (COS3 + z * (COS4 +
z * (COS5 +
z * (COS6 +
cosl(k+l) = cosl(k)cosl(l) - sinl(k)sinl(l).
Furthermore write k = 0.1484375 + h. */
x -= 0.1484375L;
- index = (int) (x * 128L + 0.5L);
- h = index / 128.0L;
- l = y - (h - x);
- z = l * l;
- sin_l =
+ int index = (int) (x * 128L + 0.5L);
+ long double h = index / 128.0L;
+ long double l = y - (h - x);
+ long double z = l * l;
+ long double sin_l =
l * (ONE +
z * (SSIN1 +
z * (SSIN2 + z * (SSIN3 + z * (SSIN4 + z * SSIN5)))));
- cos_l_m1 =
+ long double cos_l_m1 =
z * (SCOS1 + z * (SCOS2 + z * (SCOS3 + z * (SCOS4 + z * SCOS5))));
index *= 4;
long double
sinl (long double x)
{
- long double y[2], z = 0.0L;
- int n;
-
/* sinl(NaN) is NaN */
if (isnanl (x))
return x;
/* |x| ~< pi/4 */
if (x >= -0.7853981633974483096156608458198757210492
&& x <= 0.7853981633974483096156608458198757210492)
- return kernel_sinl (x, z, 0);
+ {
+ long double z = 0.0L;
+ return kernel_sinl (x, z, 0);
+ }
/* sinl(Inf) is NaN, sinl(0) is 0 */
else if (x + x == x)
/* argument reduction needed */
else
{
- n = ieee754_rem_pio2l (x, y);
+ long double y[2];
+ int n = ieee754_rem_pio2l (x, y);
switch (n & 3)
{
case 0:
const unsigned int limit = 24 * 24 * 60 * 60;
while (limit < seconds)
{
- unsigned int result;
seconds -= limit;
- result = sleep (limit);
+ unsigned int result = sleep (limit);
if (result)
return seconds + result;
}
int
sm3_stream (FILE *stream, void *resblock)
{
- struct sm3_ctx ctx;
- size_t sum;
-
char *buffer = malloc (BLOCKSIZE + 72);
if (!buffer)
return 1;
/* Initialize the computation context. */
+ struct sm3_ctx ctx;
sm3_init_ctx (&ctx);
+ size_t sum;
+
/* Iterate over full file contents. */
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
- size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
while (1)
{
- n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
+ size_t n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
if (++j) \
dbg_printf("%2d %08x %08x %08x %08x %08x %08x %08x %08x\n", \
j-1, A, B, C, D, E, F, G, H); \
- ss1 = rol(rol(A,12) + E + T,7); \
- ss2 = ss1 ^ rol(A,12); \
+ uint32_t ss1 = rol(rol(A,12) + E + T,7); \
+ uint32_t ss2 = ss1 ^ rol(A,12); \
D += FF##i(A,B,C) + ss2 + (W1 ^ W2); \
H += GG##i(E,F,G) + ss1 + W1; \
B = rol(B,9); \
while (words < endp)
{
- uint32_t tw;
- uint32_t ss1, ss2;
-
for (int j = 0; j < 16; j++)
{
x[j] = SWAP (*words);
" %08x %08x %08x %08x %08x %08x %08x %08x\n",
a, b, c, d, e, f, g, h);
+ uint32_t tw;
+
R1( a, b, c, d, e, f, g, h, T( 0), W1( 0), W1( 4) );
R1( d, a, b, c, h, e, f, g, T( 1), W1( 1), W1( 5) );
R1( c, d, a, b, g, h, e, f, T( 2), W1( 2), W1( 6) );
snprintf (char *str, size_t size, const char *format, ...)
{
va_list args;
- ptrdiff_t ret;
-
va_start (args, format);
- ret = vsnzprintf (str, size, format, args);
+ ptrdiff_t ret = vsnzprintf (str, size, format, args);
va_end (args);
#if PTRDIFF_MAX > INT_MAX
ptrdiff_t
snzprintf (char *str, size_t size, const char *format, ...)
{
- char *output;
- size_t len;
- size_t lenbuf = size;
va_list args;
-
va_start (args, format);
- output = vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+
+ size_t lenbuf = size;
+ char *output = vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
+
va_end (args);
if (!output)
int
rpl_socket (int domain, int type, int protocol)
{
- SOCKET fh;
-
gl_sockets_startup (SOCKETS_1_1);
/* We have to use WSASocket() to create non-overlapped IO sockets.
Overlapped IO sockets cannot be used with read/write. */
- fh = WSASocket (domain, type, protocol, NULL, 0, 0);
+ SOCKET fh = WSASocket (domain, type, protocol, NULL, 0, 0);
if (fh == INVALID_SOCKET)
{
our calls to closesocket() and the primary close(), some other thread
could make system calls that allocate precisely the same HANDLE value
as sock; then the primary close() would call CloseHandle() on it. */
- SOCKET sock;
- WSANETWORKEVENTS ev;
/* Test whether fd refers to a socket. */
- sock = FD_TO_SOCKET (fd);
+ SOCKET sock = FD_TO_SOCKET (fd);
+ WSANETWORKEVENTS ev;
ev.lNetworkEvents = 0xDEADBEEF;
WSAEnumNetworkEvents (sock, NULL, &ev);
if (ev.lNetworkEvents != 0xDEADBEEF)
gl_ioctl_fn primary,
int fd, int request, void *arg)
{
- SOCKET sock;
- WSANETWORKEVENTS ev;
-
/* Test whether fd refers to a socket. */
- sock = FD_TO_SOCKET (fd);
+ SOCKET sock = FD_TO_SOCKET (fd);
+ WSANETWORKEVENTS ev;
ev.lNetworkEvents = 0xDEADBEEF;
WSAEnumNetworkEvents (sock, NULL, &ev);
if (ev.lNetworkEvents != 0xDEADBEEF)
if (version > initialized_sockets_version)
{
WSADATA data;
- int err;
-
- err = WSAStartup (version, &data);
+ int err = WSAStartup (version, &data);
if (err != 0)
return 1;
gl_sockets_cleanup (void)
{
#if WINDOWS_SOCKETS
- int err;
-
initialized_sockets_version = 0;
unregister_fd_hook (&fd_sockets_hook);
- err = WSACleanup ();
+ int err = WSACleanup ();
if (err != 0)
return 1;
#endif
#else
/* Unix API. */
- char **child_environ;
- char **malloced_environ;
- sigset_t blocked_signals;
- posix_spawn_file_actions_t actions;
- bool actions_allocated;
- posix_spawnattr_t attrs;
- bool attrs_allocated;
- int err;
- pid_t child;
- child_environ = environ;
- malloced_environ = NULL;
+ char **child_environ = environ;
+ char **malloced_environ = NULL;
# if defined _WIN32 || defined __CYGWIN__
if (dll_dirs != NULL && dll_dirs[0] != NULL)
{
}
# endif
+ sigset_t blocked_signals;
if (slave_process)
{
sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
block_fatal_signals ();
}
- actions_allocated = false;
- attrs_allocated = false;
+
+ posix_spawn_file_actions_t actions;
+ bool actions_allocated = false;
+ posix_spawnattr_t attrs;
+ bool attrs_allocated = false;
+
+ int err;
+ pid_t child;
if ((err = posix_spawn_file_actions_init (&actions)) != 0
|| (actions_allocated = true,
(pipe_stdin
Linux/ppc64, Linux/ppc64le, and Solaris/SPARC, it causes a SIGBUS or
SIGSEGV when done in the child process after vfork() and when $PATH is long
(ca. 4 KB or so). */
- char *path, *name;
+ char *path;
+ char *name;
if (use_path)
{
/* We have to search for FILE on the path. */
sprintf (char *str, const char *format, ...)
{
va_list args;
- ptrdiff_t ret;
-
va_start (args, format);
- ret = vszprintf (str, format, args);
+ ptrdiff_t ret = vszprintf (str, format, args);
va_end (args);
#if PTRDIFF_MAX > INT_MAX
long double
sqrtl (long double x)
{
- long double delta, y;
- int exponent;
-
/* Check for NaN */
if (isnanl (x))
return x;
if (x + x == x)
return x;
+ int exponent;
frexpl (x, &exponent);
- y = ldexpl (x, -exponent / 2);
+ long double y = ldexpl (x, -exponent / 2);
+ long double delta;
do
{
delta = y;
static inline uintptr_t
allocate_block_from_pool (size_t size, struct page_pool *pool)
{
- uintptr_t page;
-
/* Try in the last used page first. */
- page = pool->last_page;
- if (likely (page != 0))
- {
- uintptr_t block = pool->allocate_block_in_page (size, page);
- if (likely (block != 0))
- {
- add_update (page, pool);
- return block;
- }
- }
+ {
+ uintptr_t page = pool->last_page;
+ if (likely (page != 0))
+ {
+ uintptr_t block = pool->allocate_block_in_page (size, page);
+ if (likely (block != 0))
+ {
+ add_update (page, pool);
+ return block;
+ }
+ }
+ }
/* Ensure that the pool and its managed_pages is initialized. */
if (unlikely (pool->managed_pages == NULL))
while (gl_oset_iterator_next (&iter, &elt))
{
struct page_tree_element *element = (struct page_tree_element *) elt;
- page = element->page;
+ uintptr_t page = element->page;
/* No need to try the last used page again. */
if (likely (page != pool->last_page))
{
gl_oset_iterator_free (&iter);
}
+ uintptr_t page;
+
/* If we have a freeable page ready for reuse, use it. */
if (pool->freeable_page != 0)
{
static int
rof_open (struct rofile *rof, const char *filename)
{
- int fd;
- uintptr_t pagesize;
- size_t size;
-
- fd = open (filename, O_RDONLY);
+ int fd = open (filename, O_RDONLY);
if (fd < 0)
return -1;
rof->position = 0;
rof->eof_seen = 0;
/* Try the static buffer first. */
- pagesize = 0;
+ uintptr_t pagesize = 0;
rof->buffer = rof->stack_allocated_buffer;
- size = sizeof (rof->stack_allocated_buffer);
+ size_t size = sizeof (rof->stack_allocated_buffer);
rof->auxmap = NULL;
rof->auxmap_start = 0;
rof->auxmap_end = 0;
for (;;)
{
- uintptr_t start, end;
- int c;
-
/* Parse one line. First start and end. */
+ uintptr_t start, end;
if (!(rof_scanf_lx (&rof, &start) >= 0
&& rof_getchar (&rof) == '-'
&& rof_scanf_lx (&rof, &end) >= 0))
break;
- while (c = rof_getchar (&rof), c != -1 && c != '\n')
- ;
+
+ {
+ int c;
+ while (c = rof_getchar (&rof), c != -1 && c != '\n')
+ ;
+ }
if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
{
for (;;)
{
- uintptr_t start, end;
- int c;
-
/* Parse one line. First start. */
+ uintptr_t start;
if (!(rof_getchar (&rof) == '0'
&& rof_getchar (&rof) == 'x'
&& rof_scanf_lx (&rof, &start) >= 0))
break;
- while (c = rof_peekchar (&rof), c == ' ' || c == '\t')
- rof_getchar (&rof);
+ {
+ int c;
+ while (c = rof_peekchar (&rof), c == ' ' || c == '\t')
+ rof_getchar (&rof);
+ }
/* Then end. */
+ uintptr_t end;
if (!(rof_getchar (&rof) == '0'
&& rof_getchar (&rof) == 'x'
&& rof_scanf_lx (&rof, &end) >= 0))
break;
- while (c = rof_getchar (&rof), c != -1 && c != '\n')
- ;
+ {
+ int c;
+ while (c = rof_getchar (&rof), c != -1 && c != '\n')
+ ;
+ }
if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
{
{
/* Documentation: https://www.freebsd.org/cgi/man.cgi?sysctl(3) */
int info_path[] = { CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, getpid () };
- size_t len;
- size_t pagesize;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- char *mem;
- char *p;
- char *p_end;
-
- len = 0;
+ size_t len = 0;
if (sysctl (info_path, 4, NULL, &len, NULL, 0) < 0)
return -1;
/* Allow for small variations over time. In a multithreaded program
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
- pagesize = getpagesize ();
- memneed = len;
+ size_t pagesize = getpagesize ();
+ size_t memneed = len;
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
return -1;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- mem = (char *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ char *mem = (char *) auxmap;
if (sysctl (info_path, 4, mem, &len, NULL, 0) < 0)
{
munmap (auxmap, memneed);
return -1;
}
- p = mem;
- p_end = mem + len;
- while (p < p_end)
- {
- struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
- unsigned long start = kve->kve_start;
- unsigned long end = kve->kve_end;
- if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
- {
- /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
- = [start,auxmap_start-1] u [auxmap_end,end-1]. */
- if (start < auxmap_start)
- if (callback (locals, start, auxmap_start))
- break;
- if (auxmap_end - 1 < end - 1)
- if (callback (locals, auxmap_end, end))
+ {
+ char *p = mem;
+ char *p_end = mem + len;
+ while (p < p_end)
+ {
+ struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
+ unsigned long start = kve->kve_start;
+ unsigned long end = kve->kve_end;
+ if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
+ {
+ /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
+ = [start,auxmap_start-1] u [auxmap_end,end-1]. */
+ if (start < auxmap_start)
+ if (callback (locals, start, auxmap_start))
+ break;
+ if (auxmap_end - 1 < end - 1)
+ if (callback (locals, auxmap_end, end))
+ break;
+ }
+ else
+ {
+ if (callback (locals, start, end))
break;
- }
- else
- {
- if (callback (locals, start, end))
- break;
- }
- p += kve->kve_structsize;
- }
+ }
+ p += kve->kve_structsize;
+ }
+ }
munmap (auxmap, memneed);
return 0;
}
}
for (;;)
{
- uintptr_t halfstepsize1;
- uintptr_t halfstepsize2;
-
if (stepsize == 1)
return addr;
/* Here we know that less than stepsize pages exist starting at addr. */
- halfstepsize1 = (stepsize + 1) / 2;
- halfstepsize2 = stepsize / 2;
+ uintptr_t halfstepsize1 = (stepsize + 1) / 2;
+ uintptr_t halfstepsize2 = stepsize / 2;
/* halfstepsize1 + halfstepsize2 = stepsize. */
if (mincore ((MINCORE_ADDR_T) (addr - halfstepsize1 * pagesize),
addr += pagesize;
for (;;)
{
- uintptr_t max_remaining;
-
if (addr == 0) /* wrapped around? */
return addr;
- max_remaining = (- addr) / pagesize;
+ uintptr_t max_remaining = (- addr) / pagesize;
if (stepsize > max_remaining)
stepsize = max_remaining;
if (mincore ((MINCORE_ADDR_T) addr, stepsize * pagesize, vec) < 0)
}
for (;;)
{
- uintptr_t halfstepsize1;
- uintptr_t halfstepsize2;
-
if (stepsize == 1)
return addr;
/* Here we know that less than stepsize pages exist starting at addr. */
- halfstepsize1 = (stepsize + 1) / 2;
- halfstepsize2 = stepsize / 2;
+ uintptr_t halfstepsize1 = (stepsize + 1) / 2;
+ uintptr_t halfstepsize2 = stepsize / 2;
/* halfstepsize1 + halfstepsize2 = stepsize. */
if (mincore ((MINCORE_ADDR_T) addr, halfstepsize1 * pagesize, vec) < 0)
static int
is_unmapped (uintptr_t addr1, uintptr_t addr2)
{
- uintptr_t count;
- uintptr_t stepsize;
-
/* Round addr1 down. */
addr1 = (addr1 / pagesize) * pagesize;
/* Round addr2 up and turn it into an exclusive bound. */
average, therefore we have good chances of hitting a mapped area if we
traverse only every second, or only fourth page, etc. This doesn't
decrease the worst-case runtime, only the average runtime. */
- count = (addr2 - addr1) / pagesize;
+ uintptr_t count = (addr2 - addr1) / pagesize;
/* We have to test is_mapped (addr1 + i * pagesize) for 0 <= i < count. */
+ uintptr_t stepsize;
for (stepsize = 1; stepsize < count; )
stepsize = 2 * stepsize;
for (;;)
{
- uintptr_t addr_stepsize;
- uintptr_t i;
- uintptr_t addr;
-
stepsize = stepsize / 2;
if (stepsize == 0)
break;
- addr_stepsize = stepsize * pagesize;
+ uintptr_t addr_stepsize = stepsize * pagesize;
+ uintptr_t i;
+ uintptr_t addr;
for (i = stepsize, addr = addr1 + addr_stepsize;
i < count;
i += 2 * stepsize, addr += 2 * addr_stepsize)
static uintptr_t
mapped_range_start (uintptr_t addr)
{
- uintptr_t stepsize;
- uintptr_t known_unmapped_page;
-
/* Look at smaller addresses, in larger and larger steps, to minimize the
number of mquery() calls. */
- stepsize = pagesize;
+ uintptr_t known_unmapped_page;
+ uintptr_t stepsize = pagesize;
for (;;)
{
- uintptr_t hole;
-
if (addr == 0)
abort ();
break;
}
- hole = (uintptr_t) mquery ((void *) (addr - stepsize), pagesize,
- 0, 0, -1, 0);
+ uintptr_t hole = (uintptr_t) mquery ((void *) (addr - stepsize), pagesize,
+ 0, 0, -1, 0);
if (!(hole == (uintptr_t) (void *) -1 || hole >= addr))
{
/* Some part of [addr - stepsize, addr - 1] is unmapped. */
/* Still 0 < addr - known_unmapped_page <= stepsize. */
while (stepsize > pagesize)
{
- uintptr_t hole;
-
stepsize = stepsize / 2;
- hole = (uintptr_t) mquery ((void *) (addr - stepsize), pagesize,
- 0, 0, -1, 0);
+ uintptr_t hole = (uintptr_t) mquery ((void *) (addr - stepsize), pagesize,
+ 0, 0, -1, 0);
if (!(hole == (uintptr_t) (void *) -1 || hole >= addr))
/* Some part of [addr - stepsize, addr - 1] is unmapped. */
known_unmapped_page = hole;
static uintptr_t
mapped_range_end (uintptr_t addr)
{
- uintptr_t end;
-
if (addr == 0)
abort ();
- end = (uintptr_t) mquery ((void *) addr, pagesize, 0, 0, -1, 0);
+ uintptr_t end = (uintptr_t) mquery ((void *) addr, pagesize, 0, 0, -1, 0);
if (end == (uintptr_t) (void *) -1)
end = 0; /* wrap around */
return end;
only the virtual memory areas that are connected to a file, not the
anonymous ones. But at least since AIX 7.1, it is well usable. */
- char fnamebuf[6+10+4+1];
- char *fname;
- int fd;
- size_t memneed;
-
if (pagesize == 0)
init_pagesize ();
+ char fnamebuf[6+10+4+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u/map", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - (4+1);
+ char *fname = fnamebuf + sizeof (fnamebuf) - (4+1);
memcpy (fname, "/map", 4+1);
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY | O_CLOEXEC);
+ int fd = open (fname, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
We read the entire contents, but look only at the prmap_t entries and
ignore the tail part. */
- for (memneed = 2 * pagesize; ; memneed = 2 * memneed)
+ for (size_t memneed = 2 * pagesize; ; memneed = 2 * memneed)
{
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
So use mmap(), and ignore the resulting VMA if it occurs among the
resulting VMAs. (Normally it doesn't, because it was allocated after
the open() call.) */
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- ssize_t nbytes;
-
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
{
close (fd);
return -1;
}
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
/* Read the contents of /proc/<pid>/map in a single system call.
This guarantees a consistent result (no duplicated or omitted
entries). */
- retry:
+ retry: ;
+ ssize_t nbytes;
do
nbytes = read (fd, auxmap, memneed);
while (nbytes < 0 && errno == EINTR);
}
/* We now have the entire contents of /proc/<pid>/map in memory. */
- prmap_t* maps = (prmap_t *) auxmap;
+ prmap_t *maps = (prmap_t *) auxmap;
/* The entries are not sorted by address. Therefore
1. Extract the relevant information into an array.
vma_t *vmas = (vma_t *) auxmap;
vma_t *vp = vmas;
- {
- prmap_t* mp;
- for (mp = maps;;)
- {
- unsigned long start, end;
-
- start = (unsigned long) mp->pr_vaddr;
- end = start + mp->pr_size;
- if (start == 0 && end == 0 && mp->pr_mflags == 0)
- break;
- /* Discard empty VMAs and kernel VMAs. */
- if (start < end && (mp->pr_mflags & MA_KERNTEXT) == 0)
- {
- if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
- {
- /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
- = [start,auxmap_start-1] u [auxmap_end,end-1]. */
- if (start < auxmap_start)
- {
- vp->start = start;
- vp->end = auxmap_start;
- vp++;
- }
- if (auxmap_end - 1 < end - 1)
- {
- vp->start = auxmap_end;
- vp->end = end;
- vp++;
- }
- }
- else
- {
- vp->start = start;
- vp->end = end;
- vp++;
- }
- }
- mp++;
- }
- }
+ for (prmap_t *mp = maps;;)
+ {
+ unsigned long start = (unsigned long) mp->pr_vaddr;
+ unsigned long end = start + mp->pr_size;
+ if (start == 0 && end == 0 && mp->pr_mflags == 0)
+ break;
+ /* Discard empty VMAs and kernel VMAs. */
+ if (start < end && (mp->pr_mflags & MA_KERNTEXT) == 0)
+ {
+ if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
+ {
+ /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
+ = [start,auxmap_start-1] u [auxmap_end,end-1]. */
+ if (start < auxmap_start)
+ {
+ vp->start = start;
+ vp->end = auxmap_start;
+ vp++;
+ }
+ if (auxmap_end - 1 < end - 1)
+ {
+ vp->start = auxmap_end;
+ vp->end = end;
+ vp++;
+ }
+ }
+ else
+ {
+ vp->start = start;
+ vp->end = end;
+ vp++;
+ }
+ }
+ mp++;
+ }
size_t nvmas = vp - vmas;
/* Sort the array in ascending order.
Insertion-sort is OK in this case, despite its worst-case running
time of O(N²), since the number of VMAs will rarely be larger than
1000. */
- {
- size_t i;
- for (i = 1; i < nvmas; i++)
- {
- /* Invariant: Here vmas[0..i-1] is sorted. */
- size_t j;
- for (j = i; j > 0 && vmas[j - 1].start > vmas[j].start; j--)
- {
- vma_t tmp = vmas[j - 1];
- vmas[j - 1] = vmas[j];
- vmas[j] = tmp;
- }
- /* Invariant: Here vmas[0..i] is sorted. */
- }
- }
+ for (size_t i = 1; i < nvmas; i++)
+ {
+ /* Invariant: Here vmas[0..i-1] is sorted. */
+ for (size_t j = i; j > 0 && vmas[j - 1].start > vmas[j].start; j--)
+ {
+ vma_t tmp = vmas[j - 1];
+ vmas[j - 1] = vmas[j];
+ vmas[j] = tmp;
+ }
+ /* Invariant: Here vmas[0..i] is sorted. */
+ }
/* Invoke the callback. */
- {
- size_t i;
- for (i = 0; i < nvmas; i++)
- {
- vma_t *vpi = &vmas[i];
- if (callback (locals, vpi->start, vpi->end))
- break;
- }
- }
+ for (size_t i = 0; i < nvmas; i++)
+ {
+ vma_t *vpi = &vmas[i];
+ if (callback (locals, vpi->start, vpi->end))
+ break;
+ }
munmap (auxmap, memneed);
break;
# if defined PIOCNMAP && defined PIOCMAP
/* We must use the older /proc interface. */
- char fnamebuf[6+10+1];
- char *fname;
- int fd;
- int nmaps;
- size_t memneed;
- void *auxmap;
- uintptr_t auxmap_start;
- uintptr_t auxmap_end;
- prmap_t* maps;
- prmap_t* mp;
-
if (pagesize == 0)
init_pagesize ();
+ char fnamebuf[6+10+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - 1;
+ char *fname = fnamebuf + sizeof (fnamebuf) - 1;
*fname = '\0';
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY);
+ int fd = open (fname, O_RDONLY);
if (fd < 0)
return -1;
+ int nmaps;
if (ioctl (fd, PIOCNMAP, &nmaps) < 0)
goto fail2;
- memneed = (nmaps + 10) * sizeof (prmap_t);
+ size_t memneed = (nmaps + 10) * sizeof (prmap_t);
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
goto fail2;
- auxmap_start = (uintptr_t) auxmap;
- auxmap_end = auxmap_start + memneed;
- maps = (prmap_t *) auxmap;
+ uintptr_t auxmap_start = (uintptr_t) auxmap;
+ uintptr_t auxmap_end = auxmap_start + memneed;
+ prmap_t *maps = (prmap_t *) auxmap;
if (ioctl (fd, PIOCMAP, maps) < 0)
goto fail1;
- for (mp = maps;;)
+ for (prmap_t *mp = maps;;)
{
- uintptr_t start, end;
-
- start = (uintptr_t) mp->pr_vaddr;
- end = start + mp->pr_size;
+ uintptr_t start = (uintptr_t) mp->pr_vaddr;
+ uintptr_t end = start + mp->pr_size;
if (start == 0 && end == 0)
break;
mp++;
prmap_t. These are different in 32-bit and 64-bit processes,
but here we are fortunately accessing only the current process. */
- char fnamebuf[6+10+4+1];
- char *fname;
- int fd;
- int nmaps;
- size_t memneed;
- void *auxmap;
- uintptr_t auxmap_start;
- uintptr_t auxmap_end;
- prmap_t* maps;
- prmap_t* maps_end;
- prmap_t* mp;
-
if (pagesize == 0)
init_pagesize ();
+ char fnamebuf[6+10+4+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u/map", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - 1 - 4;
+ char *fname = fnamebuf + sizeof (fnamebuf) - 1 - 4;
memcpy (fname, "/map", 4 + 1);
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY);
+ int fd = open (fname, O_RDONLY);
if (fd < 0)
return -1;
+ int nmaps;
{
struct stat statbuf;
if (fstat (fd, &statbuf) < 0)
nmaps = statbuf.st_size / sizeof (prmap_t);
}
- memneed = (nmaps + 10) * sizeof (prmap_t);
+ size_t memneed = (nmaps + 10) * sizeof (prmap_t);
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
goto fail2;
- auxmap_start = (uintptr_t) auxmap;
- auxmap_end = auxmap_start + memneed;
- maps = (prmap_t *) auxmap;
+ uintptr_t auxmap_start = (uintptr_t) auxmap;
+ uintptr_t auxmap_end = auxmap_start + memneed;
+ prmap_t *maps = (prmap_t *) auxmap;
/* Read up to memneed bytes from fd into maps. */
+ prmap_t *maps_end;
{
size_t remaining = memneed;
size_t total_read = 0;
maps_end = maps + nmaps;
}
- for (mp = maps; mp < maps_end; mp++)
+ for (prmap_t *mp = maps; mp < maps_end; mp++)
{
uintptr_t start, end;
static int
vma_iterate (struct callback_locals *locals)
{
+ ssize_t cookie = 0;
area_info info;
- ssize_t cookie;
-
- cookie = 0;
while (get_next_area_info (0, &cookie, &info) == B_OK)
{
- uintptr_t start, end;
-
- start = (uintptr_t) info.address;
- end = start + info.size;
+ uintptr_t start = (uintptr_t) info.address;
+ uintptr_t end = start + info.size;
if (callback (locals, start, end))
break;
struct timespec
_gl_convert_FILETIME_to_timespec (const FILETIME *ft)
{
- struct timespec result;
/* FILETIME: <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-filetime> */
unsigned long long since_1601 =
((unsigned long long) ft->dwHighDateTime << 32)
| (unsigned long long) ft->dwLowDateTime;
+ struct timespec result;
if (since_1601 == 0)
{
result.tv_sec = 0;
gl_consolesafe_fprintf (FILE *restrict fp, const char *restrict format, ...)
{
va_list args;
- char *tmpstring;
va_start (args, format);
+ char *tmpstring;
int result = vasprintf (&tmpstring, format, args);
va_end (args);
if (result >= 0)
gl_consolesafe_printf (const char *restrict format, ...)
{
va_list args;
- char *tmpstring;
va_start (args, format);
+ char *tmpstring;
int result = vasprintf (&tmpstring, format, args);
va_end (args);
if (result >= 0)
return (EXPRESSION); \
else \
{ \
- RETTYPE ret; \
SetLastError (0); \
- ret = (EXPRESSION); \
+ RETTYPE ret = (EXPRESSION); \
if (FAILED) \
{ \
if (GetLastError () == ERROR_NO_DATA && ferror (stream)) \
int
scanf (const char *format, ...)
{
- int retval;
va_list args;
-
va_start (args, format);
- retval = vfscanf (stdin, format, args);
+ int retval = vfscanf (stdin, format, args);
va_end (args);
return retval;
int
fscanf (FILE *stream, const char *format, ...)
{
- int retval;
va_list args;
-
va_start (args, format);
- retval = vfscanf (stream, format, args);
+ int retval = vfscanf (stream, format, args);
va_end (args);
return retval;
return (EXPRESSION); \
else \
{ \
- RETTYPE ret; \
CLEAR_ERRNO \
CLEAR_LastError \
- ret = (EXPRESSION); \
+ RETTYPE ret = (EXPRESSION); \
if (FAILED) \
{ \
HANDLE_ENOSPC \
int
printf (const char *format, ...)
{
- int retval;
va_list args;
-
va_start (args, format);
- retval = vfprintf (stdout, format, args);
+ int retval = vfprintf (stdout, format, args);
va_end (args);
return retval;
int
fprintf (FILE *stream, const char *format, ...)
{
- int retval;
va_list args;
-
va_start (args, format);
- retval = vfprintf (stream, format, args);
+ int retval = vfprintf (stream, format, args);
va_end (args);
return retval;
char *
(__stpncpy) (char *dest, const char *src, size_t n)
{
- char c;
char *s = dest;
if (n >= 4)
for (;;)
{
- c = *src++;
- *dest++ = c;
- if (c == '\0')
- break;
- c = *src++;
- *dest++ = c;
- if (c == '\0')
- break;
- c = *src++;
- *dest++ = c;
- if (c == '\0')
- break;
- c = *src++;
- *dest++ = c;
- if (c == '\0')
- break;
+ {
+ char c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ }
+ {
+ char c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ }
+ {
+ char c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ }
+ {
+ char c = *src++;
+ *dest++ = c;
+ if (c == '\0')
+ break;
+ }
if (--n4 == 0)
goto last_chars;
}
for (;;)
{
- c = *src++;
+ char c = *src++;
--n;
*dest++ = c;
if (c == '\0')
/* Search, using the table to accelerate the processing. */
{
- size_t j;
- const UNIT *rhaystack;
- const UNIT *phaystack;
-
*resultp = NULL;
- j = 0;
- rhaystack = haystack;
- phaystack = haystack;
+ size_t j = 0;
+ const UNIT *rhaystack = haystack;
+ const UNIT *phaystack = haystack;
/* Invariant: phaystack = rhaystack + j. */
while (*phaystack != 0)
if (CANON_ELEMENT (needle[j]) == CANON_ELEMENT (*phaystack))
critical_factorization (const unsigned char *needle, size_t needle_len,
size_t *period)
{
- /* Index of last byte of left half, or SIZE_MAX. */
- size_t max_suffix, max_suffix_rev;
- size_t j; /* Index into NEEDLE for current candidate suffix. */
- size_t k; /* Offset into current period. */
- size_t p; /* Intermediate period. */
- unsigned char a, b; /* Current comparison bytes. */
-
/* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered
out 0-length needles. */
if (needle_len < 3)
*/
/* Perform lexicographic search. */
- max_suffix = SIZE_MAX;
- j = 0;
- k = p = 1;
- while (j + k < needle_len)
- {
- a = CANON_ELEMENT (needle[j + k]);
- b = CANON_ELEMENT (needle[max_suffix + k]);
- if (a < b)
- {
- /* Suffix is smaller, period is entire prefix so far. */
- j += k;
- k = 1;
- p = j - max_suffix;
- }
- else if (a == b)
- {
- /* Advance through repetition of the current period. */
- if (k != p)
- ++k;
- else
- {
- j += p;
- k = 1;
- }
- }
- else /* b < a */
- {
- /* Suffix is larger, start over from current location. */
- max_suffix = j++;
- k = p = 1;
- }
- }
- *period = p;
+ size_t max_suffix = /* Index of last byte of left half, or SIZE_MAX. */
+ SIZE_MAX;
+ {
+ size_t j = 0; /* Index into NEEDLE for current candidate suffix. */
+ size_t k = 1; /* Offset into current period. */
+ size_t p = 1; /* Intermediate period. */
+ while (j + k < needle_len)
+ {
+ unsigned char a = CANON_ELEMENT (needle[j + k]);
+ unsigned char b = CANON_ELEMENT (needle[max_suffix + k]);
+ if (a < b)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* b < a */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix = j++;
+ k = p = 1;
+ }
+ }
+ *period = p;
+ }
/* Perform reverse lexicographic search. */
- max_suffix_rev = SIZE_MAX;
- j = 0;
- k = p = 1;
- while (j + k < needle_len)
- {
- a = CANON_ELEMENT (needle[j + k]);
- b = CANON_ELEMENT (needle[max_suffix_rev + k]);
- if (b < a)
- {
- /* Suffix is smaller, period is entire prefix so far. */
- j += k;
- k = 1;
- p = j - max_suffix_rev;
- }
- else if (a == b)
- {
- /* Advance through repetition of the current period. */
- if (k != p)
- ++k;
- else
- {
- j += p;
- k = 1;
- }
- }
- else /* a < b */
- {
- /* Suffix is larger, start over from current location. */
- max_suffix_rev = j++;
- k = p = 1;
- }
- }
+ size_t max_suffix_rev = /* Index of last byte of left half, or SIZE_MAX. */
+ SIZE_MAX;
+ size_t p_rev;
+ {
+ size_t j = 0; /* Index into NEEDLE for current candidate suffix. */
+ size_t k = 1; /* Offset into current period. */
+ size_t p = 1; /* Intermediate period. */
+ while (j + k < needle_len)
+ {
+ unsigned char a = CANON_ELEMENT (needle[j + k]);
+ unsigned char b = CANON_ELEMENT (needle[max_suffix_rev + k]);
+ if (b < a)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix_rev;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* a < b */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix_rev = j++;
+ k = p = 1;
+ }
+ }
+ p_rev = p;
+ }
/* Choose the shorter suffix. Return the index of the first byte of
the right half, rather than the last byte of the left half.
factorization. */
if (max_suffix_rev + 1 < max_suffix + 1)
return max_suffix + 1;
- *period = p;
+ *period = p_rev;
return max_suffix_rev + 1;
}
two_way_short_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
- size_t i; /* Index into current byte of NEEDLE. */
- size_t j; /* Index into current window of HAYSTACK. */
- size_t period; /* The period of the right half of needle. */
- size_t suffix; /* The index of the right half of needle. */
-
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
- suffix = critical_factorization (needle, needle_len, &period);
+ size_t period; /* The period of the right half of needle. */
+ size_t suffix = /* The index of the right half of needle. */
+ critical_factorization (needle, needle_len, &period);
/* Perform the search. Each iteration compares the right half
first. */
only advance by the period, so use memory to avoid rescanning
known occurrences of the period in the right half. */
size_t memory = 0;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
- i = MAX (suffix, memory);
+ size_t i = /* Index into current byte of NEEDLE. */
+ MAX (suffix, memory);
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
period = MAX (suffix, needle_len - suffix) + 1;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
- i = suffix;
+ size_t i = /* Index into current byte of NEEDLE. */
+ suffix;
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
two_way_long_needle (const unsigned char *haystack, size_t haystack_len,
const unsigned char *needle, size_t needle_len)
{
- size_t j; /* Index into current window of HAYSTACK. */
- size_t period; /* The period of the right half of needle. */
- size_t suffix; /* The index of the right half of needle. */
- size_t shift_table[1U << CHAR_BIT]; /* See below. */
-
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
- suffix = critical_factorization (needle, needle_len, &period);
+ size_t period; /* The period of the right half of needle. */
+ size_t suffix = /* The index of the right half of needle. */
+ critical_factorization (needle, needle_len, &period);
/* Populate shift_table. For each possible byte value c,
shift_table[c] is the distance from the last occurrence of c to
the end of NEEDLE, or NEEDLE_LEN if c is absent from the NEEDLE.
shift_table[NEEDLE[NEEDLE_LEN - 1]] contains the only 0. */
+ size_t shift_table[1U << CHAR_BIT];
for (size_t i = 0; i < 1U << CHAR_BIT; i++)
shift_table[i] = needle_len;
for (size_t i = 0; i < needle_len; i++)
only advance by the period, so use memory to avoid rescanning
known occurrences of the period in the right half. */
size_t memory = 0;
- size_t shift;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
- shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
+ size_t shift =
+ shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
if (memory && shift < period)
{
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
- size_t shift;
period = MAX (suffix, needle_len - suffix) + 1;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Check the last byte first; if it does not match, then
shift to the next possible match location. */
- shift = shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
+ size_t shift =
+ shift_table[CANON_ELEMENT (haystack[j + needle_len - 1])];
if (0 < shift)
{
j += shift;
{
const unsigned char *p1 = (const unsigned char *) s1;
const unsigned char *p2 = (const unsigned char *) s2;
- unsigned char c1, c2;
if (p1 == p2)
return 0;
- do
+ for (;; p1++, p2++)
{
- c1 = tolower (*p1);
- c2 = tolower (*p2);
-
- if (c1 == '\0')
- break;
-
- ++p1;
- ++p2;
+ unsigned char c1 = tolower (*p1);
+ unsigned char c2 = tolower (*p2);
+
+ if (c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
}
# else
/* Implementation for the global locale. */
{
- int ret;
# if HAVE_WORKING_USELOCALE
locale_t saved_locale = uselocale (LC_GLOBAL_LOCALE);
# endif
- ret = strcasecmp (s1, s2);
+ int ret = strcasecmp (s1, s2);
# if HAVE_WORKING_USELOCALE
uselocale (saved_locale);
# endif
#else
- unsigned char c1, c2;
-
if (s1 == s2)
return 0;
- do
+ for (;; s1++, s2++)
{
- c1 = tolower_l ((unsigned char) *s1, locale);
- c2 = tolower_l ((unsigned char) *s2, locale);
-
- if (c1 == '\0')
- break;
-
- ++s1;
- ++s2;
+ unsigned char c1 = tolower_l ((unsigned char) *s1, locale);
+ unsigned char c2 = tolower_l ((unsigned char) *s2, locale);
+
+ if (c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
#endif
}
char *
strcasestr (const char *haystack_start, const char *needle_start)
{
- const char *haystack = haystack_start;
const char *needle = needle_start;
- size_t needle_len; /* Length of NEEDLE. */
- size_t haystack_len; /* Known minimum length of HAYSTACK. */
- bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
- while (*haystack && *needle)
- {
- ok &= (tolower ((unsigned char) *haystack)
- == tolower ((unsigned char) *needle));
- haystack++;
- needle++;
- }
- if (*needle)
- return NULL;
- if (ok)
- return (char *) haystack_start;
- needle_len = needle - needle_start;
- haystack = haystack_start + 1;
- haystack_len = needle_len - 1;
+ {
+ const char *haystack = haystack_start;
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+ while (*haystack && *needle)
+ {
+ ok &= (tolower ((unsigned char) *haystack)
+ == tolower ((unsigned char) *needle));
+ haystack++;
+ needle++;
+ }
+ if (*needle)
+ return NULL;
+ if (ok)
+ return (char *) haystack_start;
+ }
+
+ size_t needle_len = /* Length of NEEDLE. */
+ needle - needle_start;
+ const char *haystack = haystack_start + 1;
+ size_t haystack_len = /* Known minimum length of HAYSTACK. */
+ needle_len - 1;
/* Perform the search. Abstract memory is considered to be an array
of 'unsigned char' values, not an array of 'char' values. See
performance. */
typedef unsigned long int longword;
- const unsigned char *char_ptr;
- const longword *longword_ptr;
- longword repeated_one;
- longword repeated_c;
- unsigned char c;
-
- c = (unsigned char) c_in;
+ unsigned char c = (unsigned char) c_in;
if (!c)
return rawmemchr (s, 0);
- /* Handle the first few bytes by reading one byte at a time.
- Do this until CHAR_PTR is aligned on a longword boundary. */
- for (char_ptr = (const unsigned char *) s;
- (size_t) char_ptr % sizeof (longword) != 0;
- ++char_ptr)
- if (!*char_ptr || *char_ptr == c)
- return (char *) char_ptr;
+ const longword *longword_ptr;
+
+ {
+ const unsigned char *char_ptr;
+
+ /* Handle the first few bytes by reading one byte at a time.
+ Do this until CHAR_PTR is aligned on a longword boundary. */
+ for (char_ptr = (const unsigned char *) s;
+ (size_t) char_ptr % sizeof (longword) != 0;
+ ++char_ptr)
+ if (!*char_ptr || *char_ptr == c)
+ return (char *) char_ptr;
- longword_ptr = (const longword *) char_ptr;
+ longword_ptr = (const longword *) char_ptr;
+ }
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to any size longwords. */
-
- /* Compute auxiliary longword values:
- repeated_one is a value which has a 1 in every byte.
- repeated_c has c in every byte. */
- repeated_one = 0x01010101;
- repeated_c = c | (c << 8);
- repeated_c |= repeated_c << 16;
- if (0xffffffffU < (longword) -1)
- {
- repeated_one |= repeated_one << 31 << 1;
- repeated_c |= repeated_c << 31 << 1;
- if (8 < sizeof (longword))
- for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
- {
- repeated_one |= repeated_one << i;
- repeated_c |= repeated_c << i;
- }
- }
-
- /* Instead of the traditional loop which tests each byte, we will
- test a longword at a time. The tricky part is testing if *any of
- the four* bytes in the longword in question are equal to NUL or
- c. We first use an xor with repeated_c. This reduces the task
- to testing whether *any of the four* bytes in longword1 or
- longword2 is zero.
-
- Let's consider longword1. We compute tmp =
- ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
- That is, we perform the following operations:
- 1. Subtract repeated_one.
- 2. & ~longword1.
- 3. & a mask consisting of 0x80 in every byte.
- Consider what happens in each byte:
- - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
- and step 3 transforms it into 0x80. A carry can also be propagated
- to more significant bytes.
- - If a byte of longword1 is nonzero, let its lowest 1 bit be at
- position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
- the byte ends in a single bit of value 0 and k bits of value 1.
- After step 2, the result is just k bits of value 1: 2^k - 1. After
- step 3, the result is 0. And no carry is produced.
- So, if longword1 has only non-zero bytes, tmp is zero.
- Whereas if longword1 has a zero byte, call j the position of the least
- significant zero byte. Then the result has a zero at positions 0, ...,
- j-1 and a 0x80 at position j. We cannot predict the result at the more
- significant bytes (positions j+1..3), but it does not matter since we
- already have a non-zero bit at position 8*j+7.
-
- The test whether any byte in longword1 or longword2 is zero is equivalent
- to testing whether tmp1 is nonzero or tmp2 is nonzero. We can combine
- this into a single test, whether (tmp1 | tmp2) is nonzero.
-
- This test can read more than one byte beyond the end of a string,
- depending on where the terminating NUL is encountered. However,
- this is considered safe since the initialization phase ensured
- that the read will be aligned, therefore, the read will not cross
- page boundaries and will not cause a fault. */
-
- while (1)
- {
- longword longword1 = *longword_ptr ^ repeated_c;
- longword longword2 = *longword_ptr;
-
- if (((((longword1 - repeated_one) & ~longword1)
- | ((longword2 - repeated_one) & ~longword2))
- & (repeated_one << 7)) != 0)
- break;
- longword_ptr++;
- }
-
- char_ptr = (const unsigned char *) longword_ptr;
-
- /* At this point, we know that one of the sizeof (longword) bytes
- starting at char_ptr is == 0 or == c. On little-endian machines,
- we could determine the first such byte without any further memory
- accesses, just by looking at the tmp result from the last loop
- iteration. But this does not work on big-endian machines.
- Choose code that works in both cases. */
-
- char_ptr = (unsigned char *) longword_ptr;
- while (*char_ptr && (*char_ptr != c))
- char_ptr++;
- return (char *) char_ptr;
+ {
+ /* Compute auxiliary longword values:
+ repeated_one is a value which has a 1 in every byte.
+ repeated_c has c in every byte. */
+ longword repeated_one = 0x01010101;
+ longword repeated_c = c | (c << 8);
+ repeated_c |= repeated_c << 16;
+ if (0xffffffffU < (longword) -1)
+ {
+ repeated_one |= repeated_one << 31 << 1;
+ repeated_c |= repeated_c << 31 << 1;
+ if (8 < sizeof (longword))
+ for (size_t i = 64; i < sizeof (longword) * 8; i *= 2)
+ {
+ repeated_one |= repeated_one << i;
+ repeated_c |= repeated_c << i;
+ }
+ }
+
+ /* Instead of the traditional loop which tests each byte, we will
+ test a longword at a time. The tricky part is testing if *any of
+ the four* bytes in the longword in question are equal to NUL or
+ c. We first use an xor with repeated_c. This reduces the task
+ to testing whether *any of the four* bytes in longword1 or
+ longword2 is zero.
+
+ Let's consider longword1. We compute tmp =
+ ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7).
+ That is, we perform the following operations:
+ 1. Subtract repeated_one.
+ 2. & ~longword1.
+ 3. & a mask consisting of 0x80 in every byte.
+ Consider what happens in each byte:
+ - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff,
+ and step 3 transforms it into 0x80. A carry can also be propagated
+ to more significant bytes.
+ - If a byte of longword1 is nonzero, let its lowest 1 bit be at
+ position k (0 <= k <= 7); so the lowest k bits are 0. After step 1,
+ the byte ends in a single bit of value 0 and k bits of value 1.
+ After step 2, the result is just k bits of value 1: 2^k - 1. After
+ step 3, the result is 0. And no carry is produced.
+ So, if longword1 has only non-zero bytes, tmp is zero.
+ Whereas if longword1 has a zero byte, call j the position of the least
+ significant zero byte. Then the result has a zero at positions 0, ...,
+ j-1 and a 0x80 at position j. We cannot predict the result at the more
+ significant bytes (positions j+1..3), but it does not matter since we
+ already have a non-zero bit at position 8*j+7.
+
+ The test whether any byte in longword1 or longword2 is zero is equivalent
+ to testing whether tmp1 is nonzero or tmp2 is nonzero. We can combine
+ this into a single test, whether (tmp1 | tmp2) is nonzero.
+
+ This test can read more than one byte beyond the end of a string,
+ depending on where the terminating NUL is encountered. However,
+ this is considered safe since the initialization phase ensured
+ that the read will be aligned, therefore, the read will not cross
+ page boundaries and will not cause a fault. */
+
+ while (1)
+ {
+ longword longword1 = *longword_ptr ^ repeated_c;
+ longword longword2 = *longword_ptr;
+
+ if (((((longword1 - repeated_one) & ~longword1)
+ | ((longword2 - repeated_one) & ~longword2))
+ & (repeated_one << 7)) != 0)
+ break;
+ longword_ptr++;
+ }
+ }
+
+ {
+ const unsigned char *char_ptr = (const unsigned char *) longword_ptr;
+
+ /* At this point, we know that one of the sizeof (longword) bytes
+ starting at char_ptr is == 0 or == c. On little-endian machines,
+ we could determine the first such byte without any further memory
+ accesses, just by looking at the tmp result from the last loop
+ iteration. But this does not work on big-endian machines.
+ Choose code that works in both cases. */
+
+ while (*char_ptr && (*char_ptr != c))
+ char_ptr++;
+ return (char *) char_ptr;
+ }
}
#undef strerror
{
static char buf[STACKBUF_LEN];
- size_t len;
/* Cast away const, due to the historical signature of strerror;
callers should not be modifying the string. */
}
/* Fix STACKBUF_LEN if this ever aborts. */
- len = strlen (msg);
+ size_t len = strlen (msg);
if (sizeof buf <= len)
abort ();
int
strerror_l_r (int errnum, char *buf, size_t buflen, locale_t locale)
{
- int ret;
int saved_errno = errno;
+ int ret;
#if GNULIB_defined_locale_t
local_snprintf (char *buf, size_t buflen, const char *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = _vsnprintf (buf, buflen, format, args);
+ int result = _vsnprintf (buf, buflen, format, args);
va_end (args);
if (buflen > 0 && (result < 0 || result >= buflen))
buf[buflen - 1] = '\0';
if (!ret && strlen (buf) == buflen - 1)
{
char stackbuf[STACKBUF_LEN];
- size_t len;
strerror_r (errnum, stackbuf, sizeof stackbuf);
- len = strlen (stackbuf);
+ size_t len = strlen (stackbuf);
/* STACKBUF_LEN should have been large enough. */
if (len + 1 == sizeof stackbuf)
abort ();
{
/* Work around glibc 2.23 bug
<https://sourceware.org/PR19633>. */
- va_list argptr;
- locale_t orig_locale;
- directives_t directives;
- ssize_t result;
- orig_locale = uselocale ((locale_t)0);
+ locale_t orig_locale = uselocale ((locale_t)0);
if (uselocale (locale) == (locale_t)0)
/* errno is set. */
requests 'long double' arguments. But since 'long double' arguments
are only supported on glibc, do so only if the original format string
consumes at least one 'long double' argument. */
+ ssize_t result;
+ directives_t directives;
if (fmon_parse (format, &directives) < 0)
{
errno = EINVAL;
}
else
{
- bool use_long_double;
-
- use_long_double = false;
+ bool use_long_double = false;
for (unsigned int i = 0; i < directives.count; i++)
if (directives.dir[i].needs_long_double)
{
break;
}
+ va_list argptr;
va_start (argptr, format);
if (use_long_double)
{
- char *ld_format;
-
/* Allocate room for the modified format string. */
- ld_format = (char *) malloc (strlen (format) + directives.count + 1);
+ char *ld_format = (char *) malloc (strlen (format) + directives.count + 1);
if (ld_format == NULL)
{
errno = ENOMEM;
an error, or come back to the initial shift state. */
{
mbstate_t mbstate = mbstate_zero;
- size_t len = 0;
- size_t fsize;
if (! format_end)
format_end = f + strlen (f) + 1;
- fsize = format_end - f;
+ size_t fsize = format_end - f;
+ size_t len = 0;
do
{
size_t bytes = mbrlen (f + len, fsize - len, &mbstate);
case L_('s'): /* GNU extension. */
{
- struct tm ltm;
- time_t t;
-
- ltm = *tp;
+ struct tm ltm = *tp;
ltm.tm_yday = -1;
- t = mktime_z (tz, <m);
+ time_t t = mktime_z (tz, <m);
if (ltm.tm_yday < 0)
{
errno = EOVERFLOW;
{
int diff;
- int hour_diff;
- int min_diff;
- int sec_diff;
#if HAVE_STRUCT_TM_TM_GMTOFF
diff = tp->tm_gmtoff;
#else
diff = 0;
else
{
- struct tm gtm;
- struct tm ltm;
- time_t lt;
-
- ltm = *tp;
+ struct tm ltm = *tp;
ltm.tm_wday = -1;
- lt = mktime_z (tz, <m);
- if (ltm.tm_wday < 0 || ! localtime_rz (0, <, >m))
+ time_t lt = mktime_z (tz, <m);
+ if (ltm.tm_wday < 0)
+ break;
+ struct tm gtm;
+ if (! localtime_rz (0, <, >m))
break;
diff = tm_diff (<m, >m);
}
0, tp)
== '-');
}
- hour_diff = diff / 60 / 60;
- min_diff = diff / 60 % 60;
- sec_diff = diff % 60;
+ int hour_diff = diff / 60 / 60;
+ int min_diff = diff / 60 % 60;
+ int sec_diff = diff % 60;
switch (colons)
{
char **resultp, size_t *lengthp)
{
# define tmpbufsize 4096
- size_t length;
- char *result;
/* Set to the initial state. */
iconv (cd, NULL, NULL, NULL, NULL);
/* Determine the length we need. */
+ size_t length;
{
size_t count = 0;
/* The alignment is needed when converting e.g. to glibc's WCHAR_T or
*lengthp = 0;
return 0;
}
+
+ char *result;
if (*resultp != NULL && *lengthp >= length)
result = *resultp;
else
char *result = NULL;
size_t length = 0;
int retval = mem_cd_iconv (src, strlen (src), cd, &result, &length);
- char *final_result;
if (retval < 0)
{
}
/* Add the terminating NUL byte. */
- final_result =
+ char *final_result =
(result != NULL ? realloc (result, length + 1) : malloc (length + 1));
if (final_result == NULL)
{
iconv() returns for an E2BIG reason, when the output size guess is too
small. Therefore it can only be used when we don't need the number of
irreversible conversions performed. */
- char *result;
- size_t result_size;
- size_t length;
- const char *inptr = src;
size_t inbytes_remaining = strlen (src);
/* Make a guess for the worst-case output size, in order to avoid a
realloc. It's OK if the guess is wrong as long as it is not zero and
doesn't lead to an integer overflow. */
- result_size = inbytes_remaining;
+ size_t result_size = inbytes_remaining;
{
size_t approx_sqrt_SIZE_MAX = SIZE_MAX >> (sizeof (size_t) * CHAR_BIT / 2);
if (result_size <= approx_sqrt_SIZE_MAX / MB_LEN_MAX)
}
result_size += 1; /* for the terminating NUL */
- result = (char *) malloc (result_size);
+ char *result = (char *) malloc (result_size);
if (result == NULL)
{
errno = ENOMEM;
iconv (cd, NULL, NULL, NULL, NULL);
/* Do the conversion. */
+ size_t length;
+ const char *inptr = src;
{
char *outptr = result;
size_t outbytes_remaining = result_size - 1;
else
{
#if HAVE_ICONV
- iconv_t cd;
- char *result;
-
- cd = iconv_open (to_codeset, from_codeset);
+ iconv_t cd = iconv_open (to_codeset, from_codeset);
if (cd == (iconv_t) -1)
return NULL;
- result = str_cd_iconv (src, cd);
+ char *result = str_cd_iconv (src, cd);
if (result == NULL)
{
int
iconveh_open (const char *to_codeset, const char *from_codeset, iconveh_t *cdp)
{
- iconv_t cd;
- iconv_t cd1;
- iconv_t cd2;
-
- cd = iconv_open (to_codeset, from_codeset);
+ iconv_t cd = iconv_open (to_codeset, from_codeset);
+ iconv_t cd1;
if (STRCASEEQ (from_codeset, "UTF-8", 'U','T','F','-','8',0,0,0,0))
cd1 = (iconv_t)(-1);
else
}
}
+ iconv_t cd2;
if (STRCASEEQ (to_codeset, "UTF-8", 'U','T','F','-','8',0,0,0,0)
# if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
&& !defined __UCLIBC__) \
size_t insize = *inbytesleft;
char *outptr = *outbuf;
size_t outsize = *outbytesleft;
- size_t res;
-
- res = 0;
+ size_t res = 0;
do
{
ucs4_t uc;
- int n;
- int m;
-
- n = u8_mbtoucr (&uc, (const uint8_t *) inptr, insize);
+ int n = u8_mbtoucr (&uc, (const uint8_t *) inptr, insize);
if (n < 0)
{
errno = (n == -2 ? EINVAL : EILSEQ);
*incremented = false;
break;
}
- m = u8_uctomb ((uint8_t *) outptr, uc, outsize);
+ int m = u8_uctomb ((uint8_t *) outptr, uc, outsize);
if (m == -2)
{
errno = E2BIG;
# define tmpbuf tmp.buf
char *initial_result;
- char *result;
size_t allocated;
- size_t length;
- size_t last_length = (size_t)(-1); /* only needed if offsets != NULL */
-
if (*resultp != NULL && *lengthp >= sizeof (tmpbuf))
{
initial_result = *resultp;
initial_result = tmpbuf;
allocated = sizeof (tmpbuf);
}
- result = initial_result;
+
+ char *result = initial_result;
/* Test whether a direct conversion is possible at all. */
if (cd == (iconv_t)(-1))
goto indirectly;
+ size_t last_length = (size_t)(-1); /* only needed if offsets != NULL */
if (offsets != NULL)
{
for (size_t i = 0; i < srclen; i++)
last_length = (size_t)(-1);
}
- length = 0;
+ size_t length = 0;
/* First, try a direct conversion, and see whether a conversion error
occurs at all. */
{
- const char *inptr = src;
- size_t insize = srclen;
-
/* Set to the initial state. */
iconv (cd, NULL, NULL, NULL, NULL);
+ const char *inptr = src;
+ size_t insize = srclen;
+
while (insize > 0)
{
char *outptr = result + length;
size_t outsize = allocated - extra_alloc - length;
+
bool incremented;
size_t res;
- bool grow;
-
if (offsets != NULL)
{
if (length != last_length) /* ensure that offset[] be increasing */
&incremented);
length = outptr - result;
- grow = (length + extra_alloc > allocated / 2);
+ bool grow = (length + extra_alloc > allocated / 2);
if (res == (size_t)(-1))
{
if (errno == E2BIG)
(handler == iconveh_replacement_character ? 3 : 1);
if (length + extra_need + extra_alloc > allocated)
{
- char *memory;
-
allocated = 2 * allocated;
if (length + extra_need + extra_alloc > allocated)
allocated = 2 * allocated;
if (length + extra_need + extra_alloc > allocated)
abort ();
+ char *memory;
if (result == initial_result)
memory = (char *) malloc (allocated);
else
break;
if (grow)
{
- char *memory;
-
allocated = 2 * allocated;
+ char *memory;
if (result == initial_result)
memory = (char *) malloc (allocated);
else
{
char *outptr = result + length;
size_t outsize = allocated - extra_alloc - length;
- size_t res;
-
- res = iconv (cd, NULL, NULL, &outptr, &outsize);
+ size_t res = iconv (cd, NULL, NULL, &outptr, &outsize);
length = outptr - result;
if (res == (size_t)(-1))
{
if (errno == E2BIG)
{
- char *memory;
allocated = 2 * allocated;
+ char *memory;
if (result == initial_result)
memory = (char *) malloc (allocated);
else
}
length = 0;
{
+ /* Set to the initial state. */
+ if (cd1 != (iconv_t)(-1))
+ iconv (cd1, NULL, NULL, NULL, NULL);
+ if (cd2 != (iconv_t)(-1))
+ iconv (cd2, NULL, NULL, NULL, NULL);
+
const bool slowly = (offsets != NULL || handler == iconveh_error);
# define utf8bufsize 4096 /* may also be smaller or larger than tmpbufsize */
char utf8buf[utf8bufsize + 3];
bool do_final_flush1 = true;
bool do_final_flush2 = true;
- /* Set to the initial state. */
- if (cd1 != (iconv_t)(-1))
- iconv (cd1, NULL, NULL, NULL, NULL);
- if (cd2 != (iconv_t)(-1))
- iconv (cd2, NULL, NULL, NULL, NULL);
-
while (in1size > 0 || do_final_flush1 || utf8len > 0 || do_final_flush2)
{
char *out1ptr = utf8buf + utf8len;
size_t out1size = utf8bufsize - utf8len;
- bool incremented1;
- size_t res1;
- int errno1;
/* Conversion step 1: from FROM_CODESET to UTF-8. */
+ bool incremented1;
+ size_t res1;
if (in1size > 0)
{
if (offsets != NULL
*out1ptr++ = '?';
res1 = 0;
}
- errno1 = errno;
+ int errno1 = errno;
utf8len = out1ptr - utf8buf;
if (offsets != NULL
{
char *out2ptr = result + length;
size_t out2size = allocated - extra_alloc - length;
+
bool incremented2;
size_t res2;
- bool grow;
-
if (in2size > 0)
{
if (cd2 != (iconv_t)(-1))
}
length = out2ptr - result;
- grow = (length + extra_alloc > allocated / 2);
+ bool grow = (length + extra_alloc > allocated / 2);
if (res2 == (size_t)(-1))
{
if (errno == E2BIG)
/* Error handling can produce up to 10 bytes of UTF-8
output. But TO_CODESET may be UCS-2, UTF-16 or
UCS-4, so use CD2 here as well. */
- char scratchbuf[10];
- size_t scratchlen;
ucs4_t uc;
- const char *inptr;
- size_t insize;
- size_t res;
if (incremented2)
{
in2size -= n;
}
+ char scratchbuf[10];
+ size_t scratchlen;
if (handler == iconveh_escape_sequence)
{
static char const hex[16] _GL_ATTRIBUTE_NONSTRING =
scratchlen = 1;
}
- inptr = scratchbuf;
- insize = scratchlen;
+ const char *inptr = scratchbuf;
+ size_t insize = scratchlen;
+ size_t res;
if (cd2 != (iconv_t)(-1))
{
char *out2ptr_try = out2ptr;
length = out2ptr - result;
if (res == (size_t)(-1) && errno == E2BIG)
{
- char *memory;
-
allocated = 2 * allocated;
if (length + 1 + extra_alloc > allocated)
abort ();
+ char *memory;
if (result == initial_result)
memory = (char *) malloc (allocated);
else
break;
if (grow)
{
- char *memory;
-
allocated = 2 * allocated;
+ char *memory;
if (result == initial_result)
memory = (char *) malloc (allocated);
else
result = *resultp;
else
{
- char *memory;
-
- memory = (char *) malloc (memsize > 0 ? memsize : 1);
+ char *memory = (char *) malloc (memsize > 0 ? memsize : 1);
if (memory != NULL)
result = memory;
else
{
/* Shrink the allocated memory if possible. */
size_t memsize = length + extra_alloc;
- char *memory;
-
- memory = (char *) realloc (result, memsize > 0 ? memsize : 1);
+ char *memory = (char *) realloc (result, memsize > 0 ? memsize : 1);
if (memory != NULL)
result = memory;
}
{
#if HAVE_ICONV
iconveh_t cd;
- char *result;
- size_t length;
- int retval;
-
if (iconveh_open (to_codeset, from_codeset, &cd) < 0)
return -1;
- result = *resultp;
- length = *lengthp;
- retval = mem_cd_iconveh (src, srclen, &cd, handler, offsets,
- &result, &length);
+ char *result = *resultp;
+ size_t length = *lengthp;
+ int retval = mem_cd_iconveh (src, srclen, &cd, handler, offsets,
+ &result, &length);
if (retval < 0)
{
{
#if HAVE_ICONV
iconveh_t cd;
- char *result;
-
if (iconveh_open (to_codeset, from_codeset, &cd) < 0)
return NULL;
- result = str_cd_iconveh (src, &cd, handler);
+ char *result = str_cd_iconveh (src, &cd, handler);
if (result == NULL)
{
uniconv_register_autodetect (const char *name,
const char * const *try_in_order)
{
- size_t namelen;
- size_t listlen;
- size_t memneed;
- size_t i;
-
/* The TRY_IN_ORDER list must not be empty. */
if (try_in_order[0] == NULL)
{
/* We must deep-copy NAME and TRY_IN_ORDER, because they may be allocated
with dynamic extent. */
- namelen = strlen (name) + 1;
- memneed = sizeof (struct autodetect_alias) + namelen + sizeof (char *);
- for (i = 0; try_in_order[i] != NULL; i++)
- memneed += sizeof (char *) + strlen (try_in_order[i]) + 1;
- listlen = i;
+ size_t namelen = strlen (name) + 1;
+ size_t memneed = sizeof (struct autodetect_alias) + namelen + sizeof (char *);
+ size_t listlen;
+ {
+ size_t i;
+ for (i = 0; try_in_order[i] != NULL; i++)
+ memneed += sizeof (char *) + strlen (try_in_order[i]) + 1;
+ listlen = i;
+ }
void *memory = malloc (memneed);
if (memory != NULL)
char *new_name = memcpy (memory, name, namelen);
memory = new_name + namelen;
- for (i = 0; i < listlen; i++)
- {
- size_t len = strlen (try_in_order[i]) + 1;
- char *copy = memcpy (memory, try_in_order[i], len);
- new_try_in_order[i] = copy;
- memory = copy + len;
- }
- new_try_in_order[i] = NULL;
+ {
+ size_t i;
+ for (i = 0; i < listlen; i++)
+ {
+ size_t len = strlen (try_in_order[i]) + 1;
+ char *copy = memcpy (memory, try_in_order[i], len);
+ new_try_in_order[i] = copy;
+ memory = copy + len;
+ }
+ new_try_in_order[i] = NULL;
+ }
/* Now insert the new alias. */
new_alias->name = new_name;
alias = alias->next)
if (streq (from_codeset, alias->name))
{
- const char * const *encodings;
-
if (handler != iconveh_error)
{
/* First try all encodings without any forgiving. */
- encodings = alias->encodings_to_try;
+ const char * const *encodings = alias->encodings_to_try;
do
{
retval = mem_iconveha_notranslit (src, srclen,
while (*encodings != NULL);
}
- encodings = alias->encodings_to_try;
+ const char * const *encodings = alias->encodings_to_try;
do
{
retval = mem_iconveha_notranslit (src, srclen,
|| defined ICONV_SET_TRANSLITERATE
if (transliterate)
{
- int retval;
size_t len = strlen (to_codeset);
char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
if (to_codeset_suffixed == NULL)
memcpy (to_codeset_suffixed, to_codeset, len);
memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);
- retval = mem_iconveha_notranslit (src, srclen,
- from_codeset, to_codeset_suffixed,
- handler, offsets, resultp, lengthp);
+ int retval = mem_iconveha_notranslit (src, srclen,
+ from_codeset, to_codeset_suffixed,
+ handler, offsets, resultp, lengthp);
freea (to_codeset_suffixed);
alias = alias->next)
if (streq (from_codeset, alias->name))
{
- const char * const *encodings;
-
if (handler != iconveh_error)
{
/* First try all encodings without any forgiving. */
- encodings = alias->encodings_to_try;
+ const char * const *encodings = alias->encodings_to_try;
do
{
result = str_iconveha_notranslit (src,
while (*encodings != NULL);
}
- encodings = alias->encodings_to_try;
+ const char * const *encodings = alias->encodings_to_try;
do
{
result = str_iconveha_notranslit (src,
|| defined ICONV_SET_TRANSLITERATE
if (transliterate)
{
- char *result;
size_t len = strlen (to_codeset);
char *to_codeset_suffixed = (char *) malloca (len + 10 + 1);
if (to_codeset_suffixed == NULL)
memcpy (to_codeset_suffixed, to_codeset, len);
memcpy (to_codeset_suffixed + len, "//TRANSLIT", 10 + 1);
- result = str_iconveha_notranslit (src, from_codeset, to_codeset_suffixed,
- handler);
+ char *result =
+ str_iconveha_notranslit (src, from_codeset, to_codeset_suffixed,
+ handler);
freea (to_codeset_suffixed);
sb_appendvf (struct string_buffer *buffer, const char *formatstring,
va_list list)
{
- va_list list_copy;
-
/* Make a bit of room, so that the probability that the first vsnzprintf()
call succeeds is high. */
size_t room = buffer->allocated - buffer->length;
room = buffer->allocated - buffer->length;
}
+ va_list list_copy;
va_copy (list_copy, list);
/* First vsnzprintf() call. */
int
sb_appendf (struct string_buffer *buffer, const char *formatstring, ...)
{
- va_list args;
-
/* Make a bit of room, so that the probability that the first vsnzprintf()
call succeeds is high. */
size_t room = buffer->allocated - buffer->length;
room = buffer->allocated - buffer->length;
}
+ va_list args;
va_start (args, formatstring);
/* First vsnzprintf() call. */
sbr_prependvf (struct string_buffer_reversed *buffer, const char *formatstring,
va_list list)
{
- va_list list_copy;
/* Make a bit of room, so that the probability that the first vsnzprintf()
call succeeds is high. */
room = buffer->allocated - buffer->length;
}
+ va_list list_copy;
va_copy (list_copy, list);
/* First vsnzprintf() call. */
sbr_prependf (struct string_buffer_reversed *buffer, const char *formatstring,
...)
{
- va_list args;
/* Make a bit of room, so that the probability that the first vsnzprintf()
call succeeds is high. */
room = buffer->allocated - buffer->length;
}
+ va_list args;
va_start (args, formatstring);
/* First vsnzprintf() call. */
int
sd_new (rw_string_desc_t *resultp, idx_t n)
{
- rw_string_desc_t result;
-
if (!(n >= 0))
/* Invalid argument. */
abort ();
+ rw_string_desc_t result;
+
result._nbytes = n;
if (n == 0)
result._data = NULL;
strip_trailing_slashes (char *file)
{
char *base = last_component (file);
- char *base_lim;
- bool had_slash;
/* last_component returns "" for file system roots, but we need to turn
"///" into "/". */
if (! *base)
base = file;
- base_lim = base + base_len (base);
- had_slash = (*base_lim != '\0');
+ char *base_lim = base + base_len (base);
+ bool had_slash = (*base_lim != '\0');
*base_lim = '\0';
return had_slash;
}
{
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
- unsigned char c1, c2;
if (p1 == p2 || n == 0)
return 0;
- do
+ for (;; p1++, p2++)
{
- c1 = tolower (*p1);
- c2 = tolower (*p2);
-
- if (--n == 0 || c1 == '\0')
- break;
-
- ++p1;
- ++p2;
+ unsigned char c1 = tolower (*p1);
+ unsigned char c2 = tolower (*p2);
+
+ if (--n == 0 || c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
}
# else
/* Implementation for the global locale. */
{
- int ret;
# if HAVE_WORKING_USELOCALE
locale_t saved_locale = uselocale (LC_GLOBAL_LOCALE);
# endif
- ret = strncasecmp (s1, s2, n);
+ int ret = strncasecmp (s1, s2, n);
# if HAVE_WORKING_USELOCALE
uselocale (saved_locale);
# endif
#else
- unsigned char c1, c2;
-
if (s1 == s2 || n == 0)
return 0;
- do
+ for (;; s1++, s2++)
{
- c1 = tolower_l ((unsigned char) *s1, locale);
- c2 = tolower_l ((unsigned char) *s2, locale);
-
- if (--n == 0 || c1 == '\0')
- break;
-
- ++s1;
- ++s2;
+ unsigned char c1 = tolower_l ((unsigned char) *s1, locale);
+ unsigned char c2 = tolower_l ((unsigned char) *s2, locale);
+
+ if (--n == 0 || c1 == '\0' || c1 != c2)
+ {
+ if (UCHAR_MAX <= INT_MAX)
+ return c1 - c2;
+ else
+ /* On machines where 'char' and 'int' are types of the same size,
+ the difference of two 'unsigned char' values - including the
+ sign bit - doesn't fit in an 'int'. */
+ return _GL_CMP (c1, c2);
+ }
}
- while (c1 == c2);
-
- if (UCHAR_MAX <= INT_MAX)
- return c1 - c2;
- else
- /* On machines where 'char' and 'int' are types of the same size, the
- difference of two 'unsigned char' values - including the sign bit -
- doesn't fit in an 'int'. */
- return _GL_CMP (c1, c2);
#endif
}
struct locale_data *const current = locale->__locales[LC_TIME];
#endif
- int cnt;
size_t val;
int have_I, is_pm;
int century, want_century;
case 'a':
case 'A':
/* Match day of week. */
- for (cnt = 0; cnt < 7; ++cnt)
- {
+ {
+ int cnt;
+ for (cnt = 0; cnt < 7; ++cnt)
+ {
#ifdef _NL_CURRENT
- if (*decided !=raw)
- {
- if (match_string (_NL_CURRENT (LC_TIME, DAY_1 + cnt), rp))
- {
- if (*decided == not
- && strcmp (_NL_CURRENT (LC_TIME, DAY_1 + cnt),
- weekday_name[cnt]))
- *decided = loc;
- break;
- }
- if (match_string (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), rp))
- {
- if (*decided == not
- && strcmp (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt),
- ab_weekday_name[cnt]))
- *decided = loc;
- break;
- }
- }
+ if (*decided !=raw)
+ {
+ if (match_string (_NL_CURRENT (LC_TIME, DAY_1 + cnt), rp))
+ {
+ if (*decided == not
+ && strcmp (_NL_CURRENT (LC_TIME, DAY_1 + cnt),
+ weekday_name[cnt]))
+ *decided = loc;
+ break;
+ }
+ if (match_string (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), rp))
+ {
+ if (*decided == not
+ && strcmp (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt),
+ ab_weekday_name[cnt]))
+ *decided = loc;
+ break;
+ }
+ }
#endif
- if (*decided != loc
- && (match_string (weekday_name[cnt], rp)
- || match_string (ab_weekday_name[cnt], rp)))
- {
- *decided = raw;
- break;
- }
- }
- if (cnt == 7)
- /* Does not match a weekday name. */
- return NULL;
- tm->tm_wday = cnt;
- have_wday = 1;
+ if (*decided != loc
+ && (match_string (weekday_name[cnt], rp)
+ || match_string (ab_weekday_name[cnt], rp)))
+ {
+ *decided = raw;
+ break;
+ }
+ }
+ if (cnt == 7)
+ /* Does not match a weekday name. */
+ return NULL;
+ tm->tm_wday = cnt;
+ have_wday = 1;
+ }
break;
case 'b':
case 'B':
case 'h':
/* Match month name. */
- for (cnt = 0; cnt < 12; ++cnt)
- {
+ {
+ int cnt;
+ for (cnt = 0; cnt < 12; ++cnt)
+ {
#ifdef _NL_CURRENT
- if (*decided !=raw)
- {
- if (match_string (_NL_CURRENT (LC_TIME, MON_1 + cnt), rp))
- {
- if (*decided == not
- && strcmp (_NL_CURRENT (LC_TIME, MON_1 + cnt),
- month_name[cnt]))
- *decided = loc;
- break;
- }
- if (match_string (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), rp))
- {
- if (*decided == not
- && strcmp (_NL_CURRENT (LC_TIME, ABMON_1 + cnt),
- ab_month_name[cnt]))
- *decided = loc;
- break;
- }
- }
+ if (*decided !=raw)
+ {
+ if (match_string (_NL_CURRENT (LC_TIME, MON_1 + cnt), rp))
+ {
+ if (*decided == not
+ && strcmp (_NL_CURRENT (LC_TIME, MON_1 + cnt),
+ month_name[cnt]))
+ *decided = loc;
+ break;
+ }
+ if (match_string (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), rp))
+ {
+ if (*decided == not
+ && strcmp (_NL_CURRENT (LC_TIME, ABMON_1 + cnt),
+ ab_month_name[cnt]))
+ *decided = loc;
+ break;
+ }
+ }
#endif
- if (match_string (month_name[cnt], rp)
- || match_string (ab_month_name[cnt], rp))
- {
- *decided = raw;
- break;
- }
- }
- if (cnt == 12)
- /* Does not match a month name. */
- return NULL;
- tm->tm_mon = cnt;
- want_xday = 1;
+ if (match_string (month_name[cnt], rp)
+ || match_string (ab_month_name[cnt], rp))
+ {
+ *decided = raw;
+ break;
+ }
+ }
+ if (cnt == 12)
+ /* Does not match a month name. */
+ return NULL;
+ tm->tm_mon = cnt;
+ want_xday = 1;
+ }
break;
case 'c':
/* Match locale's date and time format. */
strsep (char **stringp, const char *delim)
{
char *start = *stringp;
- char *ptr;
if (start == NULL)
return NULL;
return start;
}
+ char *ptr;
/* Optimize the case of one delimiter. */
if (delim[1] == '\0')
ptr = strchr (start, delim[0]);
else
/* The general case. */
ptr = strpbrk (start, delim);
+
if (ptr == NULL)
{
*stringp = NULL;
char *
strsignal (int signum)
{
- const char *desc;
__libc_once_define (static, once);
/* If we have not yet initialized the buffer do it now. */
__libc_once (once, init);
+ const char *desc;
if (
#ifdef SIGRTMIN
(signum >= SIGRTMIN && signum <= SIGRTMAX) ||
char *
strstr (const char *haystack_start, const char *needle_start)
{
- const char *haystack = haystack_start;
const char *needle = needle_start;
- size_t needle_len; /* Length of NEEDLE. */
- size_t haystack_len; /* Known minimum length of HAYSTACK. */
- bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
- while (*haystack && *needle)
- ok &= *haystack++ == *needle++;
- if (*needle)
- return NULL;
- if (ok)
- return (char *) haystack_start;
+ {
+ const char *haystack = haystack_start;
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+ while (*haystack && *needle)
+ ok &= *haystack++ == *needle++;
+ if (*needle)
+ return NULL;
+ if (ok)
+ return (char *) haystack_start;
+ }
/* Reduce the size of haystack using strchr, since it has a smaller
linear coefficient than the Two-Way algorithm. */
- needle_len = needle - needle_start;
- haystack = strchr (haystack_start + 1, *needle_start);
+ size_t needle_len = /* Length of NEEDLE. */
+ needle - needle_start;
+ const char *haystack = strchr (haystack_start + 1, *needle_start);
if (!haystack || __builtin_expect (needle_len == 1, 0))
return (char *) haystack;
needle -= needle_len;
- haystack_len = (haystack > haystack_start + needle_len ? 1
- : needle_len + haystack_start - haystack);
+ size_t haystack_len = /* Known minimum length of HAYSTACK. */
+ (haystack > haystack_start + needle_len ? 1
+ : needle_len + haystack_start - haystack);
/* Perform the search. Abstract memory is considered to be an array
of 'unsigned char' values, not an array of 'char' values. See
char **endptr)
{
const char *s = nptr;
- const char *digits_start;
- const char *digits_end;
- const char *radixchar_ptr;
- long int exponent;
- DOUBLE num;
/* First, determine the start and end of the digit sequence. */
- digits_start = s;
- radixchar_ptr = NULL;
+ const char *digits_start = s;
+ const char *radixchar_ptr = NULL;
for (;; ++s)
{
if (base == 16 ? c_isxdigit (*s) : c_isdigit (*s))
/* Any other character terminates the digit sequence. */
break;
}
- digits_end = s;
+ const char *digits_end = s;
/* Now radixchar_ptr == NULL or
digits_start <= radixchar_ptr < digits_end. */
+ long int exponent;
if (false)
{ /* Unoptimized. */
exponent =
}
/* Then, convert the digit sequence to a number. */
+ DOUBLE num;
{
num = 0;
for (const char *dp = digits_start; dp < digits_end; dp++)
if (dp != radixchar_ptr)
{
- int digit;
-
/* Make sure that multiplication by BASE will not overflow. */
if (!(num <= MAX / base))
{
}
/* Eat the next digit. */
+ int digit;
if (c_isdigit (*dp))
digit = *dp - '0';
else if (base == 16 && c_isxdigit (*dp))
/* From here on, STRTOD refers to the underlying implementation. It needs
to handle only finite unsigned decimal numbers with non-null ENDPTR. */
{
- char radixchar;
- bool negative = false;
+ int saved_errno = errno;
- /* The number so far. */
- DOUBLE num;
+ char radixchar = decimal_point_char ();
const char *s = nptr;
- const char *end;
- char *endbuf;
- int saved_errno = errno;
-
- radixchar = decimal_point_char ();
/* Eat whitespace. */
while (locale_isspace (*s))
++s;
/* Get the sign. */
- negative = *s == '-';
+ bool negative = *s == '-';
if (*s == '-' || *s == '+')
++s;
- num = STRTOD (s, &endbuf);
+ char *endbuf;
+ DOUBLE num = /* The number so far. */
+ STRTOD (s, &endbuf);
SET_ERRNO_UPON_GRADUAL_UNDERFLOW (num);
- end = endbuf;
+ const char *end = endbuf;
if (c_isdigit (s[*s == radixchar]))
{
char *
__strtok_r (char *s, const char *delim, char **save_ptr)
{
- char *token;
-
if (s == NULL)
s = *save_ptr;
}
/* Find the end of the token. */
- token = s;
+ char *token = s;
s = strpbrk (token, delim);
if (s == NULL)
/* This token finishes the string. */
INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
int base GROUP_PARAM_PROTO LOCALE_PARAM_PROTO)
{
- int negative;
- register unsigned LONG int cutoff;
- register unsigned int cutlim;
- register unsigned LONG int i;
- register const STRING_TYPE *s;
- const STRING_TYPE *save, *end;
- int overflow;
-
#ifdef USE_NUMBER_GROUPING
# ifdef USE_IN_EXTENDED_LOCALE_MODEL
struct locale_data *current = loc->__locales[LC_NUMERIC];
return 0;
}
- save = s = nptr;
+ register const STRING_TYPE *s = nptr;
+ const STRING_TYPE *save = s;
/* Skip white space. */
while (ISSPACE (*s))
goto noconv;
/* Check for a sign. */
+ int negative;
if (*s == L_('-'))
{
negative = 1;
/* Save the pointer so we can check later if anything happened. */
save = s;
+ const STRING_TYPE *end;
#ifdef USE_NUMBER_GROUPING
if (group)
{
#endif
end = NULL;
- cutoff = STRTOL_ULONG_MAX / (unsigned LONG int) base;
- cutlim = STRTOL_ULONG_MAX % (unsigned LONG int) base;
+ register unsigned LONG int cutoff = STRTOL_ULONG_MAX / (unsigned LONG int) base;
+ register unsigned int cutlim = STRTOL_ULONG_MAX % (unsigned LONG int) base;
- overflow = 0;
- i = 0;
+ int overflow = 0;
+ register unsigned LONG int i = 0;
for (UCHAR_TYPE c = *s; c != L_('\0'); c = *++s)
{
if (s == end)
{
size_t hashcode = string_hash (string);
size_t slot = hashcode % STRUNIQ_HASH_TABLE_SIZE;
- size_t size;
- struct struniq_hash_node *new_node;
for (struct struniq_hash_node *p = struniq_hash_table[slot]; p != NULL; p = p->next)
if (streq (p->contents, string))
return p->contents;
- size = strlen (string) + 1;
- new_node =
+ size_t size = strlen (string) + 1;
+ struct struniq_hash_node *new_node =
(struct struniq_hash_node *)
malloc (FLEXSIZEOF (struct struniq_hash_node, contents, size));
if (new_node == NULL)
bool supersede_if_exists, bool supersede_if_does_not_exist,
struct supersede_final_action *action)
{
- int fd;
/* Extra flags for existing devices. */
int extra_flags =
#if defined __sun || (defined _WIN32 && !defined __CYGWIN__)
filename = "NUL";
#endif
+ int fd;
if (supersede_if_exists)
{
if (supersede_if_does_not_exist)
file. */
{
struct timespec ts[2];
-
ts[0] = get_stat_atime (&dest_statbuf);
ts[1] = get_stat_mtime (&temp_statbuf);
+
ignore_value (utimens (action->final_rename_temp, ts));
}
{
if (*argv != NULL)
{
- size_t length;
- char *command;
- char *p;
-
- length = 0;
+ size_t length = 0;
for (char * const *argp = argv; ; )
{
length += system_quote_length (interpreter, *argp) + 1;
break;
}
- command = XNMALLOC (length, char);
+ char *command = XNMALLOC (length, char);
- p = command;
- for (char * const *argp = argv; ; )
- {
- p = system_quote_copy (p, interpreter, *argp);
- argp++;
- if (*argp == NULL)
- break;
- *p++ = ' ';
- }
- *p = '\0';
+ {
+ char *p = command;
+ for (char * const *argp = argv; ; )
+ {
+ p = system_quote_copy (p, interpreter, *argp);
+ argp++;
+ if (*argp == NULL)
+ break;
+ *p++ = ' ';
+ }
+ *p = '\0';
+ }
return command;
}
ptrdiff_t
szprintf (char *str, const char *format, ...)
{
- char *output;
- size_t len;
- size_t lenbuf;
va_list args;
+ va_start (args, format);
/* Set lenbuf = min (SIZE_MAX, - (uintptr_t) str - 1). */
- lenbuf = SIZE_MAX;
+ size_t lenbuf = SIZE_MAX;
if (lenbuf >= ~ (uintptr_t) str)
lenbuf = ~ (uintptr_t) str;
- va_start (args, format);
- output = vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+ char *output = vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
+
va_end (args);
if (!output)
static long double
kernel_tanl (long double x, long double y, int iy)
{
- long double z, r, v, w, s, u, u1;
- int invert = 0, sign;
-
- sign = 1;
+ int sign = 1;
if (x < 0)
{
x = -x;
return (iy == 1 ? x : -1.0L / x) * sign;
}
}
+
+ int invert = 0;
if (x >= 0.6743316650390625) /* |x| >= 0.6743316650390625 */
{
invert = 1;
- z = pio4hi - x;
- w = pio4lo - y;
+ long double z = pio4hi - x;
+ long double w = pio4lo - y;
x = z + w;
y = 0.0;
}
- z = x * x;
- r = T0 + z * (T1 + z * (T2 + z * (T3 + z * T4)));
- v = U0 + z * (U1 + z * (U2 + z * (U3 + z * (U4 + z))));
+
+ long double z = x * x;
+ long double r = T0 + z * (T1 + z * (T2 + z * (T3 + z * T4)));
+ long double v = U0 + z * (U1 + z * (U2 + z * (U3 + z * (U4 + z))));
r = r / v;
- s = z * x;
+ long double s = z * x;
r = y + z * (s * r + y);
r += TH * s;
- w = x + r;
+ long double w = x + r;
if (invert)
{
v = (long double) iy;
{ /* if allow error up to 2 ulp,
simply return -1.0/(x+r) here */
/* compute -1.0/(x+r) accurately */
- u1 = (double) w;
+ long double u1 = (double) w;
v = r - (u1 - x);
z = -1.0 / w;
- u = (double) z;
+ long double u = (double) z;
s = 1.0 + u * u1;
return (u + z * (s + u * v)) * sign;
}
long double
tanl (long double x)
{
- long double y[2], z = 0.0L;
- int n;
-
/* tanl(NaN) is NaN */
if (isnanl (x))
return x;
/* |x| ~< pi/4 */
if (x >= -0.7853981633974483096156608458198757210492 &&
x <= 0.7853981633974483096156608458198757210492)
- return kernel_tanl (x, z, 1);
+ {
+ long double z = 0.0L;
+ return kernel_tanl (x, z, 1);
+ }
/* tanl(Inf) is NaN, tanl(0) is 0 */
else if (x + x == x)
/* argument reduction needed */
else
{
- n = ieee754_rem_pio2l (x, y);
+ long double y[2];
+ int n = ieee754_rem_pio2l (x, y);
/* 1 -- n even, -1 -- n odd */
return kernel_tanl (y[0], y[1], 1 - ((n & 1) << 1));
}
try_tempname_len (char *tmpl, int suffixlen, void *args,
int (*tryfunc) (char *, void *), size_t x_suffix_len)
{
- size_t len;
- char *XXXXXX;
- int fd;
int saved_errno = errno;
/* A lower bound on the number of temporary files to attempt to
random_value const biased_min
= RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
- len = strlen (tmpl);
+ size_t len = strlen (tmpl);
if (len < x_suffix_len + suffixlen
|| strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
{
}
/* This is where the Xs start. */
- XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
+ char *XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
for (unsigned int count = 0; count < attempts; ++count)
{
vdigits--;
}
- fd = tryfunc (tmpl, args);
+ int fd = tryfunc (tmpl, args);
if (fd >= 0)
{
__set_errno (saved_errno);
sprintf_integer (char *str, int x)
{
unsigned int y;
- char buf[20];
- char *p;
- size_t n;
-
if (x < 0)
{
*str++ = '-';
else
y = x;
- p = buf + sizeof (buf);
+ char buf[20];
+ char *p = buf + sizeof (buf);
do
{
*--p = '0' + (y % 10);
y = y / 10;
}
while (y > 0);
- n = buf + sizeof (buf) - p;
+ size_t n = buf + sizeof (buf) - p;
memcpy (str, p, n);
str[n] = '\0';
}
ostream_printf (ostream_t stream, const char *format, ...)
{
va_list args;
- char *temp_string;
- ptrdiff_t ret;
va_start (args, format);
- ret = vasprintf (&temp_string, format, args);
+ char *temp_string;
+ ptrdiff_t ret = vasprintf (&temp_string, format, args);
va_end (args);
if (ret >= 0)
{
time (time_t *tp)
{
struct timeval tv;
- time_t tt;
-
if (gettimeofday (&tv, NULL) < 0)
abort ();
- tt = tv.tv_sec;
+ time_t tt = tv.tv_sec;
if (tp)
*tp = tt;
static clock_t
filetime2clock (FILETIME time)
{
- float f;
-
/* We have a 64-bit value, in the form of two DWORDS aka unsigned
int, counting the number of 100-nanosecond intervals. We need to
convert these to clock ticks. Older POSIX uses CLK_TCK to
use it. Note that CLOCKS_PER_SEC constant does not apply here,
it is for use with the clock function. */
- f = (unsigned long long) time.dwHighDateTime << 32;
+ float f = (unsigned long long) time.dwHighDateTime << 32;
f += time.dwLowDateTime;
f = f * CLK_TCK / 10000000;
return (clock_t) round (f);
int nssum = a.tv_nsec + b.tv_nsec;
int carry = TIMESPEC_HZ <= nssum;
time_t rs;
- int rns;
bool v = ckd_add (&rs, a.tv_sec, b.tv_sec);
+ int rns;
if (v == ckd_add (&rs, rs, carry))
rns = nssum - TIMESPEC_HZ * carry;
else
int nsdiff = a.tv_nsec - b.tv_nsec;
int borrow = nsdiff < 0;
time_t rs;
- int rns;
bool v = ckd_sub (&rs, a.tv_sec, b.tv_sec);
+ int rns;
if (v == ckd_sub (&rs, rs, borrow))
rns = nsdiff + TIMESPEC_HZ * borrow;
else
path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
bool try_tmpdir)
{
- const char *d;
- size_t dlen, plen;
- bool add_slash;
-
+ size_t plen;
if (!pfx || !pfx[0])
{
pfx = "file";
if (try_tmpdir)
{
- d = __libc_secure_getenv ("TMPDIR");
+ const char *d = __libc_secure_getenv ("TMPDIR");
if (d != NULL && direxists (d))
dir = d;
else if (dir != NULL && direxists (dir))
{
#if defined _WIN32 && ! defined __CYGWIN__
char dirbuf[PATH_MAX];
- DWORD retval;
/* Find Windows temporary file directory.
We try this before P_tmpdir because Windows defines P_tmpdir to "\\"
and will therefore try to put all temporary files in the root
directory (unless $TMPDIR is set). */
- retval = GetTempPath (PATH_MAX, dirbuf);
+ DWORD retval = GetTempPath (PATH_MAX, dirbuf);
if (retval > 0 && retval < PATH_MAX && direxists (dirbuf))
dir = dirbuf;
else
}
}
- dlen = strlen (dir);
+ size_t dlen = strlen (dir);
+
+ bool add_slash;
#ifdef __VMS
add_slash = 0;
#else
tmpfile (void)
{
char dir[PATH_MAX];
- DWORD retval;
/* Find Windows temporary file directory.
We provide this as the directory argument to path_search because Windows
defines P_tmpdir to "\\" and will therefore try to put all temporary files
in the root directory (unless $TMPDIR is set). */
- retval = GetTempPath (PATH_MAX, dir);
+ DWORD retval = GetTempPath (PATH_MAX, dir);
if (retval > 0 && retval < PATH_MAX)
{
char xtemplate[PATH_MAX];
{
size_t len = strlen (xtemplate);
int o_temporary = (supports_delete_on_close () ? _O_TEMPORARY : 0);
- int fd;
+ int fd;
do
{
memcpy (&xtemplate[len - 6], "XXXXXX", 6);
tmpfile (void)
{
char buf[PATH_MAX];
- int fd;
- FILE *fp;
/* Try $TMPDIR first, not /tmp nor P_tmpdir, because we need this replacement
on Android, and /tmp does not exist on Android. */
if (path_search (buf, sizeof buf, NULL, "tmpf", true))
return NULL;
- fd = gen_tempname (buf, 0, 0, GT_FILE);
+ int fd = gen_tempname (buf, 0, 0, GT_FILE);
if (fd < 0)
return NULL;
a file is not really removed until it is closed. */
(void) unlink (buf);
- if ((fp = fdopen (fd, "w+b")) == NULL)
+ FILE *fp = fdopen (fd, "w+b");
+ if (fp == NULL)
{
int saved_errno = errno;
close (fd);
#else
/* Implementation for the global locale. */
{
- int ret;
# if HAVE_WORKING_USELOCALE
locale_t saved_locale = uselocale (LC_GLOBAL_LOCALE);
# endif
- ret = GLOBAL_FUNC (c);
+ int ret = GLOBAL_FUNC (c);
# if HAVE_WORKING_USELOCALE
uselocale (saved_locale);
# endif
static int termcap;
static char OOPS[] = "OOPS";
static char buf[MAX_LINE];
- const char *sp;
- char *dp;
- const char *fmt;
- char scan_for;
- int scan_depth;
- int if_depth;
- char fmt_buf[MAX_LINE];
- char sbuf[MAX_LINE];
va_start (tparm_args, str);
- sp = str;
- dp = buf;
- scan_for = 0;
- scan_depth = 0;
- if_depth = 0;
+ const char *sp = str;
+ char *dp = buf;
+ char scan_for = 0;
+ int scan_depth = 0;
+ int if_depth = 0;
argcnt = 0;
pos = 0;
termcap = 1;
sp++;
break;
}
- fmt = NULL;
+ char fmt_buf[MAX_LINE];
+ const char *fmt = NULL;
switch (*sp)
{
case '%':
case 'x': case 'X': case 'o': case 'c':
case '0': case '1': case '4': case '5':
case '6': case '7': case '8': case '9':
- if (fmt == NULL)
- {
- char *fmtp;
- if (termcap)
- return OOPS;
- if (*sp == ':')
- sp++;
- fmtp = fmt_buf;
- *fmtp++ = '%';
- while (*sp != 's' && *sp != 'x' && *sp != 'X' && *sp != 'd'
- && *sp != 'o' && *sp != 'c' && *sp != 'u')
- {
- if (*sp == '\0')
- return OOPS;
- *fmtp++ = *sp++;
- }
- *fmtp++ = *sp;
- *fmtp = '\0';
- fmt = fmt_buf;
- }
{
- char conv_char = fmt[strlen (fmt) - 1];
- if (conv_char == 's')
+ char sbuf[MAX_LINE];
+ if (fmt == NULL)
{
- char *s;
- if (popstring (&s))
- return OOPS;
- sprintf (sbuf, fmt, s);
- }
- else
- {
- int i;
if (termcap)
+ return OOPS;
+ if (*sp == ':')
+ sp++;
+ char *fmtp = fmt_buf;
+ *fmtp++ = '%';
+ while (*sp != 's' && *sp != 'x' && *sp != 'X' && *sp != 'd'
+ && *sp != 'o' && *sp != 'c' && *sp != 'u')
{
- if (getarg (termcap++ - 1, INTEGER, &i))
+ if (*sp == '\0')
return OOPS;
+ *fmtp++ = *sp++;
}
- else
- if (popnum (&i))
- return OOPS;
- if (i == 0 && conv_char == 'c')
- strcpy (sbuf, "\000");
- else
- sprintf (sbuf, fmt, i);
+ *fmtp++ = *sp;
+ *fmtp = '\0';
+ fmt = fmt_buf;
}
- }
- sp++;
- fmt = sbuf;
- while (*fmt != '\0')
{
- if (*fmt == '$')
- *dp++ = '\\';
- *dp++ = *fmt++;
+ char conv_char = fmt[strlen (fmt) - 1];
+ if (conv_char == 's')
+ {
+ char *s;
+ if (popstring (&s))
+ return OOPS;
+ sprintf (sbuf, fmt, s);
+ }
+ else
+ {
+ int i;
+ if (termcap)
+ {
+ if (getarg (termcap++ - 1, INTEGER, &i))
+ return OOPS;
+ }
+ else
+ if (popnum (&i))
+ return OOPS;
+ if (i == 0 && conv_char == 'c')
+ strcpy (sbuf, "\000");
+ else
+ sprintf (sbuf, fmt, i);
+ }
}
+ sp++;
+ fmt = sbuf;
+ while (*fmt != '\0')
+ {
+ if (*fmt == '$')
+ *dp++ = '\\';
+ *dp++ = *fmt++;
+ }
+ }
break;
case 'r':
{
int
ieee754_rem_pio2l (long double x, long double *y)
{
- long double z, w, t;
- double tx[8];
- int exp, n;
-
if (x >= -0.78539816339744830961566084581987572104929234984377
&& x <= 0.78539816339744830961566084581987572104929234984377)
/* x in <-pi/4, pi/4> */
if (x > 0 && x < 2.35619449019234492884698253745962716314787704953131)
{
/* 113 + 93 bit PI is ok */
- z = x - PI_2_1;
+ long double z = x - PI_2_1;
y[0] = z - PI_2_1t;
y[1] = (z - y[0]) - PI_2_1t;
return 1;
if (x < 0 && x > -2.35619449019234492884698253745962716314787704953131)
{
/* 113 + 93 bit PI is ok */
- z = x + PI_2_1;
+ long double z = x + PI_2_1;
y[0] = z + PI_2_1t;
y[1] = (z - y[0]) + PI_2_1t;
return -1;
/* Handle large arguments.
We split the 113 bits of the mantissa into 5 24bit integers
stored in a double array. */
- z = frexp (x, &exp);
+ int exp;
+ long double z = frexp (x, &exp);
+
+ double tx[8];
tx[0] = floorl (z *= 16777216.0);
z -= tx[0];
tx[1] = floorl (z *= 16777216.0);
z -= tx[3];
tx[4] = floorl (z *= 16777216.0);
- n = kernel_rem_pio2 (tx, tx + 5, exp - 24, tx[4] ? 5 : 4, 3, two_over_pi);
+ int n = kernel_rem_pio2 (tx, tx + 5, exp - 24, tx[4] ? 5 : 4, 3, two_over_pi);
/* The result is now stored in 3 double values, we need to convert it into
two long double values. */
- t = (long double) tx[6] + (long double) tx[7];
- w = (long double) tx[5];
+ long double t = (long double) tx[6] + (long double) tx[7];
+ long double w = (long double) tx[5];
if (x > 0)
{
kernel_rem_pio2 (double *x, double *y, int e0, int nx, int prec,
const int *ipio2)
{
- int jz, jx, jv, jp, jk, carry, n, iq[20], i, j, k, m, q0, ih;
- double z, fw, f[20], fq[20], q[20];
-
/* initialize jk */
- jk = init_jk[prec];
- jp = jk;
+ int jk = init_jk[prec];
+ int jp = jk;
/* determine jx,jv,q0, note that 3>q0 */
- jx = nx - 1;
- jv = (e0 - 3) / 24;
+ int jx = nx - 1;
+ int jv = (e0 - 3) / 24;
if (jv < 0)
jv = 0;
- q0 = e0 - 24 * (jv + 1);
+ int q0 = e0 - 24 * (jv + 1);
/* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */
- j = jv - jx;
- m = jx + jk;
- for (i = 0; i <= m; i++, j++)
+ int j = jv - jx;
+ int m = jx + jk;
+ double f[20];
+ for (int i = 0; i <= m; i++, j++)
f[i] = (j < 0) ? zero : (double) ipio2[j];
/* compute q[0],q[1],...q[jk] */
- for (i = 0; i <= jk; i++)
+ double q[20];
+ for (int i = 0; i <= jk; i++)
{
+ double fw;
for (j = 0, fw = 0.0; j <= jx; j++)
fw += x[j] * f[jx + i - j];
q[i] = fw;
}
- jz = jk;
-recompute:
+ int jz = jk;
+recompute: ;
+ double z;
+
/* distill q[] into iq[] in reverse order */
- for (i = 0, j = jz, z = q[jz]; j > 0; i++, j--)
- {
- fw = (double) ((int) (twon24 * z));
- iq[i] = (int) (z - two24 * fw);
- z = q[j - 1] + fw;
- }
+ int iq[20];
+ {
+ int i;
+ for (i = 0, j = jz, z = q[jz]; j > 0; i++, j--)
+ {
+ double fw = (double) ((int) (twon24 * z));
+ iq[i] = (int) (z - two24 * fw);
+ z = q[j - 1] + fw;
+ }
+ }
/* compute n */
z = ldexp (z, q0); /* actual value of z */
z -= 8.0 * floor (z * 0.125); /* trim off integer >= 8 */
- n = (int) z;
+ int n = (int) z;
z -= (double) n;
- ih = 0;
+ int ih = 0;
if (q0 > 0)
{ /* need iq[jz-1] to determine n */
- i = (iq[jz - 1] >> (24 - q0));
+ int i = (iq[jz - 1] >> (24 - q0));
n += i;
iq[jz - 1] -= i << (24 - q0);
ih = iq[jz - 1] >> (23 - q0);
if (ih > 0)
{ /* q > 0.5 */
n += 1;
- carry = 0;
- for (i = 0; i < jz; i++)
+ int carry = 0;
+ for (int i = 0; i < jz; i++)
{ /* compute 1-q */
j = iq[i];
if (carry == 0)
if (z == zero)
{
j = 0;
- for (i = jz - 1; i >= jk; i--)
+ for (int i = jz - 1; i >= jk; i--)
j |= iq[i];
if (j == 0)
{ /* need recomputation */
+ int k;
for (k = 1; iq[jk - k] == 0; k++); /* k = no. of terms needed */
- for (i = jz + 1; i <= jz + k; i++)
+ for (int i = jz + 1; i <= jz + k; i++)
{ /* add q[jz+1] to q[jz+k] */
f[jx + i] = (double) ipio2[jv + i];
+ double fw;
for (j = 0, fw = 0.0; j <= jx; j++)
fw += x[j] * f[jx + i - j];
q[i] = fw;
z = ldexp (z, -q0);
if (z >= two24)
{
- fw = (double) ((int) (twon24 * z));
+ double fw = (double) ((int) (twon24 * z));
iq[jz] = (int) (z - two24 * fw);
jz += 1;
q0 += 24;
}
/* convert integer "bit" chunk to floating-point value */
- fw = ldexp (one, q0);
- for (i = jz; i >= 0; i--)
- {
- q[i] = fw * (double) iq[i];
- fw *= twon24;
- }
+ {
+ double fw = ldexp (one, q0);
+ for (int i = jz; i >= 0; i--)
+ {
+ q[i] = fw * (double) iq[i];
+ fw *= twon24;
+ }
+ }
/* compute PIo2[0,...,jp]*q[jz,...,0] */
- for (i = jz; i >= 0; i--)
+ double fq[20];
+ for (int i = jz; i >= 0; i--)
{
+ double fw;
+ int k;
for (fw = 0.0, k = 0; k <= jp && k <= jz - i; k++)
fw += PIo2[k] * q[i + k];
fq[jz - i] = fw;
}
/* compress fq[] into y[] */
+ double fw;
switch (prec)
{
case 0:
fw = 0.0;
- for (i = jz; i >= 0; i--)
+ for (int i = jz; i >= 0; i--)
fw += fq[i];
y[0] = (ih == 0) ? fw : -fw;
break;
case 1:
case 2:
fw = 0.0;
- for (i = jz; i >= 0; i--)
+ for (int i = jz; i >= 0; i--)
fw += fq[i];
y[0] = (ih == 0) ? fw : -fw;
fw = fq[0] - fw;
- for (i = 1; i <= jz; i++)
+ for (int i = 1; i <= jz; i++)
fw += fq[i];
y[1] = (ih == 0) ? fw : -fw;
break;
case 3: /* painful */
- for (i = jz; i > 0; i--)
+ for (int i = jz; i > 0; i--)
{
fw = fq[i - 1] + fq[i];
fq[i] += fq[i - 1] - fw;
fq[i - 1] = fw;
}
- for (i = jz; i > 1; i--)
+ for (int i = jz; i > 1; i--)
{
fw = fq[i - 1] + fq[i];
fq[i] += fq[i - 1] - fw;
fq[i - 1] = fw;
}
+ int i;
for (fw = 0.0, i = jz; i >= 2; i--)
fw += fq[i];
if (ih == 0)
#if GNULIB_MCEL_PREFER
/* Skip leading whitespace. */
if (how != TRIM_TRAILING)
- for (mcel_t g; *start; start += g.len)
+ for (; *start; )
{
- g = mcel_scanz (start);
+ mcel_t g = mcel_scanz (start);
if (!c32isspace (g.ch))
break;
+ start += g.len;
}
/* Find start of any trailing whitespace. */
static void
check_tree (node root)
{
- int cnt = 0;
if (root == NULL)
return;
root->red = 0;
+ int cnt = 0;
for (node p = root->left; p; p = p->left)
cnt += !p->red;
check_tree_recurse (root, 0, cnt);
int p_r, int gp_r, int mode)
{
node root = *rootp;
- node *rp, *lp;
- rp = &(*rootp)->right;
- lp = &(*rootp)->left;
+ node *rp = &(*rootp)->right;
+ node *lp = &(*rootp)->left;
/* See if we have to split this node (both successors red). */
if (mode == 1
void *
__tsearch (const void *key, void **vrootp, __compar_fn_t compar)
{
- node q;
- node *parentp = NULL, *gparentp = NULL;
node *rootp = (node *) vrootp;
- node *nextp;
- int r = 0, p_r = 0, gp_r = 0; /* No they might not, Mr Compiler. */
if (rootp == NULL)
return NULL;
CHECK_TREE (*rootp);
- nextp = rootp;
+ node *parentp = NULL;
+ node *gparentp = NULL;
+ int r = 0, p_r = 0, gp_r = 0; /* No they might not, Mr Compiler. */
+
+ node *nextp = rootp;
while (*nextp != NULL)
{
node root = *rootp;
p_r = r;
}
- q = (struct node_t *) malloc (sizeof (struct node_t));
+ node q = (struct node_t *) malloc (sizeof (struct node_t));
if (q != NULL)
{
*nextp = q; /* link new node to old */
while (*rootp != NULL)
{
node root = *rootp;
- int r;
-
- r = (*compar) (key, root->key);
+ int r = (*compar) (key, root->key);
if (r == 0)
return root;
void *
__tdelete (const void *key, void **vrootp, __compar_fn_t compar)
{
- node p, q, r, retval;
- int cmp;
node *rootp = (node *) vrootp;
- node root, unchained;
- /* Stack of nodes so we remember the parents without recursion. It's
- _very_ unlikely that there are paths longer than 40 nodes. The tree
- would need to have around 250.000 nodes. */
- int stacksize = 100;
- int sp = 0;
- node *nodestack[100];
if (rootp == NULL)
return NULL;
- p = *rootp;
+
+ node p = *rootp;
if (p == NULL)
return NULL;
CHECK_TREE (p);
- while ((cmp = (*compar) (key, (*rootp)->key)) != 0)
- {
- if (sp == stacksize)
- abort ();
-
- nodestack[sp++] = rootp;
- p = *rootp;
- rootp = ((cmp < 0)
- ? &(*rootp)->left
- : &(*rootp)->right);
- if (*rootp == NULL)
- return NULL;
- }
+ /* Stack of nodes so we remember the parents without recursion. It's
+ _very_ unlikely that there are paths longer than 40 nodes. The tree
+ would need to have around 250.000 nodes. */
+ int stacksize = 100;
+ int sp = 0;
+ node *nodestack[100];
+ {
+ int cmp;
+ while ((cmp = (*compar) (key, (*rootp)->key)) != 0)
+ {
+ if (sp == stacksize)
+ abort ();
+
+ nodestack[sp++] = rootp;
+ p = *rootp;
+ rootp = ((cmp < 0)
+ ? &(*rootp)->left
+ : &(*rootp)->right);
+ if (*rootp == NULL)
+ return NULL;
+ }
+ }
/* This is bogus if the node to be deleted is the root... this routine
really should return an integer with 0 for success, -1 for failure
and errno = ESRCH or something. */
- retval = p;
+ node retval = p;
/* We don't unchain the node we want to delete. Instead, we overwrite
it with its successor and unchain the successor. If there is no
successor, we really unchain the node to be deleted. */
- root = *rootp;
+ node root = *rootp;
- r = root->right;
- q = root->left;
+ node r = root->right;
+ node q = root->left;
+ node unchained;
if (q == NULL || r == NULL)
unchained = root;
else
{
char procfile[14+11+1];
char largerbuf[512];
- ssize_t ret;
sprintf (procfile, "/proc/self/fd/%d", fd);
- ret = (buflen < sizeof (largerbuf)
- ? readlink (procfile, largerbuf, sizeof (largerbuf))
- : readlink (procfile, buf, buflen <= INT_MAX ? buflen : INT_MAX));
+ ssize_t ret =
+ (buflen < sizeof (largerbuf)
+ ? readlink (procfile, largerbuf, sizeof (largerbuf))
+ : readlink (procfile, buf, buflen <= INT_MAX ? buflen : INT_MAX));
if (ret < 0)
return errno;
if ((size_t) ret >= buflen)
return 0;
#elif HAVE_TTYNAME
/* Note: This is not multithread-safe. */
- char *name;
- size_t namelen;
-
- name = ttyname (fd);
+ char *name = ttyname (fd);
if (name == NULL)
return errno;
- namelen = strlen (name) + 1;
+ size_t namelen = strlen (name) + 1;
if (namelen > buflen)
return ERANGE;
memcpy (buf, name, namelen);
int
uname (struct utsname *buf)
{
- OSVERSIONINFO version;
- OSVERSIONINFOEX versionex;
- BOOL have_versionex; /* indicates whether versionex is filled */
- const char *super_version;
-
/* Preparation: Fill version and, if possible, also versionex.
But try to call GetVersionEx only once in the common case. */
+ OSVERSIONINFO version;
+ OSVERSIONINFOEX versionex;
versionex.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEX);
- have_versionex = GetVersionEx ((OSVERSIONINFO *) &versionex);
+ BOOL have_versionex = /* indicates whether versionex is filled */
+ GetVersionEx ((OSVERSIONINFO *) &versionex);
if (have_versionex)
{
/* We know that OSVERSIONINFO is a subset of OSVERSIONINFOEX. */
strcpy (buf->nodename, "localhost");
/* Determine major-major Windows version. */
+ const char *super_version;
if (version.dwPlatformId == VER_PLATFORM_WIN32_NT)
{
/* Windows NT or newer. */
VERSION2 (6, 1, "Windows 7", "Windows Server 2008 R2"),
VERSION2 (-1, -1, "Windows", "Windows Server")
};
- const char *base;
- const struct windows_version *v = versions;
/* Find a version that matches ours. The last element is a
wildcard that always ends the loop. */
+ const struct windows_version *v = versions;
while ((v->major != version.dwMajorVersion && v->major != -1)
|| (v->minor != version.dwMinorVersion && v->minor != -1))
v++;
+ const char *base;
if (have_versionex && versionex.wProductType != VER_NT_WORKSTATION)
base = v->name + v->server_offset;
else
uc_locale_language (void)
{
const char *locale_name = gl_locale_name (LC_CTYPE, "LC_CTYPE");
- const char *p;
/* Find the end of the language portion. */
- p = locale_name;
+ const char *p = locale_name;
while (*p != '\0' && *p != '_' && *p != '.' && *p != '@')
p++;
FUNC (const SRC_UNIT *s1, size_t n1, const SRC_UNIT *s2, size_t n2,
const char *iso639_language, uninorm_t nf, int *resultp)
{
- UNIT buf1[2048 / sizeof (UNIT)];
- UNIT buf2[2048 / sizeof (UNIT)];
- UNIT *norms1;
- size_t norms1_length;
- UNIT *norms2;
- size_t norms2_length;
- int cmp;
-
/* Optimization: There is no need to do canonical composition of each string.
Decomposition is enough. */
if (nf != NULL)
nf = uninorm_decomposing_form (nf);
/* Case-fold and normalize S1. */
- norms1_length = sizeof (buf1) / sizeof (UNIT);
- norms1 = U_CASEFOLD (s1, n1, iso639_language, nf, buf1, &norms1_length);
+ UNIT buf1[2048 / sizeof (UNIT)];
+ size_t norms1_length = sizeof (buf1) / sizeof (UNIT);
+ UNIT *norms1 = U_CASEFOLD (s1, n1, iso639_language, nf, buf1, &norms1_length);
if (norms1 == NULL)
/* errno is set here. */
return -1;
/* Case-fold and normalize S2. */
- norms2_length = sizeof (buf2) / sizeof (UNIT);
- norms2 = U_CASEFOLD (s2, n2, iso639_language, nf, buf2, &norms2_length);
+ UNIT buf2[2048 / sizeof (UNIT)];
+ size_t norms2_length = sizeof (buf2) / sizeof (UNIT);
+ UNIT *norms2 = U_CASEFOLD (s2, n2, iso639_language, nf, buf2, &norms2_length);
if (norms2 == NULL)
{
if (norms1 != buf1)
}
/* Compare the normalized strings. */
- cmp = U_CMP2 (norms1, norms1_length, norms2, norms2_length);
+ int cmp = U_CMP2 (norms1, norms1_length, norms2, norms2_length);
if (cmp > 0)
cmp = 1;
else if (cmp < 0)
FUNC (const UNIT *s1, size_t n1, const UNIT *s2, size_t n2,
const char *iso639_language, uninorm_t nf, int *resultp)
{
- char buf1[2048];
- char buf2[2048];
- char *transformed1;
- size_t transformed1_length;
- char *transformed2;
- size_t transformed2_length;
- int cmp;
-
/* Normalize and transform S1. */
- transformed1_length = sizeof (buf1);
- transformed1 =
+ char buf1[2048];
+ size_t transformed1_length = sizeof (buf1);
+ char *transformed1 =
U_CASEXFRM (s1, n1, iso639_language, nf, buf1, &transformed1_length);
if (transformed1 == NULL)
/* errno is set here. */
return -1;
/* Normalize and transform S2. */
- transformed2_length = sizeof (buf2);
- transformed2 =
+ char buf2[2048];
+ size_t transformed2_length = sizeof (buf2);
+ char *transformed2 =
U_CASEXFRM (s2, n2, iso639_language, nf, buf2, &transformed2_length);
if (transformed2 == NULL)
{
}
/* Compare the transformed strings. */
- cmp = memcmp2 (transformed1, transformed1_length,
- transformed2, transformed2_length);
+ int cmp = memcmp2 (transformed1, transformed1_length,
+ transformed2, transformed2_length);
if (cmp < 0)
cmp = -1;
else if (cmp > 0)
{
/* The result being accumulated. */
UNIT *result;
- size_t length;
size_t allocated;
-
- /* Initialize the accumulator. */
if (nf != NULL || resultbuf == NULL)
{
result = NULL;
result = resultbuf;
allocated = *lengthp;
}
- length = 0;
+ size_t length = 0;
{
const UNIT *s_end = s + n;
{
/* Does the context apply? */
int context = rule->context;
- bool applies;
-
if (context < 0)
context = - context;
+
+ bool applies;
switch (context)
{
case SCC_ALWAYS:
if (nf != NULL)
{
/* Finally, normalize the result. */
- UNIT *normalized_result;
-
- normalized_result = U_NORMALIZE (nf, result, length, resultbuf, lengthp);
+ UNIT *normalized_result =
+ U_NORMALIZE (nf, result, length, resultbuf, lengthp);
if (normalized_result == NULL)
goto fail;
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- UNIT *memory;
-
- memory = (UNIT *) realloc (result, length * sizeof (UNIT));
+ UNIT *memory = (UNIT *) realloc (result, length * sizeof (UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const UNIT *s, size_t n, const char *iso639_language, uninorm_t nf,
char *resultbuf, size_t *lengthp)
{
- UNIT foldedsbuf[2048 / sizeof (UNIT)];
- UNIT *foldeds;
- size_t foldeds_length;
- char convsbuf[2048];
- char *convs;
- size_t convs_length;
- char *result;
-
/* Casefold and normalize the Unicode string. */
- foldeds_length = sizeof (foldedsbuf) / sizeof (UNIT);
- foldeds = U_CASEFOLD (s, n, iso639_language, nf, foldedsbuf, &foldeds_length);
+ UNIT foldedsbuf[2048 / sizeof (UNIT)];
+ size_t foldeds_length = sizeof (foldedsbuf) / sizeof (UNIT);
+ UNIT *foldeds = U_CASEFOLD (s, n, iso639_language, nf, foldedsbuf, &foldeds_length);
if (foldeds == NULL)
/* errno is set here. */
return NULL;
/* Convert it to locale encoding. */
- convs_length = sizeof (convsbuf) - 1;
- convs = U_CONV_TO_ENCODING (locale_charset (),
- iconveh_error,
- foldeds, foldeds_length,
- NULL,
- convsbuf, &convs_length);
+ char convsbuf[2048];
+ size_t convs_length = sizeof (convsbuf) - 1;
+ char *convs = U_CONV_TO_ENCODING (locale_charset (),
+ iconveh_error,
+ foldeds, foldeds_length,
+ NULL,
+ convsbuf, &convs_length);
if (convs == NULL)
{
if (foldeds != foldedsbuf)
}
/* Apply locale dependent transformations for comparison. */
- result = amemxfrm (convs, convs_length, resultbuf, lengthp);
+ char *result = amemxfrm (convs, convs_length, resultbuf, lengthp);
if (result == NULL)
{
if (convs != convsbuf)
/* X -> nf(toCasefold(NFD(X))) or
X -> nf(toCasefold(nfd(toCasefold(NFD(X))))) */
int repeat = (uninorm_is_compat_decomposing (nf) ? 2 : 1);
- UNIT tmpbuf1[2048 / sizeof (UNIT)];
- UNIT tmpbuf2[2048 / sizeof (UNIT)];
- UNIT *tmp1;
- size_t tmp1_length;
- UNIT *tmp2;
- size_t tmp2_length;
- tmp1_length = sizeof (tmpbuf1) / sizeof (UNIT);
- tmp1 = U_NORMALIZE (UNINORM_NFD, s, n, tmpbuf1, &tmp1_length);
+ UNIT tmpbuf1[2048 / sizeof (UNIT)];
+ size_t tmp1_length = sizeof (tmpbuf1) / sizeof (UNIT);
+ UNIT *tmp1 = U_NORMALIZE (UNINORM_NFD, s, n, tmpbuf1, &tmp1_length);
if (tmp1 == NULL)
/* errno is set here. */
return NULL;
do
{
- tmp2_length = sizeof (tmpbuf2) / sizeof (UNIT);
- tmp2 = U_CASEMAP (tmp1, tmp1_length,
- prefix_context, suffix_context, iso639_language,
- uc_tocasefold, offsetof (struct special_casing_rule, casefold[0]),
- NULL,
- tmpbuf2, &tmp2_length);
+ UNIT tmpbuf2[2048 / sizeof (UNIT)];
+ size_t tmp2_length = sizeof (tmpbuf2) / sizeof (UNIT);
+ UNIT *tmp2 = U_CASEMAP (tmp1, tmp1_length,
+ prefix_context, suffix_context, iso639_language,
+ uc_tocasefold, offsetof (struct special_casing_rule, casefold[0]),
+ NULL,
+ tmpbuf2, &tmp2_length);
if (tmp2 == NULL)
{
int saved_errno = errno;
{
/* The result being accumulated. */
UNIT *result;
- size_t length;
size_t allocated;
- /* An array containing the word break positions. */
- char *wordbreaks;
-
- /* Initialize the accumulator. */
if (nf != NULL || resultbuf == NULL)
{
result = NULL;
result = resultbuf;
allocated = *lengthp;
}
- length = 0;
+ size_t length = 0;
+ /* An array containing the word break positions. */
+ char *wordbreaks;
/* Initialize the word breaks array. */
if (n > 0)
{
ucs4_t uc;
int count = U_MBTOUC_UNSAFE (&uc, s, s_end - s);
- ucs4_t (*single_character_map) (ucs4_t);
- size_t offset_in_rule; /* offset in 'struct special_casing_rule' */
-
- ucs4_t mapped_uc[3];
- unsigned int mapped_count;
-
if (*wp)
/* Crossing a word boundary. */
in_word_first_part = true;
+ ucs4_t (*single_character_map) (ucs4_t);
+ size_t offset_in_rule; /* offset in 'struct special_casing_rule' */
+
/* Determine single_character_map, offset_in_rule.
There are three possibilities:
- uc should not be converted.
offset_in_rule = offsetof (struct special_casing_rule, lower[0]);
}
+ ucs4_t mapped_uc[3];
+ unsigned int mapped_count;
+
/* Actually map uc. */
if (single_character_map == NULL)
{
{
/* Does the context apply? */
int context = rule->context;
- bool applies;
if (context < 0)
context = - context;
+
+ bool applies;
switch (context)
{
case SCC_ALWAYS:
if (nf != NULL)
{
/* Finally, normalize the result. */
- UNIT *normalized_result;
-
- normalized_result = U_NORMALIZE (nf, result, length, resultbuf, lengthp);
+ UNIT *normalized_result =
+ U_NORMALIZE (nf, result, length, resultbuf, lengthp);
if (normalized_result == NULL)
goto fail2;
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- UNIT *memory;
-
- memory = (UNIT *) realloc (result, length * sizeof (UNIT));
+ UNIT *memory = (UNIT *) realloc (result, length * sizeof (UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const UNIT *s, size_t n, const char *iso639_language,
bool *resultp)
{
- UNIT normsbuf[2048 / sizeof (UNIT)];
- UNIT *norms;
- size_t norms_length;
- UNIT mappedbuf[2048 / sizeof (UNIT)];
- UNIT *mapped_toupper;
- UNIT *mapped_tolower;
- UNIT *mapped_totitle;
- size_t mapped_length;
-
/* Apply canonical decomposition to S. */
- norms_length = sizeof (normsbuf) / sizeof (UNIT);
- norms = U_NORMALIZE (UNINORM_NFD, s, n, normsbuf, &norms_length);
+ UNIT normsbuf[2048 / sizeof (UNIT)];
+ size_t norms_length = sizeof (normsbuf) / sizeof (UNIT);
+ UNIT *norms = U_NORMALIZE (UNINORM_NFD, s, n, normsbuf, &norms_length);
if (norms == NULL)
/* errno is set here. */
return -1;
- mapped_length = sizeof (mappedbuf) / sizeof (UNIT);
+ UNIT mappedbuf[2048 / sizeof (UNIT)];
+ size_t mapped_length = sizeof (mappedbuf) / sizeof (UNIT);
/* Apply toupper mapping. */
- mapped_toupper = U_TOUPPER (norms, norms_length, iso639_language, NULL,
- mappedbuf, &mapped_length);
+ UNIT *mapped_toupper = U_TOUPPER (norms, norms_length, iso639_language, NULL,
+ mappedbuf, &mapped_length);
if (mapped_toupper == NULL)
goto fail;
}
/* Apply tolower mapping. */
- mapped_tolower = U_TOLOWER (norms, norms_length, iso639_language, NULL,
- mapped_toupper, &mapped_length);
+ UNIT *mapped_tolower = U_TOLOWER (norms, norms_length, iso639_language, NULL,
+ mapped_toupper, &mapped_length);
if (mapped_tolower == NULL)
{
if (mapped_toupper != mappedbuf)
}
/* Apply totitle mapping. */
- mapped_totitle = U_TOTITLE (norms, norms_length, iso639_language, NULL,
- mapped_tolower, &mapped_length);
+ UNIT *mapped_totitle = U_TOTITLE (norms, norms_length, iso639_language, NULL,
+ mapped_tolower, &mapped_length);
if (mapped_totitle == NULL)
{
if (mapped_tolower != mappedbuf)
const char *iso639_language,
bool *resultp)
{
- UNIT normsbuf[2048 / sizeof (UNIT)];
- UNIT *norms;
- size_t norms_length;
- UNIT mappedbuf[2048 / sizeof (UNIT)];
- UNIT *mapped;
- size_t mapped_length;
-
/* Apply canonical decomposition to S. */
- norms_length = sizeof (normsbuf) / sizeof (UNIT);
- norms = U_NORMALIZE (UNINORM_NFD, s, n, normsbuf, &norms_length);
+ UNIT normsbuf[2048 / sizeof (UNIT)];
+ size_t norms_length = sizeof (normsbuf) / sizeof (UNIT);
+ UNIT *norms = U_NORMALIZE (UNINORM_NFD, s, n, normsbuf, &norms_length);
if (norms == NULL)
/* errno is set here. */
return -1;
/* Apply mapping. */
- mapped_length = sizeof (mappedbuf) / sizeof (UNIT);
- mapped = mapping (norms, norms_length, iso639_language, NULL,
- mappedbuf, &mapped_length);
+ UNIT mappedbuf[2048 / sizeof (UNIT)];
+ size_t mapped_length = sizeof (mappedbuf) / sizeof (UNIT);
+ UNIT *mapped = mapping (norms, norms_length, iso639_language, NULL,
+ mappedbuf, &mapped_length);
if (mapped == NULL)
{
if (norms != normsbuf)
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
uninorm_t nf,
uint8_t *resultbuf, size_t *lengthp)
{
- uint8_t convbuf[2048 / sizeof (uint8_t)];
- uint8_t *conv;
- size_t conv_length;
- uint8_t *result;
-
/* Convert the string to UTF-8. */
- conv_length = sizeof (convbuf) / sizeof (uint8_t);
- conv =
+ uint8_t convbuf[2048 / sizeof (uint8_t)];
+ size_t conv_length = sizeof (convbuf) / sizeof (uint8_t);
+ uint8_t *conv =
u8_conv_from_encoding (locale_charset (), iconveh_error, s, n, NULL,
convbuf, &conv_length);
if (conv == NULL)
return NULL;
/* Case-fold and normalize. */
- result = u8_casefold (conv, conv_length, iso639_language, nf,
- resultbuf, lengthp);
+ uint8_t *result = u8_casefold (conv, conv_length, iso639_language, nf,
+ resultbuf, lengthp);
if (result == NULL)
{
if (conv != convbuf)
uninorm_t nf,
char *resultbuf, size_t *lengthp)
{
- uint8_t convbuf[2048 / sizeof (uint8_t)];
- uint8_t *conv;
- size_t conv_length;
- char *result;
-
/* Convert the string to UTF-8. */
- conv_length = sizeof (convbuf) / sizeof (uint8_t);
- conv =
+ uint8_t convbuf[2048 / sizeof (uint8_t)];
+ size_t conv_length = sizeof (convbuf) / sizeof (uint8_t);
+ uint8_t *conv =
u8_conv_from_encoding (locale_charset (), iconveh_error, s, n, NULL,
convbuf, &conv_length);
if (conv == NULL)
return NULL;
/* Case-fold and normalize. */
- result = u8_casexfrm (conv, conv_length, iso639_language, nf,
- resultbuf, lengthp);
+ char *result = u8_casexfrm (conv, conv_length, iso639_language, nf,
+ resultbuf, lengthp);
if (result == NULL)
{
if (conv != convbuf)
static iconv_t utf8_to_local;
#endif
- char inbuf[6];
- int count;
-
if (!initialized)
{
const char *charset = locale_charset ();
}
/* Convert the character to UTF-8. */
- count = u8_uctomb ((unsigned char *) inbuf, code, sizeof (inbuf));
+ char inbuf[6];
+ int count = u8_uctomb ((unsigned char *) inbuf, code, sizeof (inbuf));
if (count < 0)
return failure (code, _("character out of range"), callback_arg);
if (!is_utf8)
{
char outbuf[25];
- const char *inptr;
- size_t inbytesleft;
- char *outptr;
- size_t outbytesleft;
- size_t res;
-
- inptr = inbuf;
- inbytesleft = count;
- outptr = outbuf;
- outbytesleft = sizeof (outbuf);
+ const char *inptr = inbuf;
+ size_t inbytesleft = count;
+ char *outptr = outbuf;
+ size_t outbytesleft = sizeof (outbuf);
/* Convert the character from UTF-8 to the locale's charset. */
- res = iconv (utf8_to_local,
- (ICONV_CONST char **)&inptr, &inbytesleft,
- &outptr, &outbytesleft);
+ size_t res = iconv (utf8_to_local,
+ (ICONV_CONST char **)&inptr, &inbytesleft,
+ &outptr, &outbytesleft);
/* Analyze what iconv() actually did and distinguish replacements
that are OK (no need to invoke the FAILURE callback), such as
- replacing GREEK SMALL LETTER MU with MICRO SIGN, or
*lengthp = length / sizeof (UNIT);
return (UNIT *) result;
#else
- uint8_t *utf8_string;
size_t utf8_length;
- UNIT *result;
-
- utf8_string =
+ uint8_t *utf8_string =
u8_conv_from_encoding (fromcode, handler, src, srclen, offsets,
NULL, &utf8_length);
if (utf8_string == NULL)
return NULL;
- result = U8_TO_U (utf8_string, utf8_length, resultbuf, lengthp);
+
+ UNIT *result = U8_TO_U (utf8_string, utf8_length, resultbuf, lengthp);
if (result == NULL)
{
int saved_errno = errno;
{
size_t length = *lengthp;
size_t *offsets_end = offsets + srclen;
- size_t off8 = 0; /* offset into utf8_string */
- size_t offunit = 0; /* offset into result */
+ size_t off8 = 0; /* offset into utf8_string */
+ size_t offunit = 0; /* offset into result */
for (size_t *o = offsets; o < offsets_end; o++)
if (*o != (size_t)(-1))
{
{
#if HAVE_UTF_NAME
size_t *scaled_offsets;
- char *result;
- size_t length;
-
if (offsets != NULL && srclen > 0)
{
scaled_offsets =
else
scaled_offsets = NULL;
- result = resultbuf;
- length = *lengthp;
+ char *result = resultbuf;
+ size_t length = *lengthp;
if (mem_iconveha ((const char *) src, srclen * sizeof (UNIT),
UTF_NAME, tocode,
handler == iconveh_question_mark, handler,
#else
uint8_t tmpbuf[4096];
size_t tmpbufsize = SIZEOF (tmpbuf);
- uint8_t *utf8_src;
- size_t utf8_srclen;
- size_t *scaled_offsets;
- char *result;
-
- utf8_src = U_TO_U8 (src, srclen, tmpbuf, &tmpbufsize);
+ uint8_t *utf8_src = U_TO_U8 (src, srclen, tmpbuf, &tmpbufsize);
if (utf8_src == NULL)
return NULL;
- utf8_srclen = tmpbufsize;
+ size_t utf8_srclen = tmpbufsize;
+ size_t *scaled_offsets;
if (offsets != NULL && utf8_srclen > 0)
{
scaled_offsets = (size_t *) malloc (utf8_srclen * sizeof (size_t));
else
scaled_offsets = NULL;
- result = u8_conv_to_encoding (tocode, handler, utf8_src, utf8_srclen,
- scaled_offsets, resultbuf, lengthp);
+ char *result = u8_conv_to_encoding (tocode, handler, utf8_src, utf8_srclen,
+ scaled_offsets, resultbuf, lengthp);
if (result == NULL)
{
int saved_errno = errno;
for (size_t iunit = 0; iunit < srclen; iunit++)
offsets[iunit] = (size_t)(-1);
- size_t iunit; /* offset into src */
- size_t i8; /* offset into utf8_src */
-
- iunit = 0;
- i8 = 0;
+ size_t iunit = 0; /* offset into src */
+ size_t i8 = 0; /* offset into utf8_src */
while (iunit < srclen && i8 < utf8_srclen)
{
- int countunit;
- int count8;
-
offsets[iunit] = scaled_offsets[i8];
- countunit = U_MBLEN (src + iunit, srclen - iunit);
- count8 = u8_mblen (utf8_src + i8, utf8_srclen - i8);
+ int countunit = U_MBLEN (src + iunit, srclen - iunit);
+ int count8 = u8_mblen (utf8_src + i8, utf8_srclen - i8);
if (countunit < 0 || count8 < 0)
abort ();
iunit += countunit;
const char *fromcode,
enum iconv_ilseq_handler handler)
{
- UNIT *result;
size_t length;
-
- result =
+ UNIT *result =
U_CONV_FROM_ENCODING (fromcode, handler,
string, strlen (string) + 1, NULL,
NULL, &length);
#else
uint8_t tmpbuf[4096];
size_t tmpbufsize = SIZEOF (tmpbuf);
- uint8_t *utf8_string;
- char *result;
-
- utf8_string = U_TO_U8 (string, U_STRLEN (string) + 1, tmpbuf, &tmpbufsize);
+ uint8_t *utf8_string = U_TO_U8 (string, U_STRLEN (string) + 1, tmpbuf, &tmpbufsize);
if (utf8_string == NULL)
return NULL;
- result = u8_strconv_to_encoding (utf8_string, tocode, handler);
+ char *result = u8_strconv_to_encoding (utf8_string, tocode, handler);
if (result == NULL)
{
if (utf8_string != tmpbuf)
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- count = u16_mbtoucr (&uc, s, s_end - s);
+ ucs4_t uc;
+ int count = u16_mbtoucr (&uc, s, s_end - s);
if (count < 0)
{
if (count == -2)
}
if (count == -2)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 6 > allocated)
allocated = length + 6;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
if (STRCASEEQ (fromcode, "UTF-8", 'U','T','F','-','8',0,0,0,0))
{
/* Conversion from UTF-8 to UTF-8. No need to go through iconv(). */
- uint8_t *result;
if (u8_check ((const uint8_t *) src, srclen))
{
}
/* Memory allocation. */
+ uint8_t *result;
if (resultbuf != NULL && *lengthp >= srclen)
result = resultbuf;
else
{
if (STRCASEEQ (tocode, "UTF-8", 'U','T','F','-','8',0,0,0,0))
{
- char *result;
-
/* Conversion from UTF-8 to UTF-8. No need to go through iconv(). */
if (u8_check (src, srclen))
{
}
/* Memory allocation. */
+ char *result;
if (resultbuf != NULL && *lengthp >= srclen)
result = resultbuf;
else
const char *tocode,
enum iconv_ilseq_handler handler)
{
- char *result;
- size_t length;
-
if (STRCASEEQ (tocode, "UTF-8", 'U','T','F','-','8',0,0,0,0))
{
/* Conversion from UTF-8 to UTF-8. No need to go through iconv(). */
- length = u8_strlen (string) + 1;
+ size_t length = u8_strlen (string) + 1;
if (u8_check (string, length))
{
errno = EILSEQ;
return NULL;
}
- result = (char *) malloc (length);
+ char *result = (char *) malloc (length);
if (result == NULL)
{
errno = ENOMEM;
}
else
{
- result = NULL;
- length = 0;
+ char *result = NULL;
+ size_t length = 0;
if (mem_iconveha ((const char *) string, u8_strlen (string) + 1,
"UTF-8", tocode,
handler == iconveh_question_mark, handler,
uint32_t index1 = wc >> (t->q + t->p);
uint32_t index2 = (wc >> t->p) & ((1 << t->q) - 1);
uint32_t index3 = wc & ((1 << t->p) - 1);
- size_t i1, i2;
if (value == CONCAT(TABLE,_get) (t, wc))
return;
(alloc << t->q) * sizeof (uint32_t));
t->level2_alloc = alloc;
}
- i1 = t->level2_size << t->q;
- i2 = (t->level2_size + 1) << t->q;
+ size_t i1 = t->level2_size << t->q;
+ size_t i2 = (t->level2_size + 1) << t->q;
for (size_t i = i1; i < i2; i++)
t->level2[i] = EMPTY;
t->level1[index1] = t->level2_size++;
(alloc << t->p) * sizeof (ELEMENT));
t->level3_alloc = alloc;
}
- i1 = t->level3_size << t->p;
- i2 = (t->level3_size + 1) << t->p;
+ size_t i1 = t->level3_size << t->p;
+ size_t i2 = (t->level3_size + 1) << t->p;
for (size_t i = i1; i < i2; i++)
t->level3[i] = DEFAULT;
t->level2[index2] = t->level3_size++;
static void
CONCAT(TABLE,_finalize) (struct TABLE *t)
{
- size_t k;
- uint32_t reorder3[t->level3_size];
- uint32_t reorder2[t->level2_size];
- uint32_t level1_offset, level2_offset, level3_offset, last_offset;
-
/* Uniquify level3 blocks. */
- k = 0;
- for (size_t j = 0; j < t->level3_size; j++)
+ {
+ uint32_t reorder3[t->level3_size];
{
- size_t i;
- for (i = 0; i < k; i++)
- if (memeq (&t->level3[i << t->p], &t->level3[j << t->p],
- (1 << t->p) * sizeof (ELEMENT)))
- break;
- /* Relocate block j to block i. */
- reorder3[j] = i;
- if (i == k)
+ size_t k = 0;
+ for (size_t j = 0; j < t->level3_size; j++)
{
- if (i != j)
- memcpy (&t->level3[i << t->p], &t->level3[j << t->p],
- (1 << t->p) * sizeof (ELEMENT));
- k++;
+ size_t i;
+ for (i = 0; i < k; i++)
+ if (memeq (&t->level3[i << t->p], &t->level3[j << t->p],
+ (1 << t->p) * sizeof (ELEMENT)))
+ break;
+ /* Relocate block j to block i. */
+ reorder3[j] = i;
+ if (i == k)
+ {
+ if (i != j)
+ memcpy (&t->level3[i << t->p], &t->level3[j << t->p],
+ (1 << t->p) * sizeof (ELEMENT));
+ k++;
+ }
}
+ t->level3_size = k;
}
- t->level3_size = k;
- for (size_t i = 0; i < (t->level2_size << t->q); i++)
- if (t->level2[i] != EMPTY)
- t->level2[i] = reorder3[t->level2[i]];
+ for (size_t i = 0; i < (t->level2_size << t->q); i++)
+ if (t->level2[i] != EMPTY)
+ t->level2[i] = reorder3[t->level2[i]];
+ }
/* Uniquify level2 blocks. */
- k = 0;
- for (size_t j = 0; j < t->level2_size; j++)
+ {
+ uint32_t reorder2[t->level2_size];
{
- size_t i;
- for (i = 0; i < k; i++)
- if (memeq (&t->level2[i << t->q], &t->level2[j << t->q],
- (1 << t->q) * sizeof (uint32_t)))
- break;
- /* Relocate block j to block i. */
- reorder2[j] = i;
- if (i == k)
+ size_t k = 0;
+ for (size_t j = 0; j < t->level2_size; j++)
{
- if (i != j)
- memcpy (&t->level2[i << t->q], &t->level2[j << t->q],
- (1 << t->q) * sizeof (uint32_t));
- k++;
+ size_t i;
+ for (i = 0; i < k; i++)
+ if (memeq (&t->level2[i << t->q], &t->level2[j << t->q],
+ (1 << t->q) * sizeof (uint32_t)))
+ break;
+ /* Relocate block j to block i. */
+ reorder2[j] = i;
+ if (i == k)
+ {
+ if (i != j)
+ memcpy (&t->level2[i << t->q], &t->level2[j << t->q],
+ (1 << t->q) * sizeof (uint32_t));
+ k++;
+ }
}
+ t->level2_size = k;
}
- t->level2_size = k;
- for (size_t i = 0; i < t->level1_size; i++)
- if (t->level1[i] != EMPTY)
- t->level1[i] = reorder2[t->level1[i]];
+ for (size_t i = 0; i < t->level1_size; i++)
+ if (t->level1[i] != EMPTY)
+ t->level1[i] = reorder2[t->level1[i]];
+ }
/* Create and fill the resulting compressed representation. */
- last_offset =
+ uint32_t last_offset =
5 * sizeof (uint32_t)
+ t->level1_size * sizeof (uint32_t)
+ (t->level2_size << t->q) * sizeof (uint32_t)
t->result_size = (last_offset + 3) & ~3ul;
t->result = (char *) xmalloc (t->result_size);
- level1_offset =
+ uint32_t level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ uint32_t level2_offset =
5 * sizeof (uint32_t)
+ t->level1_size * sizeof (uint32_t);
- level3_offset =
+ uint32_t level3_offset =
5 * sizeof (uint32_t)
+ t->level1_size * sizeof (uint32_t)
+ (t->level2_size << t->q) * sizeof (uint32_t);
uint32_t index2 = (wc >> (t->p + 5)) & ((1 << t->q) - 1);
uint32_t index3 = (wc >> 5) & ((1 << t->p) - 1);
uint32_t index4 = wc & 0x1f;
- size_t i1, i2;
if (index1 >= t->level1_size)
{
(alloc << t->q) * sizeof (uint32_t));
t->level2_alloc = alloc;
}
- i1 = t->level2_size << t->q;
- i2 = (t->level2_size + 1) << t->q;
+ size_t i1 = t->level2_size << t->q;
+ size_t i2 = (t->level2_size + 1) << t->q;
for (size_t i = i1; i < i2; i++)
t->level2[i] = EMPTY;
t->level1[index1] = t->level2_size++;
(alloc << t->p) * sizeof (uint32_t));
t->level3_alloc = alloc;
}
- i1 = t->level3_size << t->p;
- i2 = (t->level3_size + 1) << t->p;
+ size_t i1 = t->level3_size << t->p;
+ size_t i2 = (t->level3_size + 1) << t->p;
for (size_t i = i1; i < i2; i++)
t->level3[i] = 0;
t->level2[index2] = t->level3_size++;
static void
CONCAT(TABLE,_finalize) (struct TABLE *t)
{
- size_t k;
- uint32_t reorder3[t->level3_size];
- uint32_t reorder2[t->level2_size];
uint32_t level1_offset, level2_offset, level3_offset;
/* Uniquify level3 blocks. */
- k = 0;
- for (size_t j = 0; j < t->level3_size; j++)
+ {
+ uint32_t reorder3[t->level3_size];
{
- size_t i;
- for (i = 0; i < k; i++)
- if (memeq (&t->level3[i << t->p], &t->level3[j << t->p],
- (1 << t->p) * sizeof (uint32_t)))
- break;
- /* Relocate block j to block i. */
- reorder3[j] = i;
- if (i == k)
+ size_t k = 0;
+ for (size_t j = 0; j < t->level3_size; j++)
{
- if (i != j)
- memcpy (&t->level3[i << t->p], &t->level3[j << t->p],
- (1 << t->p) * sizeof (uint32_t));
- k++;
+ size_t i;
+ for (i = 0; i < k; i++)
+ if (memeq (&t->level3[i << t->p], &t->level3[j << t->p],
+ (1 << t->p) * sizeof (uint32_t)))
+ break;
+ /* Relocate block j to block i. */
+ reorder3[j] = i;
+ if (i == k)
+ {
+ if (i != j)
+ memcpy (&t->level3[i << t->p], &t->level3[j << t->p],
+ (1 << t->p) * sizeof (uint32_t));
+ k++;
+ }
}
+ t->level3_size = k;
}
- t->level3_size = k;
- for (size_t i = 0; i < (t->level2_size << t->q); i++)
- if (t->level2[i] != EMPTY)
- t->level2[i] = reorder3[t->level2[i]];
+ for (size_t i = 0; i < (t->level2_size << t->q); i++)
+ if (t->level2[i] != EMPTY)
+ t->level2[i] = reorder3[t->level2[i]];
+ }
/* Uniquify level2 blocks. */
- k = 0;
- for (size_t j = 0; j < t->level2_size; j++)
+ {
+ uint32_t reorder2[t->level2_size];
{
- size_t i;
- for (i = 0; i < k; i++)
- if (memeq (&t->level2[i << t->q], &t->level2[j << t->q],
- (1 << t->q) * sizeof (uint32_t)))
- break;
- /* Relocate block j to block i. */
- reorder2[j] = i;
- if (i == k)
+ size_t k = 0;
+ for (size_t j = 0; j < t->level2_size; j++)
{
- if (i != j)
- memcpy (&t->level2[i << t->q], &t->level2[j << t->q],
- (1 << t->q) * sizeof (uint32_t));
- k++;
+ size_t i;
+ for (i = 0; i < k; i++)
+ if (memeq (&t->level2[i << t->q], &t->level2[j << t->q],
+ (1 << t->q) * sizeof (uint32_t)))
+ break;
+ /* Relocate block j to block i. */
+ reorder2[j] = i;
+ if (i == k)
+ {
+ if (i != j)
+ memcpy (&t->level2[i << t->q], &t->level2[j << t->q],
+ (1 << t->q) * sizeof (uint32_t));
+ k++;
+ }
}
+ t->level2_size = k;
}
- t->level2_size = k;
- for (size_t i = 0; i < t->level1_size; i++)
- if (t->level1[i] != EMPTY)
- t->level1[i] = reorder2[t->level1[i]];
+ for (size_t i = 0; i < t->level1_size; i++)
+ if (t->level1[i] != EMPTY)
+ t->level1[i] = reorder2[t->level1[i]];
+ }
/* Create and fill the resulting compressed representation. */
t->result_size =
+ (t->level3_size << t->p) * sizeof (uint32_t);
t->result = (char *) xmalloc (t->result_size);
- level1_offset =
+ uint32_t level1_offset =
5 * sizeof (uint32_t);
- level2_offset =
+ uint32_t level2_offset =
5 * sizeof (uint32_t)
+ t->level1_size * sizeof (uint32_t);
- level3_offset =
+ uint32_t level3_offset =
5 * sizeof (uint32_t)
+ t->level1_size * sizeof (uint32_t)
+ (t->level2_size << t->q) * sizeof (uint32_t);
int
uc_bidi_class_byname (const char *bidi_class_name)
{
- size_t len;
-
- len = strlen (bidi_class_name);
+ size_t len = strlen (bidi_class_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_bidi_class *found;
/* Copy bidi_class_name into buf, converting '_' and '-' to ' '. */
{
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_bidi_class_lookup (buf, len);
+ const struct named_bidi_class *found = uc_bidi_class_lookup (buf, len);
if (found != NULL)
return found->bidi_class;
}
uc_general_category_and (uc_general_category_t category1,
uc_general_category_t category2)
{
- uint32_t bitmask;
- uc_general_category_t result;
-
- bitmask = category1.bitmask & category2.bitmask;
+ uint32_t bitmask = category1.bitmask & category2.bitmask;
if (bitmask == category1.bitmask)
return category1;
if (bitmask == 0)
return _UC_CATEGORY_NONE;
+ uc_general_category_t result;
result.bitmask = bitmask;
result.generic = 1;
result.lookup.lookup_fn = &uc_is_general_category_withtable;
uc_general_category_and_not (uc_general_category_t category1,
uc_general_category_t category2)
{
- uint32_t bitmask;
- uc_general_category_t result;
-
- bitmask = category1.bitmask & ~category2.bitmask;
+ uint32_t bitmask = category1.bitmask & ~category2.bitmask;
if (bitmask == category1.bitmask)
return category1;
if (bitmask == 0)
return _UC_CATEGORY_NONE;
+ uc_general_category_t result;
result.bitmask = bitmask;
result.generic = 1;
result.lookup.lookup_fn = &uc_is_general_category_withtable;
uc_general_category_t
uc_general_category_byname (const char *category_name)
{
- size_t len;
-
- len = strlen (category_name);
+ size_t len = strlen (category_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_category *found;
/* Copy category_name into buf, converting '_' and '-' to ' '. */
{
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_general_category_lookup (buf, len);
+ const struct named_category *found =
+ uc_general_category_lookup (buf, len);
if (found != NULL)
/* Use a 'switch' statement here, because a table would introduce
load-time relocations. */
uc_general_category (ucs4_t uc)
{
int bit = lookup_withtable (uc);
- uc_general_category_t result;
if (bit >= 0)
{
+ uc_general_category_t result;
result.bitmask = 1 << bit;
result.generic = 1;
result.lookup.lookup_fn = &uc_is_general_category_withtable;
uc_general_category_or (uc_general_category_t category1,
uc_general_category_t category2)
{
- uint32_t bitmask;
- uc_general_category_t result;
-
- bitmask = category1.bitmask | category2.bitmask;
+ uint32_t bitmask = category1.bitmask | category2.bitmask;
if (bitmask == category1.bitmask)
return category1;
if (bitmask == category2.bitmask)
return category2;
+ uc_general_category_t result;
result.bitmask = bitmask;
result.generic = 1;
result.lookup.lookup_fn = &uc_is_general_category_withtable;
int
uc_combining_class_byname (const char *ccc_name)
{
- size_t len;
-
- len = strlen (ccc_name);
+ size_t len = strlen (ccc_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_combining_class *found;
/* Copy ccc_name into buf, converting '_' and '-' to ' '. */
{
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_combining_class_lookup (buf, len);
+ const struct named_combining_class *found =
+ uc_combining_class_lookup (buf, len);
if (found != NULL)
return found->combining_class;
}
if (ccc >= 0)
{
int index;
-
if (ccc < 10)
index = u_combining_class_index_part1[ccc];
else if (ccc >= 200 && ccc < 241)
if (ccc >= 0)
{
int index;
-
if (ccc < 10)
index = u_combining_class_index_part1[ccc];
else if (ccc >= 200 && ccc < 241)
int
uc_indic_conjunct_break_byname (const char *indic_conjunct_break_name)
{
- size_t len;
-
- len = strlen (indic_conjunct_break_name);
+ size_t len = strlen (indic_conjunct_break_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_indic_conjunct_break *found;
/* Copy indic_conjunct_break_name into buf, converting '_' and '-'
to ' '. */
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_indic_conjunct_break_lookup (buf, len);
+ const struct named_indic_conjunct_break *found =
+ uc_indic_conjunct_break_lookup (buf, len);
if (found != NULL)
return found->indic_conjunct_break;
}
int
uc_joining_group_byname (const char *joining_group_name)
{
- size_t len;
-
- len = strlen (joining_group_name);
+ size_t len = strlen (joining_group_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_joining_group *found;
/* Copy joining_group_name into buf, converting '_' and '-' to ' '. */
{
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_joining_group_lookup (buf, len);
+ const struct named_joining_group *found =
+ uc_joining_group_lookup (buf, len);
if (found != NULL)
return found->joining_group;
}
int
uc_joining_type_byname (const char *joining_type_name)
{
- size_t len;
-
- len = strlen (joining_type_name);
+ size_t len = strlen (joining_type_name);
if (len <= MAX_WORD_LENGTH)
{
char buf[MAX_WORD_LENGTH + 1];
- const struct named_joining_type *found;
/* Copy joining_type_name into buf, converting '_' and '-' to ' '. */
{
/* Here q == buf + len. */
/* Do a hash table lookup, with case-insensitive comparison. */
- found = uc_joining_type_lookup (buf, len);
+ const struct named_joining_type *found =
+ uc_joining_type_lookup (buf, len);
if (found != NULL)
return found->joining_type;
}
uc_property_byname (const char *property_name)
{
char buf[MAX_WORD_LENGTH + 1];
- const char *cp;
char *bp;
- unsigned int count;
- const struct named_property *found;
- for (cp = property_name, bp = buf, count = MAX_WORD_LENGTH + 1; ; cp++, bp++)
- {
- unsigned char c = (unsigned char) *cp;
- if (c >= 0x80)
- goto invalid;
- if (c >= 'A' && c <= 'Z')
- c += 'a' - 'A';
- else if (c == ' ' || c == '-')
- c = '_';
- *bp = c;
- if (c == '\0')
- break;
- if (--count == 0)
- goto invalid;
- }
- found = uc_property_lookup (buf, bp - buf);
+ {
+ const char *cp;
+ unsigned int count;
+ for (cp = property_name, bp = buf, count = MAX_WORD_LENGTH + 1; ; cp++, bp++)
+ {
+ unsigned char c = (unsigned char) *cp;
+ if (c >= 0x80)
+ goto invalid;
+ if (c >= 'A' && c <= 'Z')
+ c += 'a' - 'A';
+ else if (c == ' ' || c == '-')
+ c = '_';
+ *bp = c;
+ if (c == '\0')
+ break;
+ if (--count == 0)
+ goto invalid;
+ }
+ }
+
+ const struct named_property *found = uc_property_lookup (buf, bp - buf);
if (found != NULL)
/* Use a 'switch' statement here, because a table would introduce load-time
relocations. */
const uc_script_t *
uc_script_byname (const char *script_name)
{
- const struct named_script *found;
-
- found = uc_script_lookup (script_name, strlen (script_name));
+ const struct named_script *found =
+ uc_script_lookup (script_name, strlen (script_name));
if (found != NULL)
return &scripts[found->index];
else
while (s > s_start)
{
- const UNIT *prev_s;
ucs4_t uc;
-
- prev_s = U_PREV (&uc, s, s_start);
+ const UNIT *prev_s = U_PREV (&uc, s, s_start);
if (prev_s == NULL)
/* Ill-formed UTF-8 encoding. */
break;
{
while (s > s_start)
{
- const UNIT *prev_s;
ucs4_t uc;
-
- prev_s = U_PREV (&uc, s, s_start);
+ const UNIT *prev_s = U_PREV (&uc, s, s_start);
if (prev_s == NULL)
/* Ill-formed UTF-8 encoding. */
break;
while (s > s_start)
{
- const UNIT *prev_s;
ucs4_t uc;
-
- prev_s = U_PREV (&uc, s, s_start);
+ const UNIT *prev_s = U_PREV (&uc, s, s_start);
if (prev_s == NULL)
/* Ill-formed UTF-8 encoding. */
break;
do
{
- const UNIT *prev_s;
ucs4_t uc;
-
- prev_s = U_PREV (&uc, s, s_start);
+ const UNIT *prev_s = U_PREV (&uc, s, s_start);
if (prev_s == NULL)
{
/* Ill-formed UTF-8 encoding. */
bool
uc_is_grapheme_break (ucs4_t a, ucs4_t b)
{
- int a_gcp, b_gcp;
-
if ((a | b) < 0x300)
{
/* GB3 is the only relevant rule for this case. */
return a != '\r' || b != '\n';
}
- a_gcp = uc_graphemeclusterbreak_property (a);
- b_gcp = uc_graphemeclusterbreak_property (b);
+ int a_gcp = uc_graphemeclusterbreak_property (a);
+ int b_gcp = uc_graphemeclusterbreak_property (b);
return (gb_table[a_gcp] >> b_gcp) & 1;
}
if (offsets != NULL)
{
- uint8_t *t;
size_t m;
-
- t = u8_conv_from_encoding (encoding, iconveh_question_mark,
- s, n, offsets, NULL, &m);
+ uint8_t *t =
+ u8_conv_from_encoding (encoding, iconveh_question_mark,
+ s, n, offsets, NULL, &m);
if (t != NULL)
{
char *q = (char *) (m > 0 ? malloc (m) : NULL);
const char *o, const char *encoding, int cr,
char *p)
{
- const uint16_t *s_end;
- char *last_p;
- int last_column;
- int piece_width;
-
u16_possible_linebreaks_loop (s, n, encoding, cr, p);
- s_end = s + n;
- last_p = NULL;
- last_column = start_column;
- piece_width = 0;
+ const uint16_t *s_end = s + n;
+ char *last_p = NULL;
+ int last_column = start_column;
+ int piece_width = 0;
while (s < s_end)
{
ucs4_t uc;
else
{
/* uc is not a line break character. */
- int w;
-
if (*p == UC_BREAK_POSSIBLE)
{
/* Start a new piece. */
*p = UC_BREAK_PROHIBITED;
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
piece_width += w;
}
const char *o, const char *encoding, int cr,
char *p)
{
- const uint32_t *s_end;
- char *last_p;
- int last_column;
- int piece_width;
-
u32_possible_linebreaks_loop (s, n, encoding, cr, p);
- s_end = s + n;
- last_p = NULL;
- last_column = start_column;
- piece_width = 0;
+ const uint32_t *s_end = s + n;
+ char *last_p = NULL;
+ int last_column = start_column;
+ int piece_width = 0;
while (s < s_end)
{
ucs4_t uc = *s;
else
{
/* uc is not a line break character. */
- int w;
-
if (*p == UC_BREAK_POSSIBLE)
{
/* Start a new piece. */
*p = UC_BREAK_PROHIBITED;
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
piece_width += w;
}
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
const char *o, const char *encoding, int cr,
char *p)
{
- const uint8_t *s_end;
- char *last_p;
- int last_column;
- int piece_width;
-
u8_possible_linebreaks_loop (s, n, encoding, cr, p);
- s_end = s + n;
- last_p = NULL;
- last_column = start_column;
- piece_width = 0;
+ const uint8_t *s_end = s + n;
+ char *last_p = NULL;
+ int last_column = start_column;
+ int piece_width = 0;
while (s < s_end)
{
ucs4_t uc;
else
{
/* uc is not a line break character. */
- int w;
-
if (*p == UC_BREAK_POSSIBLE)
{
/* Start a new piece. */
*p = UC_BREAK_PROHIBITED;
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
piece_width += w;
}
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
if (offsets != NULL)
{
- uint8_t *t;
size_t m;
-
- t = u8_conv_from_encoding (encoding, iconveh_question_mark,
- s, n, offsets, NULL, &m);
+ uint8_t *t =
+ u8_conv_from_encoding (encoding, iconveh_question_mark,
+ s, n, offsets, NULL, &m);
if (t != NULL)
{
char *q = (char *) (m > 0 ? malloc (m) : NULL);
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
if (offsets != NULL)
{
- uint8_t *t;
size_t m;
-
- t = u8_conv_from_encoding (encoding, iconveh_question_mark,
- s, n, offsets, NULL, &m);
+ uint8_t *t =
+ u8_conv_from_encoding (encoding, iconveh_question_mark,
+ s, n, offsets, NULL, &m);
if (t != NULL)
{
char *memory =
{
char *q = (char *) memory;
char *o8 = (o != NULL ? (char *) (q + m) : NULL);
- int res_column;
/* Translate the overrides to the UTF-8 string. */
if (o != NULL)
}
/* Determine the line breaks of the UTF-8 string. */
- res_column =
+ int res_column =
u8_width_linebreaks_internal (t, m, width, start_column, at_end_columns, o8, encoding, cr, q);
/* Translate the result back to the original string. */
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
static const char *
unicode_name_word (unsigned int index, unsigned int *lengthp)
{
- unsigned int i1;
- unsigned int i2;
-
assert (index < UNICODE_CHARNAME_NUM_WORDS);
/* Binary search for i with
index < unicode_name_by_length[i+1].ind_offset
*/
- i1 = 0;
- i2 = SIZEOF (unicode_name_by_length) - 1;
+ unsigned int i1 = 0;
+ unsigned int i2 = SIZEOF (unicode_name_by_length) - 1;
while (i2 - i1 > 1)
{
unsigned int i = (i1 + i2) >> 1;
if (c >= 0xAC00 && c <= 0xD7A3)
{
/* Special case for Hangul syllables. Keeps the tables small. */
- char *ptr;
- unsigned int tmp;
- unsigned int index1;
- unsigned int index2;
- unsigned int index3;
- const char *q;
/* buf needs to have at least 16 + 7 + 1 bytes here. */
memcpy (buf, "HANGUL SYLLABLE ", 16);
- ptr = buf + 16;
+ char *ptr = buf + 16;
- tmp = c - 0xAC00;
- index3 = tmp % 28; tmp = tmp / 28;
- index2 = tmp % 21; tmp = tmp / 21;
- index1 = tmp;
+ unsigned int tmp = c - 0xAC00;
+ unsigned int index3 = tmp % 28; tmp = tmp / 28;
+ unsigned int index2 = tmp % 21; tmp = tmp / 21;
+ unsigned int index1 = tmp;
+ const char *q;
q = jamo_initial_short_name[index1];
while (*q != '\0')
*ptr++ = *q++;
{
/* Special case for CJK compatibility ideographs. Keeps the tables
small. */
- char *ptr;
/* buf needs to have at least 28 + 5 + 1 bytes here. */
memcpy (buf, "CJK COMPATIBILITY IDEOGRAPH-", 28);
- ptr = buf + 28;
+ char *ptr = buf + 28;
for (int i = (c < 0x10000 ? 12 : 16); i >= 0; i -= 4)
{
for (;;)
{
{
- int word;
const char *p2 = p1;
while (p2 < ptr && *p2 != ' ')
p2++;
- word = unicode_name_word_lookup (p1, p2 - p1);
+ int word = unicode_name_word_lookup (p1, p2 - p1);
if (word < 0)
break;
if (wordptr == &words[UNICODE_CHARNAME_MAX_WORDS])
2) [AEIOUWY]
3) [BCDGHIJKLMNPST]
*/
- const char *p2;
- const char *p3;
- const char *p4;
-
- p2 = p1;
+ const char *p2 = p1;
while (p2 < ptr
&& (*p2 == 'B' || *p2 == 'C' || *p2 == 'D'
|| *p2 == 'G' || *p2 == 'H' || *p2 == 'J'
|| *p2 == 'P' || *p2 == 'R' || *p2 == 'S'
|| *p2 == 'T'))
p2++;
- p3 = p2;
+ const char *p3 = p2;
while (p3 < ptr
&& (*p3 == 'A' || *p3 == 'E' || *p3 == 'I'
|| *p3 == 'O' || *p3 == 'U' || *p3 == 'W'
|| *p3 == 'Y'))
p3++;
- p4 = p3;
+ const char *p4 = p3;
while (p4 < ptr
&& (*p4 == 'B' || *p4 == 'C' || *p4 == 'D'
|| *p4 == 'G' || *p4 == 'H' || *p4 == 'I'
"Hangul Syllable Decomposition", See also the clarification at
<https://www.unicode.org/versions/Unicode5.1.0/>, section
"Clarification of Hangul Jamo Handling". */
- unsigned int t;
-
uc -= 0xAC00;
- t = uc % 28;
+ unsigned int t = uc % 28;
if (t == 0)
{
- unsigned int v, l;
-
uc = uc / 28;
- v = uc % 21;
- l = uc / 21;
+ unsigned int v = uc % 21;
+ unsigned int l = uc / 21;
decomposition[0] = 0x1100 + l;
decomposition[1] = 0x1161 + v;
decomposition[1] = 0x11A7 + t;
return 2;
#else
- unsigned int v, l;
-
uc = uc / 28;
- v = uc % 21;
- l = uc / 21;
+ unsigned int v = uc % 21;
+ unsigned int l = uc / 21;
decomposition[0] = 0x1100 + l;
decomposition[1] = 0x1161 + v;
is a canonical one. */
if (entry < 0x8000)
{
- const unsigned char *p;
- unsigned int element;
- unsigned int length;
-
- p = &gl_uninorm_decomp_chars_table[3 * entry];
- element = (p[0] << 16) | (p[1] << 8) | p[2];
+ const unsigned char *p = &gl_uninorm_decomp_chars_table[3 * entry];
+ unsigned int element = (p[0] << 16) | (p[1] << 8) | p[2];
/* The first element has 5 bits for the decomposition type. */
if (((element >> 18) & 0x1f) != UC_DECOMP_CANONICAL)
abort ();
- length = 1;
+ unsigned int length = 1;
for (;;)
{
/* Every element has an 18 bits wide Unicode code point. */
}
#else
char codes[6];
- const struct composition_rule *rule;
-
codes[0] = (uc1 >> 16) & 0xff;
codes[1] = (uc1 >> 8) & 0xff;
codes[2] = uc1 & 0xff;
codes[4] = (uc2 >> 8) & 0xff;
codes[5] = uc2 & 0xff;
- rule = gl_uninorm_compose_lookup (codes, 6);
+ const struct composition_rule *rule = gl_uninorm_compose_lookup (codes, 6);
if (rule != NULL)
return rule->combined;
#endif
"Hangul Syllable Decomposition", See also the clarification at
<https://www.unicode.org/versions/Unicode5.1.0/>, section
"Clarification of Hangul Jamo Handling". */
- unsigned int t;
-
uc -= 0xAC00;
- t = uc % 28;
+ unsigned int t = uc % 28;
*decomp_tag = UC_DECOMP_CANONICAL;
if (t == 0)
{
- unsigned int v, l;
-
uc = uc / 28;
- v = uc % 21;
- l = uc / 21;
+ unsigned int v = uc % 21;
+ unsigned int l = uc / 21;
decomposition[0] = 0x1100 + l;
decomposition[1] = 0x1161 + v;
decomposition[1] = 0x11A7 + t;
return 2;
#else
- unsigned int v, l;
-
uc = uc / 28;
- v = uc % 21;
- l = uc / 21;
+ unsigned int v = uc % 21;
+ unsigned int l = uc / 21;
decomposition[0] = 0x1100 + l;
decomposition[1] = 0x1161 + v;
unsigned short entry = decomp_index (uc);
if (entry != (unsigned short)(-1))
{
- const unsigned char *p;
- unsigned int element;
- unsigned int length;
-
- p = &gl_uninorm_decomp_chars_table[3 * (entry & 0x7FFF)];
- element = (p[0] << 16) | (p[1] << 8) | p[2];
+ const unsigned char *p = &gl_uninorm_decomp_chars_table[3 * (entry & 0x7FFF)];
+ unsigned int element = (p[0] << 16) | (p[1] << 8) | p[2];
/* The first element has 5 bits for the decomposition type. */
*decomp_tag = (element >> 18) & 0x1f;
- length = 1;
+ unsigned int length = 1;
for (;;)
{
/* Every element has an 18 bits wide Unicode code point. */
/* The result being accumulated. */
UNIT *result;
- size_t length;
size_t allocated;
- /* The buffer for sorting. */
- #define SORTBUF_PREALLOCATED 64
- struct ucs4_with_ccc sortbuf_preallocated[2 * SORTBUF_PREALLOCATED];
- struct ucs4_with_ccc *sortbuf; /* array of size 2 * sortbuf_allocated */
- size_t sortbuf_allocated;
- size_t sortbuf_count;
-
- /* Initialize the accumulator. */
if (resultbuf == NULL)
{
result = NULL;
result = resultbuf;
allocated = *lengthp;
}
- length = 0;
+ size_t length = 0;
- /* Initialize the buffer for sorting. */
- sortbuf = sortbuf_preallocated;
- sortbuf_allocated = SORTBUF_PREALLOCATED;
- sortbuf_count = 0;
+ /* The buffer for sorting. */
+ #define SORTBUF_PREALLOCATED 64
+ struct ucs4_with_ccc sortbuf_preallocated[2 * SORTBUF_PREALLOCATED];
+ struct ucs4_with_ccc *sortbuf = /* array of size 2 * sortbuf_allocated */
+ sortbuf_preallocated;
+ size_t sortbuf_allocated = SORTBUF_PREALLOCATED;
+ size_t sortbuf_count = 0;
{
const UNIT *s_end = s + n;
int count;
ucs4_t decomposed[UC_DECOMPOSITION_MAX_LENGTH];
int decomposed_count;
- int i;
if (s < s_end)
{
decomposed_count = 0;
}
- i = 0;
+ int i = 0;
for (;;)
{
ucs4_t uc;
/* Append (uc, ccc) to sortbuf. */
if (sortbuf_count == sortbuf_allocated)
{
- struct ucs4_with_ccc *new_sortbuf;
-
sortbuf_allocated = 2 * sortbuf_allocated;
if (sortbuf_allocated < sortbuf_count) /* integer overflow? */
abort ();
- new_sortbuf =
+ struct ucs4_with_ccc *new_sortbuf =
(struct ucs4_with_ccc *) malloc (2 * sortbuf_allocated * sizeof (struct ucs4_with_ccc));
if (new_sortbuf == NULL)
{
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- UNIT *memory;
-
- memory = (UNIT *) realloc (result, length * sizeof (UNIT));
+ UNIT *memory = (UNIT *) realloc (result, length * sizeof (UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const UNIT *s1, size_t n1, const UNIT *s2, size_t n2,
uninorm_t nf, int *resultp)
{
- UNIT buf1[2048 / sizeof (UNIT)];
- UNIT buf2[2048 / sizeof (UNIT)];
- UNIT *norms1;
- size_t norms1_length;
- UNIT *norms2;
- size_t norms2_length;
- int cmp;
-
/* Normalize S1. */
- norms1_length = sizeof (buf1) / sizeof (UNIT);
- norms1 = U_NORMALIZE (nf, s1, n1, buf1, &norms1_length);
+ UNIT buf1[2048 / sizeof (UNIT)];
+ size_t norms1_length = sizeof (buf1) / sizeof (UNIT);
+ UNIT *norms1 = U_NORMALIZE (nf, s1, n1, buf1, &norms1_length);
if (norms1 == NULL)
/* errno is set here. */
return -1;
/* Normalize S2. */
- norms2_length = sizeof (buf2) / sizeof (UNIT);
- norms2 = U_NORMALIZE (nf, s2, n2, buf2, &norms2_length);
+ UNIT buf2[2048 / sizeof (UNIT)];
+ size_t norms2_length = sizeof (buf2) / sizeof (UNIT);
+ UNIT *norms2 = U_NORMALIZE (nf, s2, n2, buf2, &norms2_length);
if (norms2 == NULL)
{
if (norms1 != buf1)
}
/* Compare the normalized strings. */
- cmp = U_CMP2 (norms1, norms1_length, norms2, norms2_length);
+ int cmp = U_CMP2 (norms1, norms1_length, norms2, norms2_length);
if (cmp > 0)
cmp = 1;
else if (cmp < 0)
FUNC (const UNIT *s1, size_t n1, const UNIT *s2, size_t n2,
uninorm_t nf, int *resultp)
{
- char buf1[2048];
- char buf2[2048];
- char *transformed1;
- size_t transformed1_length;
- char *transformed2;
- size_t transformed2_length;
- int cmp;
-
/* Normalize and transform S1. */
- transformed1_length = sizeof (buf1);
- transformed1 = U_NORMXFRM (s1, n1, nf, buf1, &transformed1_length);
+ char buf1[2048];
+ size_t transformed1_length = sizeof (buf1);
+ char *transformed1 = U_NORMXFRM (s1, n1, nf, buf1, &transformed1_length);
if (transformed1 == NULL)
/* errno is set here. */
return -1;
/* Normalize and transform S2. */
- transformed2_length = sizeof (buf2);
- transformed2 = U_NORMXFRM (s2, n2, nf, buf2, &transformed2_length);
+ char buf2[2048];
+ size_t transformed2_length = sizeof (buf2);
+ char *transformed2 = U_NORMXFRM (s2, n2, nf, buf2, &transformed2_length);
if (transformed2 == NULL)
{
if (transformed1 != buf1)
}
/* Compare the transformed strings. */
- cmp = memcmp2 (transformed1, transformed1_length,
- transformed2, transformed2_length);
+ int cmp = memcmp2 (transformed1, transformed1_length,
+ transformed2, transformed2_length);
if (cmp < 0)
cmp = -1;
else if (cmp > 0)
FUNC (const UNIT *s, size_t n, uninorm_t nf,
char *resultbuf, size_t *lengthp)
{
- UNIT normsbuf[2048 / sizeof (UNIT)];
- UNIT *norms;
- size_t norms_length;
- char convsbuf[2048];
- char *convs;
- size_t convs_length;
- char *result;
-
/* Normalize the Unicode string. */
- norms_length = sizeof (normsbuf) / sizeof (UNIT);
- norms = U_NORMALIZE (nf, s, n, normsbuf, &norms_length);
+ UNIT normsbuf[2048 / sizeof (UNIT)];
+ size_t norms_length = sizeof (normsbuf) / sizeof (UNIT);
+ UNIT *norms = U_NORMALIZE (nf, s, n, normsbuf, &norms_length);
if (norms == NULL)
/* errno is set here. */
return NULL;
/* Convert it to locale encoding. */
- convs_length = sizeof (convsbuf) - 1;
- convs = U_CONV_TO_ENCODING (locale_charset (),
+ char convsbuf[2048];
+ size_t convs_length = sizeof (convsbuf) - 1;
+ char *convs = U_CONV_TO_ENCODING (locale_charset (),
iconveh_error,
norms, norms_length,
NULL,
}
/* Apply locale dependent transformations for comparison. */
- result = amemxfrm (convs, convs_length, resultbuf, lengthp);
+ char *result = amemxfrm (convs, convs_length, resultbuf, lengthp);
if (result == NULL)
{
if (convs != convsbuf)
/* Invariant: decomposed[0..curr-1] is fully decomposed, i.e.
all elements are atomic. */
ucs4_t curr_decomposed[UC_DECOMPOSITION_MAX_LENGTH];
- int curr_decomposed_count;
-
- curr_decomposed_count =
+ int curr_decomposed_count =
filter->decomposer (decomposed[curr], curr_decomposed);
if (curr_decomposed_count >= 0)
{
/* Append (uc, ccc) to sortbuf. */
if (sortbuf_count == filter->sortbuf_allocated)
{
- struct ucs4_with_ccc *new_sortbuf;
-
filter->sortbuf_allocated = 2 * filter->sortbuf_allocated;
if (filter->sortbuf_allocated < sortbuf_count) /* integer overflow? */
abort ();
- new_sortbuf =
+ struct ucs4_with_ccc *new_sortbuf =
(struct ucs4_with_ccc *)
malloc (2 * filter->sortbuf_allocated * sizeof (struct ucs4_with_ccc));
if (new_sortbuf == NULL)
ASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp, const FCHAR_T *format, ...)
{
va_list args;
- DCHAR_T *result;
-
va_start (args, format);
- result = VASNPRINTF (resultbuf, lengthp, format, args);
+ DCHAR_T *result = VASNPRINTF (resultbuf, lengthp, format, args);
va_end (args);
return result;
}
ASPRINTF (DCHAR_T **resultp, const FCHAR_T *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = VASPRINTF (resultp, format, args);
+ int result = VASPRINTF (resultp, format, args);
va_end (args);
return result;
}
SNPRINTF (DCHAR_T *buf, size_t size, const FCHAR_T *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = VSNPRINTF (buf, size, format, args);
+ int result = VSNPRINTF (buf, size, format, args);
va_end (args);
return result;
}
SPRINTF (DCHAR_T *buf, const FCHAR_T *format, ...)
{
va_list args;
- int result;
-
va_start (args, format);
- result = VSPRINTF (buf, format, args);
+ int result = VSPRINTF (buf, format, args);
va_end (args);
return result;
}
VSNPRINTF (DCHAR_T *buf, size_t size, const FCHAR_T *format, va_list args)
{
size_t length;
- DCHAR_T *result;
if (size == 0)
buf = NULL;
else
length = size;
- result = VASNPRINTF (buf, &length, format, args);
+ DCHAR_T *result = VASNPRINTF (buf, &length, format, args);
if (result == NULL)
return -1;
Also note that glibc's iconv fails with E2BIG when we pass a length that
is so large that buf + length wraps around, i.e.
(uintptr_t) (buf + length) < (uintptr_t) buf. */
- size_t length;
- DCHAR_T *result;
/* Set length = min (SIZE_MAX, INT_MAX, - (uintptr_t) buf - 1). */
- length = (SIZE_MAX < INT_MAX ? SIZE_MAX : INT_MAX);
+ size_t length = (SIZE_MAX < INT_MAX ? SIZE_MAX : INT_MAX);
if (length > (~ (uintptr_t) buf) / sizeof (DCHAR_T))
length = (~ (uintptr_t) buf) / sizeof (DCHAR_T);
- result = VASNPRINTF (buf, &length, format, args);
+ DCHAR_T *result = VASNPRINTF (buf, &length, format, args);
if (result == NULL)
return -1;
int
ulc_fprintf (FILE *fp, const char *format, ...)
{
+ va_list args;
+ va_start (args, format);
+
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
- va_list args;
+ char *output = ulc_vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
- va_start (args, format);
- output = ulc_vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
va_end (args);
if (!output)
ulc_vfprintf (FILE *fp, const char *format, va_list args)
{
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
-
- output = ulc_vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
+ char *output = ulc_vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
{
uint16_t *
u16_chr (const uint16_t *s, size_t n, ucs4_t uc)
{
- uint16_t c[2];
-
if (uc < 0x10000)
{
uint16_t c0 = uc;
}
}
else
- switch (u16_uctomb_aux (c, uc, 2))
- {
- case 2:
- if (n > 1)
- {
- uint16_t c0 = c[0];
- uint16_t c1 = c[1];
+ {
+ uint16_t c[2];
+
+ switch (u16_uctomb_aux (c, uc, 2))
+ {
+ case 2:
+ if (n > 1)
+ {
+ uint16_t c0 = c[0];
+ uint16_t c1 = c[1];
- for (n--; n > 0; s++, n--)
- {
- if (*s == c0 && s[1] == c1)
- return (uint16_t *) s;
- }
- }
- break;
- }
+ for (n--; n > 0; s++, n--)
+ {
+ if (*s == c0 && s[1] == c1)
+ return (uint16_t *) s;
+ }
+ }
+ break;
+ }
+ }
return NULL;
}
size_t
u16_mbsnlen (const uint16_t *s, size_t n)
{
- size_t characters;
-
- characters = 0;
+ size_t characters = 0;
while (n > 0)
{
ucs4_t uc;
const uint16_t *
u16_next (ucs4_t *puc, const uint16_t *s)
{
- int count;
-
- count = u16_strmbtouc (puc, s);
+ int count = u16_strmbtouc (puc, s);
if (count > 0)
return s + count;
else
uint16_t *
u16_strchr (const uint16_t *s, ucs4_t uc)
{
- uint16_t c[2];
-
if (uc < 0x10000)
{
uint16_t c0 = uc;
return (uint16_t *) s;
}
else
- switch (u16_uctomb_aux (c, uc, 2))
- {
- case 2:
- if (*s == 0)
- goto notfound;
+ {
+ uint16_t c[2];
+
+ switch (u16_uctomb_aux (c, uc, 2))
{
- uint16_t c0 = c[0];
- uint16_t c1 = c[1];
+ case 2:
+ if (*s == 0)
+ goto notfound;
+ {
+ uint16_t c0 = c[0];
+ uint16_t c1 = c[1];
- for (;; s++)
- {
- if (s[1] == 0)
- goto notfound;
- if (*s == c0 && s[1] == c1)
- break;
- }
- return (uint16_t *) s;
+ for (;; s++)
+ {
+ if (s[1] == 0)
+ goto notfound;
+ if (*s == c0 && s[1] == c1)
+ break;
+ }
+ return (uint16_t *) s;
+ }
}
- }
+ }
notfound:
return NULL;
}
/* Calling u16_strlen and then searching from the other end would cause more
memory accesses. Avoid that, at the cost of a few more comparisons. */
uint16_t *result = NULL;
- uint16_t c[2];
if (uc < 0x10000)
{
}
}
else
- switch (u16_uctomb_aux (c, uc, 2))
- {
- case 2:
- if (*s)
- {
- uint16_t c0 = c[0];
- uint16_t c1 = c[1];
+ {
+ uint16_t c[2];
+
+ switch (u16_uctomb_aux (c, uc, 2))
+ {
+ case 2:
+ if (*s)
+ {
+ uint16_t c0 = c[0];
+ uint16_t c1 = c[1];
- /* FIXME: Maybe walking the string via u16_mblen is a win? */
- for (;; s++)
- {
- if (s[1] == 0)
- break;
- if (*s == c0 && s[1] == c1)
- result = (uint16_t *) s;
- }
- }
- break;
- }
+ /* FIXME: Maybe walking the string via u16_mblen is a win? */
+ for (;; s++)
+ {
+ if (s[1] == 0)
+ break;
+ if (*s == c0 && s[1] == c1)
+ result = (uint16_t *) s;
+ }
+ }
+ break;
+ }
+ }
return result;
}
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- count = u16_mbtoucr (&uc, s, s_end - s);
+ ucs4_t uc;
+ int count = u16_mbtoucr (&uc, s, s_end - s);
if (count < 0)
{
if (!(result == resultbuf || result == NULL))
/* Store it in the output string. */
if (length + 1 > allocated)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 1 > allocated)
allocated = length + 1;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- count = u16_mbtoucr (&uc, s, s_end - s);
+ ucs4_t uc;
+ int count = u16_mbtoucr (&uc, s, s_end - s);
if (count < 0)
{
if (!(result == resultbuf || result == NULL))
}
if (count == -2)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 6 > allocated)
allocated = length + 6;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
const uint32_t *
u32_next (ucs4_t *puc, const uint32_t *s)
{
- int count;
-
- count = u32_strmbtouc (puc, s);
+ int count = u32_strmbtouc (puc, s);
if (count > 0)
return s + count;
else
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- uc = *s++;
+ ucs4_t uc = *s++;
/* No need to call the safe variant u32_mbtouc, because
u16_uctomb will verify uc anyway. */
/* Store it in the output string. */
- count = u16_uctomb (result + length, uc, allocated - length);
+ int count = u16_uctomb (result + length, uc, allocated - length);
if (count == -1)
{
if (!(result == resultbuf || result == NULL))
}
if (count == -2)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 2 > allocated)
allocated = length + 2;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- uc = *s++;
+ ucs4_t uc = *s++;
/* No need to call the safe variant u32_mbtouc, because
u8_uctomb will verify uc anyway. */
/* Store it in the output string. */
- count = u8_uctomb (result + length, uc, allocated - length);
+ int count = u8_uctomb (result + length, uc, allocated - length);
if (count == -1)
{
if (!(result == resultbuf || result == NULL))
}
if (count == -2)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 6 > allocated)
allocated = length + 6;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
{
uint8_t c[6];
- size_t uc_size;
- uc_size = u8_uctomb_aux (c, uc, 6);
+ size_t uc_size = u8_uctomb_aux (c, uc, 6);
if (n < uc_size)
return NULL;
size_t
u8_mbsnlen (const uint8_t *s, size_t n)
{
- size_t characters;
-
- characters = 0;
+ size_t characters = 0;
while (n > 0)
{
ucs4_t uc;
const uint8_t *
u8_next (ucs4_t *puc, const uint8_t *s)
{
- int count;
-
- count = u8_strmbtouc (puc, s);
+ int count = u8_strmbtouc (puc, s);
if (count > 0)
return s + count;
else
uint8_t *
u8_strchr (const uint8_t *s, ucs4_t uc)
{
- uint8_t c[6];
-
if (uc < 0x80)
{
uint8_t c0 = uc;
}
}
else
+ {
/* Loops equivalent to strstr, optimized for a specific length (2, 3, 4)
of the needle. We use an algorithm similar to Boyer-Moore which
is documented in lib/unistr/u8-chr.c. There is additional
complication because we need to check after every byte for
a NUL byte, but the idea is the same. */
- switch (u8_uctomb_aux (c, uc, 6))
- {
- case 2:
- if (*s == 0 || s[1] == 0)
- break;
- {
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
- /* Search for { c0, c1 }. */
- uint8_t s1 = s[1];
-
- for (;;)
- {
- /* Here s[0] != 0, s[1] != 0.
- Test whether s[0..1] == { c0, c1 }. */
- if (s1 == c1)
- {
- if (*s == c0)
- return (uint8_t *) s;
- else
- /* Skip the search at s + 1, because s[1] = c1 < c0. */
- goto case2_skip2;
- }
- else
- {
- if (s1 == c0)
- goto case2_skip1;
- else
- /* Skip the search at s + 1, because s[1] != c0. */
- goto case2_skip2;
- }
- case2_skip2:
- s++;
- s1 = s[1];
- if (s[1] == 0)
- break;
- case2_skip1:
- s++;
- s1 = s[1];
- if (s[1] == 0)
- break;
- }
- }
- break;
+ uint8_t c[6];
- case 3:
- if (*s == 0 || s[1] == 0 || s[2] == 0)
- break;
+ switch (u8_uctomb_aux (c, uc, 6))
{
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
- uint8_t c2 = c[2];
- /* Search for { c0, c1, c2 }. */
- uint8_t s2 = s[2];
+ case 2:
+ if (*s == 0 || s[1] == 0)
+ break;
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
+ /* Search for { c0, c1 }. */
+ uint8_t s1 = s[1];
+
+ for (;;)
+ {
+ /* Here s[0] != 0, s[1] != 0.
+ Test whether s[0..1] == { c0, c1 }. */
+ if (s1 == c1)
+ {
+ if (*s == c0)
+ return (uint8_t *) s;
+ else
+ /* Skip the search at s + 1, because s[1] = c1 < c0. */
+ goto case2_skip2;
+ }
+ else
+ {
+ if (s1 == c0)
+ goto case2_skip1;
+ else
+ /* Skip the search at s + 1, because s[1] != c0. */
+ goto case2_skip2;
+ }
+ case2_skip2:
+ s++;
+ s1 = s[1];
+ if (s[1] == 0)
+ break;
+ case2_skip1:
+ s++;
+ s1 = s[1];
+ if (s[1] == 0)
+ break;
+ }
+ }
+ break;
- for (;;)
- {
- /* Here s[0] != 0, s[1] != 0, s[2] != 0.
- Test whether s[0..2] == { c0, c1, c2 }. */
- if (s2 == c2)
- {
- if (s[1] == c1 && *s == c0)
- return (uint8_t *) s;
- else
- /* If c2 != c1:
- Skip the search at s + 1, because s[2] == c2 != c1.
- Skip the search at s + 2, because s[2] == c2 < c0. */
- if (c2 == c1)
+ case 3:
+ if (*s == 0 || s[1] == 0 || s[2] == 0)
+ break;
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
+ uint8_t c2 = c[2];
+ /* Search for { c0, c1, c2 }. */
+ uint8_t s2 = s[2];
+
+ for (;;)
+ {
+ /* Here s[0] != 0, s[1] != 0, s[2] != 0.
+ Test whether s[0..2] == { c0, c1, c2 }. */
+ if (s2 == c2)
+ {
+ if (s[1] == c1 && *s == c0)
+ return (uint8_t *) s;
+ else
+ /* If c2 != c1:
+ Skip the search at s + 1, because s[2] == c2 != c1.
+ Skip the search at s + 2, because s[2] == c2 < c0. */
+ if (c2 == c1)
+ goto case3_skip1;
+ else
+ goto case3_skip3;
+ }
+ else
+ {
+ if (s2 == c1)
goto case3_skip1;
+ else if (s2 == c0)
+ /* Skip the search at s + 1, because s[2] != c1. */
+ goto case3_skip2;
else
+ /* Skip the search at s + 1, because s[2] != c1.
+ Skip the search at s + 2, because s[2] != c0. */
goto case3_skip3;
- }
- else
- {
- if (s2 == c1)
- goto case3_skip1;
- else if (s2 == c0)
- /* Skip the search at s + 1, because s[2] != c1. */
- goto case3_skip2;
- else
- /* Skip the search at s + 1, because s[2] != c1.
- Skip the search at s + 2, because s[2] != c0. */
- goto case3_skip3;
- }
- case3_skip3:
- s++;
- s2 = s[2];
- if (s[2] == 0)
- break;
- case3_skip2:
- s++;
- s2 = s[2];
- if (s[2] == 0)
- break;
- case3_skip1:
- s++;
- s2 = s[2];
- if (s[2] == 0)
- break;
- }
- }
- break;
-
- case 4:
- if (*s == 0 || s[1] == 0 || s[2] == 0 || s[3] == 0)
+ }
+ case3_skip3:
+ s++;
+ s2 = s[2];
+ if (s[2] == 0)
+ break;
+ case3_skip2:
+ s++;
+ s2 = s[2];
+ if (s[2] == 0)
+ break;
+ case3_skip1:
+ s++;
+ s2 = s[2];
+ if (s[2] == 0)
+ break;
+ }
+ }
break;
- {
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
- uint8_t c2 = c[2];
- uint8_t c3 = c[3];
- /* Search for { c0, c1, c2, c3 }. */
- uint8_t s3 = s[3];
- for (;;)
- {
- /* Here s[0] != 0, s[1] != 0, s[2] != 0, s[3] != 0.
- Test whether s[0..3] == { c0, c1, c2, c3 }. */
- if (s3 == c3)
- {
- if (s[2] == c2 && s[1] == c1 && *s == c0)
- return (uint8_t *) s;
- else
- /* If c3 != c2:
- Skip the search at s + 1, because s[3] == c3 != c2.
- If c3 != c1:
- Skip the search at s + 2, because s[3] == c3 != c1.
- Skip the search at s + 3, because s[3] == c3 < c0. */
- if (c3 == c2)
+ case 4:
+ if (*s == 0 || s[1] == 0 || s[2] == 0 || s[3] == 0)
+ break;
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
+ uint8_t c2 = c[2];
+ uint8_t c3 = c[3];
+ /* Search for { c0, c1, c2, c3 }. */
+ uint8_t s3 = s[3];
+
+ for (;;)
+ {
+ /* Here s[0] != 0, s[1] != 0, s[2] != 0, s[3] != 0.
+ Test whether s[0..3] == { c0, c1, c2, c3 }. */
+ if (s3 == c3)
+ {
+ if (s[2] == c2 && s[1] == c1 && *s == c0)
+ return (uint8_t *) s;
+ else
+ /* If c3 != c2:
+ Skip the search at s + 1, because s[3] == c3 != c2.
+ If c3 != c1:
+ Skip the search at s + 2, because s[3] == c3 != c1.
+ Skip the search at s + 3, because s[3] == c3 < c0. */
+ if (c3 == c2)
+ goto case4_skip1;
+ else if (c3 == c1)
+ goto case4_skip2;
+ else
+ goto case4_skip4;
+ }
+ else
+ {
+ if (s3 == c2)
goto case4_skip1;
- else if (c3 == c1)
+ else if (s3 == c1)
+ /* Skip the search at s + 1, because s[3] != c2. */
goto case4_skip2;
+ else if (s3 == c0)
+ /* Skip the search at s + 1, because s[3] != c2.
+ Skip the search at s + 2, because s[3] != c1. */
+ goto case4_skip3;
else
+ /* Skip the search at s + 1, because s[3] != c2.
+ Skip the search at s + 2, because s[3] != c1.
+ Skip the search at s + 3, because s[3] != c0. */
goto case4_skip4;
- }
- else
- {
- if (s3 == c2)
- goto case4_skip1;
- else if (s3 == c1)
- /* Skip the search at s + 1, because s[3] != c2. */
- goto case4_skip2;
- else if (s3 == c0)
- /* Skip the search at s + 1, because s[3] != c2.
- Skip the search at s + 2, because s[3] != c1. */
- goto case4_skip3;
- else
- /* Skip the search at s + 1, because s[3] != c2.
- Skip the search at s + 2, because s[3] != c1.
- Skip the search at s + 3, because s[3] != c0. */
- goto case4_skip4;
- }
- case4_skip4:
- s++;
- s3 = s[3];
- if (s[3] == 0)
- break;
- case4_skip3:
- s++;
- s3 = s[3];
- if (s[3] == 0)
- break;
- case4_skip2:
- s++;
- s3 = s[3];
- if (s[3] == 0)
- break;
- case4_skip1:
- s++;
- s3 = s[3];
- if (s[3] == 0)
- break;
- }
+ }
+ case4_skip4:
+ s++;
+ s3 = s[3];
+ if (s[3] == 0)
+ break;
+ case4_skip3:
+ s++;
+ s3 = s[3];
+ if (s[3] == 0)
+ break;
+ case4_skip2:
+ s++;
+ s3 = s[3];
+ if (s[3] == 0)
+ break;
+ case4_skip1:
+ s++;
+ s3 = s[3];
+ if (s[3] == 0)
+ break;
+ }
+ }
+ break;
}
- break;
- }
+ }
return NULL;
}
/* Calling u8_strlen and then searching from the other end would cause more
memory accesses. Avoid that, at the cost of a few more comparisons. */
uint8_t *result = NULL;
- uint8_t c[6];
if (uc < 0x80)
{
}
}
else
- switch (u8_uctomb_aux (c, uc, 6))
- {
- case 2:
- if (*s)
- {
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
+ {
+ uint8_t c[6];
+
+ switch (u8_uctomb_aux (c, uc, 6))
+ {
+ case 2:
+ if (*s)
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
- /* FIXME: Maybe walking the string via u8_mblen is a win? */
- for (;; s++)
- {
- if (s[1] == 0)
- break;
- if (*s == c0 && s[1] == c1)
- result = (uint8_t *) s;
- }
- }
- break;
+ /* FIXME: Maybe walking the string via u8_mblen is a win? */
+ for (;; s++)
+ {
+ if (s[1] == 0)
+ break;
+ if (*s == c0 && s[1] == c1)
+ result = (uint8_t *) s;
+ }
+ }
+ break;
- case 3:
- if (*s && s[1])
- {
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
- uint8_t c2 = c[2];
+ case 3:
+ if (*s && s[1])
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
+ uint8_t c2 = c[2];
- /* FIXME: Maybe walking the string via u8_mblen is a win? */
- for (;; s++)
- {
- if (s[2] == 0)
- break;
- if (*s == c0 && s[1] == c1 && s[2] == c2)
- result = (uint8_t *) s;
- }
- }
- break;
+ /* FIXME: Maybe walking the string via u8_mblen is a win? */
+ for (;; s++)
+ {
+ if (s[2] == 0)
+ break;
+ if (*s == c0 && s[1] == c1 && s[2] == c2)
+ result = (uint8_t *) s;
+ }
+ }
+ break;
- case 4:
- if (*s && s[1] && s[2])
- {
- uint8_t c0 = c[0];
- uint8_t c1 = c[1];
- uint8_t c2 = c[2];
- uint8_t c3 = c[3];
+ case 4:
+ if (*s && s[1] && s[2])
+ {
+ uint8_t c0 = c[0];
+ uint8_t c1 = c[1];
+ uint8_t c2 = c[2];
+ uint8_t c3 = c[3];
- /* FIXME: Maybe walking the string via u8_mblen is a win? */
- for (;; s++)
- {
- if (s[3] == 0)
- break;
- if (*s == c0 && s[1] == c1 && s[2] == c2 && s[3] == c3)
- result = (uint8_t *) s;
- }
- }
- break;
- }
+ /* FIXME: Maybe walking the string via u8_mblen is a win? */
+ for (;; s++)
+ {
+ if (s[3] == 0)
+ break;
+ if (*s == c0 && s[1] == c1 && s[2] == c2 && s[3] == c3)
+ result = (uint8_t *) s;
+ }
+ }
+ break;
+ }
+ }
return result;
}
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- count = u8_mbtoucr (&uc, s, s_end - s);
+ ucs4_t uc;
+ int count = u8_mbtoucr (&uc, s, s_end - s);
if (count < 0)
{
if (!(result == resultbuf || result == NULL))
}
if (count == -2)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 2 > allocated)
allocated = length + 2;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
FUNC (const SRC_UNIT *s, size_t n, DST_UNIT *resultbuf, size_t *lengthp)
{
const SRC_UNIT *s_end = s + n;
+
/* Output string accumulator. */
DST_UNIT *result;
size_t allocated;
- size_t length;
-
if (resultbuf != NULL)
{
result = resultbuf;
result = NULL;
allocated = 0;
}
- length = 0;
+ size_t length = 0;
/* Invariants:
result is either == resultbuf or == NULL or malloc-allocated.
If length > 0, then result != NULL. */
while (s < s_end)
{
- ucs4_t uc;
- int count;
-
/* Fetch a Unicode character from the input string. */
- count = u8_mbtoucr (&uc, s, s_end - s);
+ ucs4_t uc;
+ int count = u8_mbtoucr (&uc, s, s_end - s);
if (count < 0)
{
if (!(result == resultbuf || result == NULL))
/* Store it in the output string. */
if (length + 1 > allocated)
{
- DST_UNIT *memory;
-
allocated = (allocated > 0 ? 2 * allocated : 12);
if (length + 1 > allocated)
allocated = length + 1;
+
+ DST_UNIT *memory;
if (result == resultbuf || result == NULL)
memory = (DST_UNIT *) malloc (allocated * sizeof (DST_UNIT));
else
else if (result != resultbuf && length < allocated)
{
/* Shrink the allocated memory if possible. */
- DST_UNIT *memory;
-
- memory = (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
+ DST_UNIT *memory =
+ (DST_UNIT *) realloc (result, length * sizeof (DST_UNIT));
if (memory != NULL)
result = memory;
}
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
if (offsets != NULL)
{
- uint8_t *t;
size_t m;
-
- t = u8_conv_from_encoding (encoding, iconveh_question_mark,
- s, n, offsets, NULL, &m);
+ uint8_t *t =
+ u8_conv_from_encoding (encoding, iconveh_question_mark,
+ s, n, offsets, NULL, &m);
if (t != NULL)
{
char *q = (char *) (m > 0 ? malloc (m) : NULL);
char *buf = NULL;
int alloc = 0;
int size = 0;
- int count;
while (! feof (stream))
{
exit (1);
}
}
- count = fread (buf + size, 1, BUFSIZE, stream);
+ int count = fread (buf + size, 1, BUFSIZE, stream);
if (count == 0)
{
if (ferror (stream))
while (s < s_end)
{
ucs4_t uc;
- int w;
-
s += u16_mbtouc_unsafe (&uc, s, s_end - s);
if (uc == 0)
break; /* end of string reached */
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
width += w;
}
while (s < s_end)
{
ucs4_t uc = *s++;
- int w;
if (uc == 0)
break; /* end of string reached */
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
width += w;
}
while (s < s_end)
{
ucs4_t uc;
- int w;
-
s += u8_mbtouc_unsafe (&uc, s, s_end - s);
if (uc == 0)
break; /* end of string reached */
- w = uc_width (uc, encoding);
+ int w = uc_width (uc, encoding);
if (w >= 0) /* ignore control characters in the string */
width += w;
}
int
rpl_unlinkat (int fd, char const *name, int flag)
{
- size_t len;
- int result = 0;
/* rmdir behavior has no problems with trailing slash. */
if (flag & AT_REMOVEDIR)
return unlinkat (fd, name, flag);
- len = strlen (name);
+ size_t len = strlen (name);
+ int result = 0;
if (len && ISSLASH (name[len - 1]))
{
/* See the lengthy comment in unlink.c why we disobey the POSIX
int
unsetenv (const char *name)
{
- size_t len;
-
if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
{
__set_errno (EINVAL);
return -1;
}
- len = strlen (name);
+ size_t len = strlen (name);
#if HAVE_DECL__PUTENV /* native Windows */
/* The Microsoft documentation
of the form "NAME=". (NB: This is a different convention than with glibc
putenv, which expects a string of the form "NAME"!) */
{
- int putenv_result;
char *name_ = malloc (len + 2);
if (name_ == NULL)
return -1;
memcpy (name_, name, len);
name_[len] = '=';
name_[len + 1] = 0;
- putenv_result = _putenv (name_);
+ int putenv_result = _putenv (name_);
/* In this particular case it is OK to free() the argument passed to
_putenv. */
free (name_);
int
rpl_unsetenv (const char *name)
{
- int result = 0;
if (!name || !*name || strchr (name, '='))
{
errno = EINVAL;
return -1;
}
+ int result = 0;
while (getenv (name))
# if !VOID_UNSETENV
result =
uid_t *uid, gid_t *gid,
char **username, char **groupname)
{
- const char *error_msg;
- struct passwd *pwd;
- struct group *grp;
- char *u;
- char const *g;
- char *gname = NULL;
- uid_t unum = *uid;
- gid_t gnum = gid ? *gid : -1;
-
- error_msg = NULL;
+ const char *error_msg = NULL;
if (username)
*username = NULL;
if (groupname)
group specifiers or to NULL. If U is not NULL, it is a newly
allocated string. */
- u = NULL;
+ char *u = NULL;
if (separator == NULL)
{
if (*spec)
}
}
- g = (separator == NULL || *(separator + 1) == '\0'
- ? NULL
- : separator + 1);
+ char const *g = (separator == NULL || *(separator + 1) == '\0'
+ ? NULL
+ : separator + 1);
#ifdef __DJGPP__
/* Pretend that we are the user U whose group is G. This makes
setenv ("GROUP", g, 1);
#endif
+ char *gname = NULL;
+ uid_t unum = *uid;
+ gid_t gnum = gid ? *gid : -1;
+
if (u != NULL)
{
/* If it starts with "+", skip the look-up. */
- pwd = (*u == '+' ? NULL : getpwnam (u));
+ struct passwd *pwd = (*u == '+' ? NULL : getpwnam (u));
if (pwd == NULL)
{
username = NULL;
so get the login group. */
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
gnum = pwd->pw_gid;
- grp = getgrgid (gnum);
+ struct group *grp = getgrgid (gnum);
gname = xstrdup (grp ? grp->gr_name : umaxtostr (gnum, buf));
endgrent ();
}
{
/* Explicit group. */
/* If it starts with "+", skip the look-up. */
- grp = (*g == '+' ? NULL : getgrnam (g));
+ struct group *grp = (*g == '+' ? NULL : getgrnam (g));
if (grp == NULL)
{
groupname = NULL;
{
for (int i = 1; i < argc; i++)
{
- const char *e;
- char *username, *groupname;
+ char *tmp = strdup (argv[i]);
+
uid_t uid;
gid_t gid;
- char *tmp;
+ char *username;
+ char *groupname;
+ const char *e = parse_user_spec (tmp, &uid, &gid, &username, &groupname);
- tmp = strdup (argv[i]);
- e = parse_user_spec (tmp, &uid, &gid, &username, &groupname);
free (tmp);
+
printf ("%s: %lu %lu %s %s %s\n",
argv[i],
(unsigned long int) uid,
/* Remove trailing slashes (except the very first one, at position
drive_prefix_len), but remember their presence. */
- size_t rlen;
+ size_t rlen = len;
bool check_dir = false;
-
- rlen = len;
while (rlen > drive_prefix_len && ISSLASH (name[rlen-1]))
{
check_dir = true;
/* Information about the destination file system. */
static struct fs_res *new_dst_res;
struct fs_res *dst_res = NULL;
- struct fs_res tmp_dst_res;
/* timestamp resolution in nanoseconds. */
int res;
}
else
{
- low_memory:
+ low_memory: ;
+ struct fs_res tmp_dst_res;
if (ht)
{
tmp_dst_res.dev = dst_stat->st_dev;
if (SYSCALL_RESOLUTION < res)
{
- struct stat dst_status;
-
/* Ignore source timestamp information that must necessarily
be lost when filtered through utimens. */
src_ns -= src_ns % SYSCALL_RESOLUTION;
if (utimensat (dfd, dst_name, timespec, AT_SYMLINK_NOFOLLOW))
return -2;
+ struct stat dst_status;
+
/* Read the modification time that was set. */
{
int stat_result
static int
validate_timespec (struct timespec timespec[2])
{
- int result = 0;
- int utime_omit_count = 0;
if (!is_valid_timespecs (timespec))
{
errno = EINVAL;
return -1;
}
+ int result = 0;
+ int utime_omit_count = 0;
/* Work around Linux kernel 2.6.25 bug, where utimensat fails with
EINVAL if tv_sec is not 0 when using the flag values of tv_nsec.
Flag a Linux kernel 2.6.32 bug, where an mtime of UTIME_OMIT
struct timespec adjusted_timespec[2];
struct timespec *ts = timespec ? adjusted_timespec : NULL;
int adjustment_needed = 0;
- struct stat st;
if (ts)
{
fsync (fd);
#endif
+ struct stat st;
+
/* POSIX 2008 added two interfaces to set file timestamps with
nanosecond resolution; newer Linux implements both functions via
a single syscall. We provide a fallback for ENOSYS (for example,
<https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-filetime> */
if (0 <= fd)
{
- HANDLE handle;
- FILETIME current_time;
- FILETIME last_access_time;
- FILETIME last_write_time;
-
- handle = (HANDLE) _get_osfhandle (fd);
+ HANDLE handle = (HANDLE) _get_osfhandle (fd);
if (handle == INVALID_HANDLE_VALUE)
{
errno = EBADF;
return -1;
}
+ FILETIME current_time;
if (ts == NULL || ts[0].tv_nsec == UTIME_NOW || ts[1].tv_nsec == UTIME_NOW)
{
/* GetSystemTimeAsFileTime
GetSystemTimeAsFileTime (¤t_time);
}
+ FILETIME last_access_time;
if (ts == NULL || ts[0].tv_nsec == UTIME_NOW)
{
last_access_time = current_time;
last_access_time.dwHighDateTime = time_since_16010101 >> 32;
}
+ FILETIME last_write_time;
if (ts == NULL || ts[1].tv_nsec == UTIME_NOW)
{
last_write_time = current_time;
time_t adiff = st.st_atime - t[0].tv_sec;
time_t mdiff = st.st_mtime - t[1].tv_sec;
- struct timeval *tt = NULL;
struct timeval truncated_timeval[2];
truncated_timeval[0] = t[0];
truncated_timeval[1] = t[1];
+
+ struct timeval *tt = NULL;
if (abig && adiff == 1 && get_stat_atime_ns (&st) == 0)
{
tt = truncated_timeval;
struct timespec adjusted_timespec[2];
struct timespec *ts = timespec ? adjusted_timespec : NULL;
int adjustment_needed = 0;
- struct stat st;
if (ts)
{
if (adjustment_needed < 0)
return -1;
+ struct stat st;
+
/* The Linux kernel did not support symlink timestamps until
utimensat, in version 2.6.22, so we don't need to mimic
fdutimens' worry about buggy NFS clients. But we do have to
{
struct timeval timeval[2];
struct timeval *t;
- int result;
if (ts)
{
timeval[0] = (struct timeval) { .tv_sec = ts[0].tv_sec,
else
t = NULL;
- result = lutimes (file, t);
+ int result = lutimes (file, t);
if (result == 0 || errno != ENOSYS)
return result;
}
static int utimensat_works_really; /* 0 = unknown, 1 = yes, -1 = no. */
if (0 <= utimensat_works_really)
{
- int result;
# if defined __linux__ || defined __sun || defined __NetBSD__
struct stat st;
/* As recently as Linux kernel 2.6.32 (Dec 2009), several file
}
# endif
# endif
- result = utimensat (fd, file, times, flag);
+ int result = utimensat (fd, file, times, flag);
/* Linux kernel 2.6.25 has a bug where it returns EINVAL for
UTIME_NOW or UTIME_OMIT with non-zero tv_sec, which
local_utimensat works around. Meanwhile, EINVAL for a bad
size_t a_len = a.nlimbs;
const mp_limb_t *b_ptr = b.limbs;
size_t b_len = b.nlimbs;
- mp_limb_t *roomptr;
mp_limb_t *tmp_roomptr = NULL;
mp_limb_t *q_ptr;
size_t q_len;
/* Allocate room for a_len+2 digits.
(Need a_len+1 digits for the real division and 1 more digit for the
final rounding of q.) */
- roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
+ mp_limb_t *roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));
if (roomptr == NULL)
return NOMEM_PTR;
static void *
decode_long_double (long double x, int *ep, mpn_t *mp)
{
- mpn_t m;
- int exp;
- long double y;
-
/* Allocate memory for result. */
+ mpn_t m;
m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
if (m.limbs == NULL)
return NULL;
/* Split into exponential part and mantissa. */
- y = safe_frexpl (x, &exp);
+ int exp;
+ long double y = safe_frexpl (x, &exp);
if (!(y >= 0.0L && y < 1.0L))
abort ();
/* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the
static void *
decode_double (double x, int *ep, mpn_t *mp)
{
- mpn_t m;
- int exp;
- double y;
-
/* Allocate memory for result. */
+ mpn_t m;
m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS;
m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t));
if (m.limbs == NULL)
return NULL;
/* Split into exponential part and mantissa. */
- y = frexp (x, &exp);
+ int exp;
+ double y = frexp (x, &exp);
if (!(y >= 0.0 && y < 1.0))
abort ();
/* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the
static char *
scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n)
{
- int s;
- size_t extra_zeroes;
- unsigned int abs_n;
- unsigned int abs_s;
- mp_limb_t *pow5_ptr;
- size_t pow5_len;
- unsigned int s_limbs;
- unsigned int s_bits;
- mpn_t pow5;
- mpn_t z;
- void *z_memory;
- char *digits;
-
/* x = 2^e * m, hence
y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m)
= round (2^s * 5^n * m). */
- s = e + n;
- extra_zeroes = 0;
+ int s = e + n;
+ size_t extra_zeroes = 0;
/* Factor out a common power of 10 if possible. */
if (s > 0 && n > 0)
{
z = round (2^s * 5^n * m). */
/* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same
sign. 2.322 is slightly larger than log(5)/log(2). */
- abs_n = (n >= 0 ? n : -n);
- abs_s = (s >= 0 ? s : -s);
- pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
- + abs_s / GMP_LIMB_BITS + 1)
- * sizeof (mp_limb_t));
+ unsigned int abs_n = (n >= 0 ? n : -n);
+ unsigned int abs_s = (s >= 0 ? s : -s);
+ mp_limb_t *pow5_ptr =
+ (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1
+ + abs_s / GMP_LIMB_BITS + 1)
+ * sizeof (mp_limb_t));
if (pow5_ptr == NULL)
{
free (memory);
}
/* Initialize with 1. */
pow5_ptr[0] = 1;
- pow5_len = 1;
+ size_t pow5_len = 1;
/* Multiply with 5^|n|. */
if (abs_n > 0)
{
pow5_ptr[pow5_len++] = (mp_limb_t) carry;
}
}
- s_limbs = abs_s / GMP_LIMB_BITS;
- s_bits = abs_s % GMP_LIMB_BITS;
+ unsigned int s_limbs = abs_s / GMP_LIMB_BITS;
+ unsigned int s_bits = abs_s % GMP_LIMB_BITS;
+ mpn_t pow5;
+ mpn_t z;
+ void *z_memory;
if (n >= 0 ? s >= 0 : s <= 0)
{
/* Multiply with 2^|s|. */
if (z_memory == NOMEM_PTR)
return NULL;
- digits = convert_to_decimal (z, extra_zeroes);
+ char *digits = convert_to_decimal (z, extra_zeroes);
free (z_memory);
return digits;
}
static int
floorlog10l (long double x)
{
- int exp;
- long double y;
- double z;
- double l;
-
/* Split into exponential part and mantissa. */
- y = safe_frexpl (x, &exp);
+ int exp;
+ long double y = safe_frexpl (x, &exp);
if (!(y >= 0.0L && y < 1.0L))
abort ();
if (y == 0.0L)
if (!(y >= 0.5L && y < 1.0L))
abort ();
/* Compute an approximation for l = log2(x) = exp + log2(y). */
- l = exp;
- z = y;
+ double l = exp;
+ double z = y;
if (z < 0.70710678118654752444)
{
z *= 1.4142135623730950488;
static int
floorlog10 (double x)
{
- int exp;
- double y;
- double z;
- double l;
-
/* Split into exponential part and mantissa. */
- y = frexp (x, &exp);
+ int exp;
+ double y = frexp (x, &exp);
if (!(y >= 0.0 && y < 1.0))
abort ();
if (y == 0.0)
if (!(y >= 0.5 && y < 1.0))
abort ();
/* Compute an approximation for l = log2(x) = exp + log2(y). */
- l = exp;
- z = y;
+ double l = exp;
+ double z = y;
if (z < 0.70710678118654752444)
{
z *= 1.4142135623730950488;
goto fail_1_with_EINVAL;
{
- size_t buf_neededlength;
- TCHAR_T *buf;
- TCHAR_T *buf_malloced;
- const FCHAR_T *cp;
- size_t di;
- DIRECTIVE *dp;
- /* Output string accumulator. */
- DCHAR_T *result;
- size_t allocated;
- size_t length;
-
/* Allocate a small buffer that will hold a directive passed to
sprintf or snprintf. */
- buf_neededlength =
+ size_t buf_neededlength =
xsum4 (7, d.max_width_length, d.max_precision_length, 6);
+ TCHAR_T *buf;
+ TCHAR_T *buf_malloced;
#if HAVE_ALLOCA
if (buf_neededlength < 4000 / sizeof (TCHAR_T))
{
buf_malloced = buf;
}
- result = resultbuf;
- allocated = (resultbuf != NULL ? *lengthp : 0);
- length = 0;
+ /* Output string accumulator. */
+ DCHAR_T *result = resultbuf;
+ size_t allocated = (resultbuf != NULL ? *lengthp : 0);
+ size_t length = 0;
+
/* Invariants:
result is either == resultbuf or malloc-allocated.
If result == NULL, resultbuf is == NULL as well.
#define ENSURE_ALLOCATION_ELSE(needed, oom_statement) \
if ((needed) > allocated) \
{ \
- size_t memory_size; \
- DCHAR_T *memory; \
- \
allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \
if ((needed) > allocated) \
allocated = (needed); \
- memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
+ size_t memory_size = xtimes (allocated, sizeof (DCHAR_T)); \
if (size_overflow_p (memory_size)) \
oom_statement \
+ DCHAR_T *memory; \
if (result == resultbuf) \
memory = (DCHAR_T *) malloc (memory_size); \
else \
#define ENSURE_ALLOCATION(needed) \
ENSURE_ALLOCATION_ELSE((needed), goto out_of_memory; )
+ const FCHAR_T *cp;
+ size_t di;
+ DIRECTIVE *dp;
for (cp = format, di = 0, dp = &d.dir[0]; ; cp = dp->dir_end, di++, dp++)
{
if (cp != dp->dir_start)
{
arg_type type = a.arg[dp->arg_index].type;
int flags = dp->flags;
- int has_width;
- size_t width;
- int has_precision;
- size_t precision;
- has_width = 0;
- width = 0;
+ int has_width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
has_width = 1;
}
- has_precision = 0;
- precision = 0;
+ int has_precision = 0;
+ size_t precision = 0;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
than INT_MAX characters, whence snprintf or sprintf would
fail to process it. */
int flags = dp->flags;
- int has_width;
- size_t width;
- int has_precision;
- size_t precision;
- has_width = 0;
- width = 0;
+ int has_width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
has_width = 1;
}
- has_precision = 0;
- precision = 6;
+ int has_precision = 0;
+ size_t precision = 6;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
{
const char *arg = a.arg[dp->arg_index].a.a_string;
- size_t bytes;
-# if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
- size_t characters;
-# endif
-# if !DCHAR_IS_TCHAR
- /* This code assumes that TCHAR_T is 'char'. */
- static_assert (sizeof (TCHAR_T) == 1);
- DCHAR_T *tmpdst;
- size_t tmpdst_len;
-# endif
- size_t w;
+ size_t bytes;
if (has_precision)
{
/* Use only at most PRECISION bytes, from the left. */
}
# if ENABLE_UNISTDIO && DCHAR_IS_TCHAR
+ size_t characters;
if (has_width)
characters = mbsnlen (arg, bytes);
else
# endif
# if !DCHAR_IS_TCHAR
+ /* This code assumes that TCHAR_T is 'char'. */
+ static_assert (sizeof (TCHAR_T) == 1);
+ DCHAR_T *tmpdst;
+ size_t tmpdst_len;
/* Convert from TCHAR_T[] to DCHAR_T[]. */
tmpdst =
DCHAR_CONV_FROM_ENCODING (locale_charset (),
goto fail_with_errno;
# endif
+ size_t w;
if (has_width)
{
# if ENABLE_UNISTDIO
convert back the result from a char[] to a wchar_t[].
Instead, just copy the argument wchar_t[] to the result. */
int flags = dp->flags;
- size_t width;
- width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
if (dp->conversion == 's')
{
- int has_precision;
- size_t precision;
-
- has_precision = 0;
- precision = 6;
+ int has_precision = 0;
+ size_t precision = 6;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
{
/* Use only at most PRECISION wide characters, from
the left. */
- const wchar_t *ls_arg_end;
-
- ls_arg_end = ls_arg;
+ const wchar_t *ls_arg_end = ls_arg;
characters = 0;
for (; precision > 0; precision--)
{
such bugs, we implement the entire processing of the 's'
directive ourselves. */
int flags = dp->flags;
- int has_width;
- size_t width;
- int has_precision;
- size_t precision;
- has_width = 0;
- width = 0;
+ int has_width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
has_width = 1;
}
- has_precision = 0;
- precision = 6;
+ int has_precision = 0;
+ size_t precision = 6;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
# endif
while (precision > 0)
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
-
if (*arg_end == 0)
/* Found the terminating null wide character. */
break;
- count = local_wcrtomb (cbuf, *arg_end, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, *arg_end, &state);
if (count < 0)
/* Cannot convert. */
goto fail_with_EILSEQ;
# endif
for (;;)
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
-
if (*arg_end == 0)
/* Found the terminating null wide character. */
break;
- count = local_wcrtomb (cbuf, *arg_end, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, *arg_end, &state);
if (count < 0)
/* Cannot convert. */
goto fail_with_EILSEQ;
# if !DCHAR_IS_TCHAR
{
- TCHAR_T *tmpsrc;
-
/* Convert the string into a piece of temporary memory. */
- tmpsrc = (TCHAR_T *) malloc (bytes * sizeof (TCHAR_T));
+ TCHAR_T *tmpsrc = (TCHAR_T *) malloc (bytes * sizeof (TCHAR_T));
if (tmpsrc == NULL)
goto out_of_memory;
{
# endif
for (size_t remaining = bytes; remaining > 0; )
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
-
if (*arg == 0)
abort ();
- count = local_wcrtomb (cbuf, *arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, *arg, &state);
if (count <= 0)
/* Inconsistency. */
abort ();
ENSURE_ALLOCATION (xsum (length, bytes));
for (size_t remaining = bytes; remaining > 0; )
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
-
if (*arg == 0)
abort ();
- count = local_wcrtomb (cbuf, *arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, *arg, &state);
if (count <= 0)
/* Inconsistency. */
abort ();
# endif
while (arg < arg_end)
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
-
if (*arg == 0)
abort ();
- count = local_wcrtomb (cbuf, *arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, *arg, &state);
if (count <= 0)
/* Cannot convert. */
goto fail_with_EILSEQ;
a correct behaviour for the null wint_t argument and/or the
fallback that avoids EILSEQ. */
int flags = dp->flags;
- int has_width;
- size_t width;
- has_width = 0;
- width = 0;
+ int has_width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
# endif
{
/* Count the number of bytes. */
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
mbstate_t state;
mbszero (&state);
# endif
- count = local_wcrtomb (cbuf, arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, arg, &state);
if (count < 0)
/* Cannot convert. */
goto fail_with_EILSEQ;
/* Convert the string into a piece of temporary memory. */
if (bytes > 0)
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
mbstate_t state;
mbszero (&state);
# endif
- count = local_wcrtomb (cbuf, arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, arg, &state);
if (count <= 0)
/* Inconsistency. */
abort ();
ENSURE_ALLOCATION (xsum (length, bytes));
if (bytes > 0)
{
- int count;
# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
mbstate_t state;
mbszero (&state);
# endif
- count = local_wcrtomb (result + length, arg, &state);
+ int count = local_wcrtomb (result + length, arg, &state);
if (count <= 0)
/* Inconsistency. */
abort ();
}
else
{
- char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
- int count;
# if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t
mbstate_t state;
mbszero (&state);
# endif
- count = local_wcrtomb (cbuf, arg, &state);
+ char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */
+ int count = local_wcrtomb (cbuf, arg, &state);
if (count < 0)
/* Cannot convert. */
goto fail_with_EILSEQ;
/* Implement the 'c' directive ourselves, in order to avoid
EILSEQ in the "C" locale. */
int flags = dp->flags;
- size_t width;
- width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
{
char arg = (char) a.arg[dp->arg_index].a.a_char;
mbstate_t state;
- wchar_t wc;
-
mbszero (&state);
+
+ wchar_t wc;
int count = mbrtowc (&wc, &arg, 1, &state);
if (count < 0)
/* Invalid or incomplete multibyte character. */
{
arg_type type = a.arg[dp->arg_index].type;
int flags = dp->flags;
- int has_width;
- size_t width;
- int has_precision;
- size_t precision;
- size_t tmp_length;
- size_t count;
- DCHAR_T tmpbuf[700];
- DCHAR_T *tmp;
- DCHAR_T *tmp_end;
- DCHAR_T *tmp_start;
- DCHAR_T *pad_ptr;
- DCHAR_T *p;
- has_width = 0;
- width = 0;
+ int has_width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
has_width = 1;
}
- has_precision = 0;
- precision = 1;
+ int has_precision = 0;
+ size_t precision = 1;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
}
/* Allocate a temporary buffer of sufficient size. */
+ size_t tmp_length;
switch (type)
{
default:
if (tmp_length < width)
tmp_length = width;
+ DCHAR_T tmpbuf[700];
+ DCHAR_T *tmp;
if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
tmp = tmpbuf;
else
goto out_of_memory;
}
- tmp_end = tmp + tmp_length;
+ DCHAR_T *tmp_end = tmp + tmp_length;
unsigned long long arg;
switch (type)
}
int need_prefix = ((flags & FLAG_ALT) && arg != 0);
- p = tmp_end;
+ DCHAR_T *p = tmp_end;
/* "The result of converting a zero value with a precision
of zero is no characters." */
if (!(has_precision && precision == 0 && arg == 0))
*--p = '0';
}
- pad_ptr = p;
+ DCHAR_T *pad_ptr = p;
if (need_prefix)
{
# endif
*--p = '0';
}
- tmp_start = p;
+ DCHAR_T *tmp_start = p;
/* The generated string now extends from tmp_start to tmp_end,
with the zero padding insertion point being at pad_ptr,
tmp_start <= pad_ptr <= tmp_end. */
- count = tmp_end - tmp_start;
+ size_t count = tmp_end - tmp_start;
if (count < width)
{
{
arg_type type = a.arg[dp->arg_index].type;
int flags = dp->flags;
- size_t width;
- int has_precision;
- size_t precision;
- size_t tmp_length;
- size_t count;
- DCHAR_T tmpbuf[700];
- DCHAR_T *tmp;
- DCHAR_T *pad_ptr;
- DCHAR_T *p;
- width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
goto overflow;
}
- has_precision = 0;
- precision = 0;
+ int has_precision = 0;
+ size_t precision = 0;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
}
/* Allocate a temporary buffer of sufficient size. */
+ size_t tmp_length;
if (type == TYPE_LONGDOUBLE)
tmp_length =
(unsigned int) ((LDBL_DIG + 1)
tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
+ DCHAR_T tmpbuf[700];
+ DCHAR_T *tmp;
if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
tmp = tmpbuf;
else
goto out_of_memory;
}
- pad_ptr = NULL;
- p = tmp;
+ DCHAR_T *pad_ptr = NULL;
+ DCHAR_T *p = tmp;
if (type == TYPE_LONGDOUBLE)
{
# if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || (NEED_WPRINTF_DIRECTIVE_LA && WIDE_CHAR_VERSION)
}
else
{
- int sign = 0;
DECL_LONG_DOUBLE_ROUNDING
BEGIN_LONG_DOUBLE_ROUNDING ();
+ int sign = 0;
if (signbit (arg)) /* arg < 0.0L or negative zero */
{
sign = -1;
{
int exponent;
long double mantissa;
-
if (arg > 0.0L)
mantissa = printf_frexpl (arg, &exponent);
else
*p++ = dp->conversion - 'A' + 'X';
pad_ptr = p;
{
- int digit;
-
- digit = (int) mantissa;
+ int digit = (int) mantissa;
mantissa -= digit;
*p++ = '0' + digit;
if ((flags & FLAG_ALT)
else
{
int sign = 0;
-
if (signbit (arg)) /* arg < 0.0 or negative zero */
{
sign = -1;
{
int exponent;
double mantissa;
-
if (arg > 0.0)
mantissa = printf_frexp (arg, &exponent);
else
*p++ = dp->conversion - 'A' + 'X';
pad_ptr = p;
{
- int digit;
-
- digit = (int) mantissa;
+ int digit = (int) mantissa;
mantissa -= digit;
*p++ = '0' + digit;
if ((flags & FLAG_ALT)
/* The generated string now extends from tmp to p, with the
zero padding insertion point being at pad_ptr. */
- count = p - tmp;
+ size_t count = p - tmp;
if (count < width)
{
arg_type type = a.arg[dp->arg_index].type;
# endif
int flags = dp->flags;
- size_t width;
- size_t count;
- int has_precision;
- size_t precision;
- size_t tmp_length;
- DCHAR_T tmpbuf[700];
- DCHAR_T *tmp;
- DCHAR_T *pad_ptr;
- DCHAR_T *p;
- width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
goto overflow;
}
- has_precision = 0;
- precision = 0;
+ int has_precision = 0;
+ size_t precision = 0;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
precision = 6;
/* Allocate a temporary buffer of sufficient size. */
+ size_t tmp_length;
# if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE
tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1);
# elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE
tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */
+ DCHAR_T tmpbuf[700];
+ DCHAR_T *tmp;
if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T))
tmp = tmpbuf;
else
goto out_of_memory;
}
- pad_ptr = NULL;
- p = tmp;
+ DCHAR_T *pad_ptr = NULL;
+ DCHAR_T *p = tmp;
# if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE
# if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE
}
else
{
- int sign = 0;
DECL_LONG_DOUBLE_ROUNDING
BEGIN_LONG_DOUBLE_ROUNDING ();
+ int sign = 0;
if (signbit (arg)) /* arg < 0.0L or negative zero */
{
sign = -1;
if (dp->conversion == 'f' || dp->conversion == 'F')
{
- char *digits;
- size_t ndigits;
-
- digits =
+ char *digits =
scale10_round_decimal_long_double (arg, precision);
if (digits == NULL)
{
END_LONG_DOUBLE_ROUNDING ();
goto out_of_memory;
}
- ndigits = strlen (digits);
+ size_t ndigits = strlen (digits);
if (ndigits > precision)
{
else
{
/* arg > 0.0L. */
- int adjusted;
+ exponent = floorlog10l (arg);
+ int adjusted = 0;
char *digits;
size_t ndigits;
-
- exponent = floorlog10l (arg);
- adjusted = 0;
for (;;)
{
digits =
else
{
/* arg > 0.0L. */
- int exponent;
- int adjusted;
+ int exponent = floorlog10l (arg);
+ int adjusted = 0;
char *digits;
size_t ndigits;
- size_t nzeroes;
-
- exponent = floorlog10l (arg);
- adjusted = 0;
for (;;)
{
digits =
/* Determine the number of trailing zeroes
that have to be dropped. */
- nzeroes = 0;
+ size_t nzeroes = 0;
if ((flags & FLAG_ALT) == 0)
while (nzeroes < ndigits
&& digits[nzeroes] == '0')
else
{
int sign = 0;
-
if (signbit (arg)) /* arg < 0.0 or negative zero */
{
sign = -1;
if (dp->conversion == 'f' || dp->conversion == 'F')
{
- char *digits;
- size_t ndigits;
-
- digits =
+ char *digits =
scale10_round_decimal_double (arg, precision);
if (digits == NULL)
goto out_of_memory;
- ndigits = strlen (digits);
+ size_t ndigits = strlen (digits);
if (ndigits > precision)
{
else
{
/* arg > 0.0. */
- int adjusted;
+ exponent = floorlog10 (arg);
+ int adjusted = 0;
char *digits;
size_t ndigits;
-
- exponent = floorlog10 (arg);
- adjusted = 0;
for (;;)
{
digits =
else
{
/* arg > 0.0. */
- int exponent;
- int adjusted;
+ int exponent = floorlog10 (arg);
+ int adjusted = 0;
char *digits;
size_t ndigits;
- size_t nzeroes;
-
- exponent = floorlog10 (arg);
- adjusted = 0;
for (;;)
{
digits =
/* Determine the number of trailing zeroes
that have to be dropped. */
- nzeroes = 0;
+ size_t nzeroes = 0;
if ((flags & FLAG_ALT) == 0)
while (nzeroes < ndigits
&& digits[nzeroes] == '0')
/* The generated string now extends from tmp to p, with the
zero padding insertion point being at pad_ptr. */
- count = p - tmp;
+ size_t count = p - tmp;
if (count < width)
{
{
arg_type type = a.arg[dp->arg_index].type;
int flags = dp->flags;
-#if (WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- int has_width;
-#endif
-#if !USE_SNPRINTF || WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- size_t width;
-#endif
-#if !USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- int has_precision;
- size_t precision;
-#endif
#if NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION
int prec_ourselves;
#else
#endif
#if (WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- has_width = 0;
+ int has_width = 0;
#endif
#if !USE_SNPRINTF || WIDE_CHAR_VERSION || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- width = 0;
+ size_t width = 0;
if (dp->width_start != dp->width_end)
{
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
#endif
#if !USE_SNPRINTF || (WIDE_CHAR_VERSION && DCHAR_IS_TCHAR) || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (WIDE_CHAR_VERSION && MUSL_LIBC) || NEED_PRINTF_FLAG_LEFTADJUST || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_FLAG_ALT_PRECISION_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION || NEED_PRINTF_FLAG_GROUPING || NEED_PRINTF_FLAG_GROUPING_INT
- has_precision = 0;
- precision = 6;
+ int has_precision = 0;
+ size_t precision = 6;
if (dp->precision_start != dp->precision_end)
{
if (dp->precision_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->precision_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->precision_arg_index].a.a_int;
+ int arg = a.arg[dp->precision_arg_index].a.a_int;
/* "A negative precision is taken as if the precision
were omitted." */
if (arg >= 0)
quick check anyway. */
if (dp->width_arg_index != ARG_NONE)
{
- int arg;
-
if (!(a.arg[dp->width_arg_index].type == TYPE_INT))
abort ();
- arg = a.arg[dp->width_arg_index].a.a_int;
+ int arg = a.arg[dp->width_arg_index].a.a_int;
width = arg;
if (arg < 0)
{
)
{
/* The result string is not guaranteed to be ASCII. */
- const TCHAR_T *tmpsrc;
- DCHAR_T *tmpdst;
- size_t tmpdst_len;
/* This code assumes that TCHAR_T is 'char'. */
static_assert (sizeof (TCHAR_T) == 1);
+ const TCHAR_T *tmpsrc;
# if USE_SNPRINTF
tmpsrc = (TCHAR_T *) (result + length);
# else
tmpsrc = tmp;
# endif
+ DCHAR_T *tmpdst;
+ size_t tmpdst_len;
# if WIDE_CHAR_VERSION
/* Convert tmpsrc[0..count-1] to a freshly allocated
wide character array. */
# endif
{
const TCHAR_T *tmpsrc;
- DCHAR_T *tmpdst;
-
# if USE_SNPRINTF
if (result == resultbuf)
{
tmpsrc = tmp;
ENSURE_ALLOCATION (xsum (length, count));
# endif
- tmpdst = result + length;
+ DCHAR_T *tmpdst = result + length;
/* Copy backwards, because of overlapping. */
tmpsrc += count;
tmpdst += count;
if (result != resultbuf && length + 1 < allocated)
{
/* Shrink the allocated memory if possible. */
- DCHAR_T *memory;
-
- memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
+ DCHAR_T *memory =
+ (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T));
if (memory != NULL)
result = memory;
}
/* Test for presence of git:
"git --version 2>/dev/null" */
const char *argv[3];
- pid_t child;
- int fd[1];
-
argv[0] = "git";
argv[1] = "--version";
argv[2] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
git_present = false;
else
/* Run "git ls-files FILENAME" and return true if the exit code is 0
and the output is non-empty. */
const char *argv[4];
- pid_t child;
- int fd[1];
-
argv[0] = "git";
argv[1] = "ls-files";
argv[2] = filename;
argv[3] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
return false;
and return true if the exit code is 0.
The '--' option is for the case that the specified file was removed. */
const char *argv[7];
- int exitstatus;
-
argv[0] = "git";
argv[1] = "diff";
argv[2] = "--quiet";
argv[4] = "HEAD";
argv[5] = filename;
argv[6] = NULL;
- exitstatus = execute ("git", "git", argv, NULL, NULL,
- false, false, true, true,
- true, false, NULL);
+
+ int exitstatus = execute ("git", "git", argv, NULL, NULL,
+ false, false, true, true,
+ true, false, NULL);
return (exitstatus == 0);
}
of the change), as the number of seconds since the Epoch.
The '--' option is for the case that the specified file was removed. */
const char *argv[7];
- pid_t child;
- int fd[1];
-
argv[0] = "git";
argv[1] = "log";
argv[2] = "-1";
argv[4] = "--";
argv[5] = filename;
argv[6] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
return -1;
/* Retrieve its result. */
- FILE *fp;
- char *line;
- size_t linesize;
- size_t linelen;
-
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
- line = NULL; linesize = 0;
- linelen = getline (&line, &linesize, fp);
+ char *line = NULL;
+ size_t linesize = 0;
+ size_t linelen = getline (&line, &linesize, fp);
if (linelen == (size_t)(-1))
{
error (0, 0, _("%s subprocess I/O error"), "git");
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "git", true, false, true, false, NULL);
if (exitstatus == 0)
{
/* Run "git rev-parse --show-toplevel 2>/dev/null" and return its output,
without the trailing newline. */
const char *argv[4];
- pid_t child;
- int fd[1];
-
argv[0] = "git";
argv[1] = "rev-parse";
argv[2] = "--show-toplevel";
argv[3] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
return NULL;
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, "git", true, true, true, false, NULL);
if (exitstatus == 0)
{
}
if (i > i0)
{
- pid_t child;
- int fd[1];
-
argv[i] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
break;
}
if (i > i0)
{
- pid_t child;
- int fd[1];
-
argv[i] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
break;
}
if (i > i0)
{
- pid_t child;
- int fd[1];
-
argv[i] = NULL;
- child = create_pipe_in ("git", "git", argv, NULL, NULL,
- DEV_NULL, true, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in ("git", "git", argv, NULL, NULL,
+ DEV_NULL, true, true, false, fd);
if (child == -1)
break;
vdzprintf (int fd, const char *format, va_list args)
{
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
-
- output = vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
+ char *output = vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
return -1;
const char *version, /* const char *author1, ...*/ ...)
{
va_list authors;
-
va_start (authors, version);
version_etc_va (stream, command_name, package, version, authors);
va_end (authors);
vfzprintf (FILE *fp, const char *format, va_list args)
{
char buf[2000];
- char *output;
- size_t len;
size_t lenbuf = sizeof (buf);
-
- output = vasnprintf (buf, &lenbuf, format, args);
- len = lenbuf;
+ char *output = vasnprintf (buf, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
{
static int
rof_open (struct rofile *rof, const char *filename)
{
- int fd;
- unsigned long pagesize;
- size_t size;
-
- fd = open (filename, O_RDONLY | O_CLOEXEC);
+ int fd = open (filename, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
rof->position = 0;
rof->eof_seen = 0;
/* Try the static buffer first. */
- pagesize = 0;
+ unsigned long pagesize = 0;
rof->buffer = rof->stack_allocated_buffer;
- size = sizeof (rof->stack_allocated_buffer);
+ size_t size = sizeof (rof->stack_allocated_buffer);
rof->auxmap = NULL;
rof->auxmap_start = 0;
rof->auxmap_end = 0;
for (;;)
{
- unsigned long start, end;
- unsigned int flags;
- int c;
-
/* Parse one line. First start and end. */
+ unsigned long start, end;
if (!(rof_scanf_lx (&rof, &start) >= 0
&& rof_getchar (&rof) == '-'
&& rof_scanf_lx (&rof, &end) >= 0))
break;
/* Then the flags. */
- do
+ unsigned int flags;
+ {
+ int c;
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ flags = 0;
+ if (c == 'r')
+ flags |= VMA_PROT_READ;
+ c = rof_getchar (&rof);
+ if (c == 'w')
+ flags |= VMA_PROT_WRITE;
c = rof_getchar (&rof);
- while (c == ' ');
- flags = 0;
- if (c == 'r')
- flags |= VMA_PROT_READ;
- c = rof_getchar (&rof);
- if (c == 'w')
- flags |= VMA_PROT_WRITE;
- c = rof_getchar (&rof);
- if (c == 'x')
- flags |= VMA_PROT_EXECUTE;
- while (c = rof_getchar (&rof), c != -1 && c != '\n')
- ;
+ if (c == 'x')
+ flags |= VMA_PROT_EXECUTE;
+ while (c = rof_getchar (&rof), c != -1 && c != '\n')
+ ;
+ }
if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
{
for (;;)
{
- unsigned long start, end;
- unsigned int flags;
- int c;
-
/* Parse one line. First start. */
+ unsigned long start;
if (!(rof_getchar (&rof) == '0'
&& rof_getchar (&rof) == 'x'
&& rof_scanf_lx (&rof, &start) >= 0))
break;
- while (c = rof_peekchar (&rof), c == ' ' || c == '\t')
- rof_getchar (&rof);
+ {
+ int c;
+ while (c = rof_peekchar (&rof), c == ' ' || c == '\t')
+ rof_getchar (&rof);
+ }
/* Then end. */
+ unsigned long end;
if (!(rof_getchar (&rof) == '0'
&& rof_getchar (&rof) == 'x'
&& rof_scanf_lx (&rof, &end) >= 0))
break;
# if defined __FreeBSD__ || defined __DragonFly__
- /* Then the resident pages count. */
- do
- c = rof_getchar (&rof);
- while (c == ' ');
- do
- c = rof_getchar (&rof);
- while (c != -1 && c != '\n' && c != ' ');
- /* Then the private resident pages count. */
- do
- c = rof_getchar (&rof);
- while (c == ' ');
- do
- c = rof_getchar (&rof);
- while (c != -1 && c != '\n' && c != ' ');
- /* Then some kernel address. */
- do
- c = rof_getchar (&rof);
- while (c == ' ');
- do
- c = rof_getchar (&rof);
- while (c != -1 && c != '\n' && c != ' ');
+ {
+ int c;
+ /* Then the resident pages count. */
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ do
+ c = rof_getchar (&rof);
+ while (c != -1 && c != '\n' && c != ' ');
+ /* Then the private resident pages count. */
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ do
+ c = rof_getchar (&rof);
+ while (c != -1 && c != '\n' && c != ' ');
+ /* Then some kernel address. */
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ do
+ c = rof_getchar (&rof);
+ while (c != -1 && c != '\n' && c != ' ');
+ }
# endif
/* Then the flags. */
- do
+ unsigned int flags;
+ {
+ int c;
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ flags = 0;
+ if (c == 'r')
+ flags |= VMA_PROT_READ;
+ c = rof_getchar (&rof);
+ if (c == 'w')
+ flags |= VMA_PROT_WRITE;
c = rof_getchar (&rof);
- while (c == ' ');
- flags = 0;
- if (c == 'r')
- flags |= VMA_PROT_READ;
- c = rof_getchar (&rof);
- if (c == 'w')
- flags |= VMA_PROT_WRITE;
- c = rof_getchar (&rof);
- if (c == 'x')
- flags |= VMA_PROT_EXECUTE;
- while (c = rof_getchar (&rof), c != -1 && c != '\n')
- ;
+ if (c == 'x')
+ flags |= VMA_PROT_EXECUTE;
+ while (c = rof_getchar (&rof), c != -1 && c != '\n')
+ ;
+ }
if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
{
vma_iterate_proc (vma_iterate_callback_fn callback, void *data)
{
char fnamebuf[6+10+4+1];
- char *fname;
- struct rofile rof;
-
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u/map", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - (4 + 1);
+ char *fname = fnamebuf + sizeof (fnamebuf) - (4 + 1);
memcpy (fname, "/map", 4 + 1);
{
unsigned int value = getpid ();
memcpy (fname, "/proc/", 6);
/* Open the current process' maps file. It describes one VMA per line. */
+ struct rofile rof;
if (rof_open (&rof, fname) >= 0)
{
unsigned long auxmap_start = rof.auxmap_start;
for (;;)
{
- unsigned long start, end;
- unsigned int flags;
- int c;
-
/* Parse one line. First start and end. */
+ unsigned long start, end;
if (!(rof_scanf_lx (&rof, &start) >= 0
&& rof_getchar (&rof) == '-'
&& rof_scanf_lx (&rof, &end) >= 0))
break;
/* Then the flags. */
- do
+ unsigned int flags;
+ {
+ int c;
+ do
+ c = rof_getchar (&rof);
+ while (c == ' ');
+ flags = 0;
+ if (c == 'r')
+ flags |= VMA_PROT_READ;
+ c = rof_getchar (&rof);
+ if (c == 'w')
+ flags |= VMA_PROT_WRITE;
c = rof_getchar (&rof);
- while (c == ' ');
- flags = 0;
- if (c == 'r')
- flags |= VMA_PROT_READ;
- c = rof_getchar (&rof);
- if (c == 'w')
- flags |= VMA_PROT_WRITE;
- c = rof_getchar (&rof);
- if (c == 'x')
- flags |= VMA_PROT_EXECUTE;
- while (c = rof_getchar (&rof), c != -1 && c != '\n')
- ;
+ if (c == 'x')
+ flags |= VMA_PROT_EXECUTE;
+ while (c = rof_getchar (&rof), c != -1 && c != '\n')
+ ;
+ }
if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
{
{
/* Documentation: https://www.freebsd.org/cgi/man.cgi?sysctl(3) */
int info_path[] = { CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, getpid () };
- size_t len;
- size_t pagesize;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- char *mem;
- char *p;
- char *p_end;
-
- len = 0;
+ size_t len = 0;
if (sysctl (info_path, 4, NULL, &len, NULL, 0) < 0)
return -1;
/* Allow for small variations over time. In a multithreaded program
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
- pagesize = getpagesize ();
- memneed = len;
+ size_t pagesize = getpagesize ();
+ size_t memneed = len;
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
return -1;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- mem = (char *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ char *mem = (char *) auxmap;
if (sysctl (info_path, 4, mem, &len, NULL, 0) < 0)
{
munmap (auxmap, memneed);
return -1;
}
- p = mem;
- p_end = mem + len;
- while (p < p_end)
- {
- struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
- unsigned long start = kve->kve_start;
- unsigned long end = kve->kve_end;
- unsigned int flags = 0;
- if (kve->kve_protection & KVME_PROT_READ)
- flags |= VMA_PROT_READ;
- if (kve->kve_protection & KVME_PROT_WRITE)
- flags |= VMA_PROT_WRITE;
- if (kve->kve_protection & KVME_PROT_EXEC)
- flags |= VMA_PROT_EXECUTE;
- if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
- {
- /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
- = [start,auxmap_start-1] u [auxmap_end,end-1]. */
- if (start < auxmap_start)
- if (callback (data, start, auxmap_start, flags))
- break;
- if (auxmap_end - 1 < end - 1)
- if (callback (data, auxmap_end, end, flags))
+ {
+ char *p = mem;
+ char *p_end = mem + len;
+ while (p < p_end)
+ {
+ struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
+ unsigned long start = kve->kve_start;
+ unsigned long end = kve->kve_end;
+ unsigned int flags = 0;
+ if (kve->kve_protection & KVME_PROT_READ)
+ flags |= VMA_PROT_READ;
+ if (kve->kve_protection & KVME_PROT_WRITE)
+ flags |= VMA_PROT_WRITE;
+ if (kve->kve_protection & KVME_PROT_EXEC)
+ flags |= VMA_PROT_EXECUTE;
+ if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
+ {
+ /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
+ = [start,auxmap_start-1] u [auxmap_end,end-1]. */
+ if (start < auxmap_start)
+ if (callback (data, start, auxmap_start, flags))
+ break;
+ if (auxmap_end - 1 < end - 1)
+ if (callback (data, auxmap_end, end, flags))
+ break;
+ }
+ else
+ {
+ if (callback (data, start, end, flags))
break;
- }
- else
- {
- if (callback (data, start, end, flags))
- break;
- }
- p += kve->kve_structsize;
- }
+ }
+ p += kve->kve_structsize;
+ }
+ }
munmap (auxmap, memneed);
return 0;
}
parts of each entry. */
offsetof (struct kinfo_vmentry, kve_path);
int info_path[] = { CTL_VM, VM_PROC, VM_PROC_MAP, getpid (), entry_size };
- size_t len;
- size_t pagesize;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- char *mem;
- char *p;
- char *p_end;
-
- len = 0;
+ size_t len = 0;
if (sysctl (info_path, 5, NULL, &len, NULL, 0) < 0)
return -1;
/* Allow for small variations over time. In a multithreaded program
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
- pagesize = getpagesize ();
- memneed = len;
+ size_t pagesize = getpagesize ();
+ size_t memneed = len;
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
return -1;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- mem = (char *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ char *mem = (char *) auxmap;
if (sysctl (info_path, 5, mem, &len, NULL, 0) < 0
|| len > 0x100000 - entry_size)
{
munmap (auxmap, memneed);
return -1;
}
- p = mem;
- p_end = mem + len;
- while (p < p_end)
- {
- struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
- unsigned long start = kve->kve_start;
- unsigned long end = kve->kve_end;
- unsigned int flags = 0;
- if (kve->kve_protection & KVME_PROT_READ)
- flags |= VMA_PROT_READ;
- if (kve->kve_protection & KVME_PROT_WRITE)
- flags |= VMA_PROT_WRITE;
- if (kve->kve_protection & KVME_PROT_EXEC)
- flags |= VMA_PROT_EXECUTE;
- if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
- {
- /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
- = [start,auxmap_start-1] u [auxmap_end,end-1]. */
- if (start < auxmap_start)
- if (callback (data, start, auxmap_start, flags))
- break;
- if (auxmap_end - 1 < end - 1)
- if (callback (data, auxmap_end, end, flags))
+ {
+ char *p = mem;
+ char *p_end = mem + len;
+ while (p < p_end)
+ {
+ struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
+ unsigned long start = kve->kve_start;
+ unsigned long end = kve->kve_end;
+ unsigned int flags = 0;
+ if (kve->kve_protection & KVME_PROT_READ)
+ flags |= VMA_PROT_READ;
+ if (kve->kve_protection & KVME_PROT_WRITE)
+ flags |= VMA_PROT_WRITE;
+ if (kve->kve_protection & KVME_PROT_EXEC)
+ flags |= VMA_PROT_EXECUTE;
+ if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
+ {
+ /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
+ = [start,auxmap_start-1] u [auxmap_end,end-1]. */
+ if (start < auxmap_start)
+ if (callback (data, start, auxmap_start, flags))
+ break;
+ if (auxmap_end - 1 < end - 1)
+ if (callback (data, auxmap_end, end, flags))
+ break;
+ }
+ else
+ {
+ if (callback (data, start, end, flags))
break;
- }
- else
- {
- if (callback (data, start, end, flags))
- break;
- }
- p += entry_size;
- }
+ }
+ p += entry_size;
+ }
+ }
munmap (auxmap, memneed);
return 0;
}
{
/* Documentation: https://man.openbsd.org/sysctl.2 */
int info_path[] = { CTL_KERN, KERN_PROC_VMMAP, getpid () };
- size_t len;
- size_t pagesize;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- char *mem;
-
- len = 0;
+ size_t len = 0;
if (sysctl (info_path, 3, NULL, &len, NULL, 0) < 0)
return -1;
/* Allow for small variations over time. In a multithreaded program
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
- pagesize = getpagesize ();
- memneed = len;
+ size_t pagesize = getpagesize ();
+ size_t memneed = len;
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
return -1;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- mem = (char *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ char *mem = (char *) auxmap;
for (;;)
{
size_t rlen = len;
- char *p;
- char *p_end;
-
if (sysctl (info_path, 3, mem, &rlen, NULL, 0) < 0)
{
/* sysctl failed. */
}
if (rlen == 0)
break;
- p = mem;
- p_end = mem + rlen;
- while (p < p_end)
- {
- struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
- unsigned long start = kve->kve_start;
- unsigned long end = kve->kve_end;
- unsigned int flags = 0;
- if (kve->kve_protection & KVE_PROT_READ)
- flags |= VMA_PROT_READ;
- if (kve->kve_protection & KVE_PROT_WRITE)
- flags |= VMA_PROT_WRITE;
- if (kve->kve_protection & KVE_PROT_EXEC)
- flags |= VMA_PROT_EXECUTE;
- if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
- {
- /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
- = [start,auxmap_start-1] u [auxmap_end,end-1]. */
- if (start < auxmap_start)
- if (callback (data, start, auxmap_start, flags))
- break;
- if (auxmap_end - 1 < end - 1)
- if (callback (data, auxmap_end, end, flags))
- break;
- }
- else
- {
- if (start != end)
- if (callback (data, start, end, flags))
- break;
- }
- p += sizeof (struct kinfo_vmentry);
- }
+ char *p_end = mem + rlen;
+ {
+ char *p = mem;
+ while (p < p_end)
+ {
+ struct kinfo_vmentry *kve = (struct kinfo_vmentry *) p;
+ unsigned long start = kve->kve_start;
+ unsigned long end = kve->kve_end;
+ unsigned int flags = 0;
+ if (kve->kve_protection & KVE_PROT_READ)
+ flags |= VMA_PROT_READ;
+ if (kve->kve_protection & KVE_PROT_WRITE)
+ flags |= VMA_PROT_WRITE;
+ if (kve->kve_protection & KVE_PROT_EXEC)
+ flags |= VMA_PROT_EXECUTE;
+ if (start <= auxmap_start && auxmap_end - 1 <= end - 1)
+ {
+ /* Consider [start,end-1] \ [auxmap_start,auxmap_end-1]
+ = [start,auxmap_start-1] u [auxmap_end,end-1]. */
+ if (start < auxmap_start)
+ if (callback (data, start, auxmap_start, flags))
+ break;
+ if (auxmap_end - 1 < end - 1)
+ if (callback (data, auxmap_end, end, flags))
+ break;
+ }
+ else
+ {
+ if (start != end)
+ if (callback (data, start, end, flags))
+ break;
+ }
+ p += sizeof (struct kinfo_vmentry);
+ }
+ }
if (rlen < len)
break;
/* sysctl returned exactly len entries, which means that another sysctl
only the virtual memory areas that are connected to a file, not the
anonymous ones. But at least since AIX 7.1, it is well usable. */
- size_t pagesize;
- char fnamebuf[6+10+4+1];
- char *fname;
- int fd;
- size_t memneed;
-
- pagesize = getpagesize ();
+ size_t pagesize = getpagesize ();
+ char fnamebuf[6+10+4+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u/map", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - (4+1);
+ char *fname = fnamebuf + sizeof (fnamebuf) - (4+1);
memcpy (fname, "/map", 4+1);
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY | O_CLOEXEC);
+ int fd = open (fname, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
We read the entire contents, but look only at the prmap_t entries and
ignore the tail part. */
- for (memneed = 2 * pagesize; ; memneed = 2 * memneed)
+ for (size_t memneed = 2 * pagesize; ; memneed = 2 * memneed)
{
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
So use mmap(), and ignore the resulting VMA if it occurs among the
resulting VMAs. (Normally it doesn't, because it was allocated after
the open() call.) */
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- ssize_t nbytes;
-
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
{
close (fd);
return -1;
}
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
/* Read the contents of /proc/<pid>/map in a single system call.
This guarantees a consistent result (no duplicated or omitted
entries). */
- retry:
+ retry: ;
+ ssize_t nbytes;
do
nbytes = read (fd, auxmap, memneed);
while (nbytes < 0 && errno == EINTR);
}
/* We now have the entire contents of /proc/<pid>/map in memory. */
- prmap_t* maps = (prmap_t *) auxmap;
+ prmap_t *maps = (prmap_t *) auxmap;
/* The entries are not sorted by address. Therefore
1. Extract the relevant information into an array.
vma_t *vp = vmas;
for (prmap_t *mp = maps;;)
{
- unsigned long start, end;
-
- start = (unsigned long) mp->pr_vaddr;
- end = start + mp->pr_size;
+ unsigned long start = (unsigned long) mp->pr_vaddr;
+ unsigned long end = start + mp->pr_size;
if (start == 0 && end == 0 && mp->pr_mflags == 0)
break;
/* Discard empty VMAs and kernel VMAs. */
if (start < end && (mp->pr_mflags & MA_KERNTEXT) == 0)
{
- unsigned int flags;
- flags = 0;
+ unsigned int flags = 0;
if (mp->pr_mflags & MA_READ)
flags |= VMA_PROT_READ;
if (mp->pr_mflags & MA_WRITE)
# if defined PIOCNMAP && defined PIOCMAP
/* We must use the older /proc interface. */
- size_t pagesize;
- char fnamebuf[6+10+1];
- char *fname;
- int fd;
- int nmaps;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- prmap_t* maps;
-
- pagesize = getpagesize ();
+ size_t pagesize = getpagesize ();
+ char fnamebuf[6+10+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - 1;
+ char *fname = fnamebuf + sizeof (fnamebuf) - 1;
*fname = '\0';
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY | O_CLOEXEC);
+ int fd = open (fname, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
+ int nmaps;
if (ioctl (fd, PIOCNMAP, &nmaps) < 0)
goto fail2;
- memneed = (nmaps + 10) * sizeof (prmap_t);
+ size_t memneed = (nmaps + 10) * sizeof (prmap_t);
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
goto fail2;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- maps = (prmap_t *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ prmap_t *maps = (prmap_t *) auxmap;
if (ioctl (fd, PIOCMAP, maps) < 0)
goto fail1;
for (prmap_t *mp = maps;;)
{
- unsigned long start, end;
- unsigned int flags;
-
- start = (unsigned long) mp->pr_vaddr;
- end = start + mp->pr_size;
+ unsigned long start = (unsigned long) mp->pr_vaddr;
+ unsigned long end = start + mp->pr_size;
if (start == 0 && end == 0)
break;
- flags = 0;
+ unsigned int flags = 0;
if (mp->pr_mflags & MA_READ)
flags |= VMA_PROT_READ;
if (mp->pr_mflags & MA_WRITE)
prmap_t. These are different in 32-bit and 64-bit processes,
but here we are fortunately accessing only the current process. */
- size_t pagesize;
- char fnamebuf[6+10+4+1];
- char *fname;
- int fd;
- int nmaps;
- size_t memneed;
- void *auxmap;
- unsigned long auxmap_start;
- unsigned long auxmap_end;
- prmap_t* maps;
- prmap_t* maps_end;
-
- pagesize = getpagesize ();
+ size_t pagesize = getpagesize ();
+ char fnamebuf[6+10+4+1];
/* Construct fname = sprintf (fnamebuf+i, "/proc/%u/map", getpid ()). */
- fname = fnamebuf + sizeof (fnamebuf) - 1 - 4;
+ char *fname = fnamebuf + sizeof (fnamebuf) - 1 - 4;
memcpy (fname, "/map", 4 + 1);
{
unsigned int value = getpid ();
fname -= 6;
memcpy (fname, "/proc/", 6);
- fd = open (fname, O_RDONLY | O_CLOEXEC);
+ int fd = open (fname, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return -1;
+ int nmaps;
{
struct stat statbuf;
if (fstat (fd, &statbuf) < 0)
nmaps = statbuf.st_size / sizeof (prmap_t);
}
- memneed = (nmaps + 10) * sizeof (prmap_t);
+ size_t memneed = (nmaps + 10) * sizeof (prmap_t);
/* Allocate memneed bytes of memory.
We cannot use alloca here, because not much stack space is guaranteed.
We also cannot use malloc here, because a malloc() call may call mmap()
and thus pre-allocate available memory.
So use mmap(), and ignore the resulting VMA. */
memneed = ((memneed - 1) / pagesize + 1) * pagesize;
- auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ void *auxmap = (void *) mmap ((void *) 0, memneed, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (auxmap == (void *) -1)
goto fail2;
- auxmap_start = (unsigned long) auxmap;
- auxmap_end = auxmap_start + memneed;
- maps = (prmap_t *) auxmap;
+ unsigned long auxmap_start = (unsigned long) auxmap;
+ unsigned long auxmap_end = auxmap_start + memneed;
+ prmap_t *maps = (prmap_t *) auxmap;
/* Read up to memneed bytes from fd into maps. */
+ prmap_t *maps_end;
{
size_t remaining = memneed;
size_t total_read = 0;
for (prmap_t *mp = maps; mp < maps_end; mp++)
{
- unsigned long start, end;
- unsigned int flags;
-
- start = (unsigned long) mp->pr_vaddr;
- end = start + mp->pr_size;
- flags = 0;
+ unsigned long start = (unsigned long) mp->pr_vaddr;
+ unsigned long end = start + mp->pr_size;
+ unsigned int flags = 0;
if (mp->pr_mflags & MA_READ)
flags |= VMA_PROT_READ;
if (mp->pr_mflags & MA_WRITE)
{
int more;
mach_port_t object_name;
- unsigned int flags;
/* In Mac OS X 10.5, the types vm_address_t, vm_offset_t, vm_size_t have
32 bits in 32-bit processes and 64 bits in 64-bit processes. Whereas
mach_vm_address_t and mach_vm_size_t are always 64 bits large.
mach_port_deallocate (mach_task_self (), object_name);
if (!more)
break;
- flags = 0;
+ unsigned int flags = 0;
if (info.protection & VM_PROT_READ)
flags |= VMA_PROT_READ;
if (info.protection & VM_PROT_WRITE)
https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html */
task_t task = mach_task_self ();
- vm_size_t size;
- for (vm_address_t address = 0;; address += size)
+ for (vm_address_t address = 0;; )
{
+ vm_size_t size;
vm_prot_t protection;
vm_prot_t max_protection;
vm_inherit_t inheritance;
boolean_t shared;
memory_object_name_t object_name;
vm_offset_t offset;
- unsigned int flags;
if (!(vm_region (task, &address, &size, &protection, &max_protection,
- &inheritance, &shared, &object_name, &offset)
+ &inheritance, &shared, &object_name, &offset)
== KERN_SUCCESS))
break;
mach_port_deallocate (task, object_name);
- flags = 0;
+ unsigned int flags = 0;
if (protection & VM_PROT_READ)
flags |= VMA_PROT_READ;
if (protection & VM_PROT_WRITE)
flags |= VMA_PROT_EXECUTE;
if (callback (data, address, address + size, flags))
break;
+
+ address += size;
}
return 0;
#elif defined _WIN32 || defined __CYGWIN__
/* Windows platform. Use the native Windows API. */
- MEMORY_BASIC_INFORMATION info;
uintptr_t address = 0;
-
+ MEMORY_BASIC_INFORMATION info;
while (VirtualQuery ((void*)address, &info, sizeof(info)) == sizeof(info))
{
if (info.State != MEM_FREE)
distinguished from areas reserved for future malloc(). */
if (info.State != MEM_RESERVE)
{
- uintptr_t start, end;
+ uintptr_t start = (uintptr_t)info.BaseAddress;
+ uintptr_t end = start + info.RegionSize;
unsigned int flags;
-
- start = (uintptr_t)info.BaseAddress;
- end = start + info.RegionSize;
switch (info.Protect & ~(PAGE_GUARD|PAGE_NOCACHE))
{
case PAGE_READONLY:
#elif defined __BEOS__ || defined __HAIKU__
/* Use the BeOS specific API. */
+ ssize_t cookie = 0;
area_info info;
- ssize_t cookie;
-
- cookie = 0;
while (get_next_area_info (0, &cookie, &info) == B_OK)
{
- unsigned long start, end;
- unsigned int flags;
-
- start = (unsigned long) info.address;
- end = start + info.size;
- flags = 0;
+ unsigned long start = (unsigned long) info.address;
+ unsigned long end = start + info.size;
+ unsigned int flags = 0;
if (info.protection & B_READ_AREA)
flags |= VMA_PROT_READ;
if (info.protection & B_WRITE_AREA)
# endif
{
- uintptr_t pagesize;
- uintptr_t address;
- int /*bool*/ address_known_mapped;
-
- pagesize = getpagesize ();
+ uintptr_t pagesize = getpagesize ();
/* Avoid calling mquery with a NULL first argument, because this argument
value has a specific meaning. We know the NULL page is unmapped. */
- address = pagesize;
- address_known_mapped = 0;
+ uintptr_t address = pagesize;
+ int /*bool*/ address_known_mapped = 0;
for (;;)
{
/* Test whether the page at address is mapped. */
/* The page at address is mapped.
This is the start of an interval. */
uintptr_t start = address;
- uintptr_t end;
/* Find the end of the interval. */
- end = (uintptr_t) mquery ((void *) address, pagesize, 0, 0, -1, 0);
+ uintptr_t end =
+ (uintptr_t) mquery ((void *) address, pagesize, 0, 0, -1, 0);
if (end == (uintptr_t) (void *) -1)
end = 0; /* wrap around */
+
address = end;
/* When wrapping around, OpenBSD 7.6/x86_64 produces an interval
ptrdiff_t
vsnzprintf (char *str, size_t size, const char *format, va_list args)
{
- char *output;
- size_t len;
size_t lenbuf = size;
-
- output = vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+ char *output = vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
return -1;
ptrdiff_t
vszprintf (char *str, const char *format, va_list args)
{
- char *output;
- size_t len;
- size_t lenbuf;
-
/* Set lenbuf = min (SIZE_MAX, - (uintptr_t) str - 1). */
- lenbuf = SIZE_MAX;
+ size_t lenbuf = SIZE_MAX;
if (lenbuf >= ~ (uintptr_t) str)
lenbuf = ~ (uintptr_t) str;
- output = vasnprintf (str, &lenbuf, format, args);
- len = lenbuf;
+ char *output = vasnprintf (str, &lenbuf, format, args);
+ size_t len = lenbuf;
if (!output)
return -1;
if (waitpid_pfn == NULL)
{
- void *libcx_handle;
-
/* Try to use waitpid() of LIBCx first if available because it can
process the return value of spawn-family of kLIBC as well as spawn2()
of LIBCx. */
- libcx_handle = dlopen ("libcx0", RTLD_LAZY);
+ void *libcx_handle = dlopen ("libcx0", RTLD_LAZY);
if (libcx_handle != NULL)
waitpid_pfn = dlsym (libcx_handle, "_waitpid");
/* If not available, falls back to waitpid() of kLIBC. */
bool slave_process, bool exit_on_error,
int *termsigp)
{
+ if (termsigp != NULL)
+ *termsigp = 0;
+
#if HAVE_WAITID && defined WNOWAIT && 0
/* Commented out because waitid() without WEXITED and with WNOWAIT doesn't
work: On Solaris 7, it returns -1 and sets errno = ECHILD, and on
meanwhile another process acquires the same PID as child, and then - still
before unregister_slave_subprocess() - this process gets a fatal signal,
it would kill the other totally unrelated process. */
- siginfo_t info;
- if (termsigp != NULL)
- *termsigp = 0;
+ siginfo_t info;
for (;;)
{
if (waitid (P_PID, child, &info, WEXITED | (slave_process ? WNOWAIT : 0))
}
#else
/* waitpid() is just as portable as wait() nowadays. */
- int status;
- if (termsigp != NULL)
- *termsigp = 0;
- status = 0;
+ int status = 0;
for (;;)
{
int result = waitpid (child, &status, 0);
critical_factorization (const UNIT *needle, size_t needle_len,
size_t *period)
{
- /* Index of last character of left half, or SIZE_MAX. */
- size_t max_suffix, max_suffix_rev;
- size_t j; /* Index into NEEDLE for current candidate suffix. */
- size_t k; /* Offset into current period. */
- size_t p; /* Intermediate period. */
- UNIT a, b; /* Current comparison characters. */
-
/* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered
out 0-length needles. */
if (needle_len < 3)
*/
/* Perform lexicographic search. */
- max_suffix = SIZE_MAX;
- j = 0;
- k = p = 1;
- while (j + k < needle_len)
- {
- a = CANON_ELEMENT (needle[j + k]);
- b = CANON_ELEMENT (needle[max_suffix + k]);
- if (a < b)
- {
- /* Suffix is smaller, period is entire prefix so far. */
- j += k;
- k = 1;
- p = j - max_suffix;
- }
- else if (a == b)
- {
- /* Advance through repetition of the current period. */
- if (k != p)
- ++k;
- else
- {
- j += p;
- k = 1;
- }
- }
- else /* b < a */
- {
- /* Suffix is larger, start over from current location. */
- max_suffix = j++;
- k = p = 1;
- }
- }
- *period = p;
+ size_t max_suffix = /* Index of last character of left half, or SIZE_MAX. */
+ SIZE_MAX;
+ {
+ size_t j = 0; /* Index into NEEDLE for current candidate suffix. */
+ size_t k = 1; /* Offset into current period. */
+ size_t p = 1; /* Intermediate period. */
+ while (j + k < needle_len)
+ {
+ UNIT a = CANON_ELEMENT (needle[j + k]);
+ UNIT b = CANON_ELEMENT (needle[max_suffix + k]);
+ if (a < b)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* b < a */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix = j++;
+ k = p = 1;
+ }
+ }
+ *period = p;
+ }
/* Perform reverse lexicographic search. */
- max_suffix_rev = SIZE_MAX;
- j = 0;
- k = p = 1;
- while (j + k < needle_len)
- {
- a = CANON_ELEMENT (needle[j + k]);
- b = CANON_ELEMENT (needle[max_suffix_rev + k]);
- if (b < a)
- {
- /* Suffix is smaller, period is entire prefix so far. */
- j += k;
- k = 1;
- p = j - max_suffix_rev;
- }
- else if (a == b)
- {
- /* Advance through repetition of the current period. */
- if (k != p)
- ++k;
- else
- {
- j += p;
- k = 1;
- }
- }
- else /* a < b */
- {
- /* Suffix is larger, start over from current location. */
- max_suffix_rev = j++;
- k = p = 1;
- }
- }
+ size_t max_suffix_rev = /* Index of last character of left half, or SIZE_MAX. */
+ SIZE_MAX;
+ size_t p_rev;
+ {
+ size_t j = 0; /* Index into NEEDLE for current candidate suffix. */
+ size_t k = 1; /* Offset into current period. */
+ size_t p = 1; /* Intermediate period. */
+ while (j + k < needle_len)
+ {
+ UNIT a = CANON_ELEMENT (needle[j + k]);
+ UNIT b = CANON_ELEMENT (needle[max_suffix_rev + k]);
+ if (b < a)
+ {
+ /* Suffix is smaller, period is entire prefix so far. */
+ j += k;
+ k = 1;
+ p = j - max_suffix_rev;
+ }
+ else if (a == b)
+ {
+ /* Advance through repetition of the current period. */
+ if (k != p)
+ ++k;
+ else
+ {
+ j += p;
+ k = 1;
+ }
+ }
+ else /* a < b */
+ {
+ /* Suffix is larger, start over from current location. */
+ max_suffix_rev = j++;
+ k = p = 1;
+ }
+ }
+ p_rev = p;
+ }
/* Choose the shorter suffix. Return the index of the first character
of the right half, rather than the last character of the left half.
factorization. */
if (max_suffix_rev + 1 < max_suffix + 1)
return max_suffix + 1;
- *period = p;
+ *period = p_rev;
return max_suffix_rev + 1;
}
two_way_short_needle (const UNIT *haystack, size_t haystack_len,
const UNIT *needle, size_t needle_len)
{
- size_t i; /* Index into current character of NEEDLE. */
- size_t j; /* Index into current window of HAYSTACK. */
- size_t period; /* The period of the right half of needle. */
- size_t suffix; /* The index of the right half of needle. */
-
/* Factor the needle into two halves, such that the left half is
smaller than the global period, and the right half is
periodic (with a period as large as NEEDLE_LEN - suffix). */
- suffix = critical_factorization (needle, needle_len, &period);
+ size_t period; /* The period of the right half of needle. */
+ size_t suffix = /* The index of the right half of needle. */
+ critical_factorization (needle, needle_len, &period);
/* Perform the search. Each iteration compares the right half
first. */
only advance by the period, so use memory to avoid rescanning
known occurrences of the period in the right half. */
size_t memory = 0;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
- i = MAX (suffix, memory);
+ size_t i = /* Index into current character of NEEDLE. */
+ MAX (suffix, memory);
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
/* The two halves of needle are distinct; no extra memory is
required, and any mismatch results in a maximal shift. */
period = MAX (suffix, needle_len - suffix) + 1;
- j = 0;
+ size_t j = 0; /* Index into current window of HAYSTACK. */
while (AVAILABLE (haystack, haystack_len, j, needle_len))
{
/* Scan for matches in right half. */
- i = suffix;
+ size_t i = /* Index into current character of NEEDLE. */
+ suffix;
while (i < needle_len && (CANON_ELEMENT (needle[i])
== CANON_ELEMENT (haystack[i + j])))
++i;
RETURN_TYPE
FUNC (const UNIT *haystack_start, const UNIT *needle_start)
{
- const UNIT *haystack = haystack_start;
const UNIT *needle = needle_start;
- size_t needle_len; /* Length of NEEDLE. */
- size_t haystack_len; /* Known minimum length of HAYSTACK. */
- bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
- while (*haystack && *needle)
- ok &= *haystack++ == *needle++;
- if (*needle)
- return NULL;
- if (ok)
- return (RETURN_TYPE) haystack_start;
+ {
+ const UNIT *haystack = haystack_start;
+ bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */
+ while (*haystack && *needle)
+ ok &= *haystack++ == *needle++;
+ if (*needle)
+ return NULL;
+ if (ok)
+ return (RETURN_TYPE) haystack_start;
+ }
/* Reduce the size of haystack using STRCHR, since it has a smaller
linear coefficient than the Two-Way algorithm. */
- needle_len = needle - needle_start;
- haystack = STRCHR (haystack_start + 1, *needle_start);
+ size_t needle_len = /* Length of NEEDLE. */
+ needle - needle_start;
+ const UNIT *haystack = STRCHR (haystack_start + 1, *needle_start);
if (!haystack || __builtin_expect (needle_len == 1, 0))
return (RETURN_TYPE) haystack;
needle -= needle_len;
- haystack_len = (haystack > haystack_start + needle_len ? 1
- : needle_len + haystack_start - haystack);
+ size_t haystack_len = /* Known minimum length of HAYSTACK. */
+ (haystack > haystack_start + needle_len ? 1
+ : needle_len + haystack_start - haystack);
/* Perform the search. */
return two_way_short_needle (haystack, haystack_len,
int
FUNC (const UNIT *s, size_t n)
{
- int count = 0;
- for (; n > 0; s++, n--)
- {
- UNIT c = *s;
- if (c == (UNIT)'\0')
- break;
+ {
+ int count = 0;
+ for (; n > 0; s++, n--)
{
- int width = CHARACTER_WIDTH (c);
- if (width < 0)
- goto found_nonprinting;
- if (width > INT_MAX - count)
- goto overflow;
- count += width;
+ UNIT c = *s;
+ if (c == (UNIT)'\0')
+ break;
+ {
+ int width = CHARACTER_WIDTH (c);
+ if (width < 0)
+ goto found_nonprinting;
+ if (width > INT_MAX - count)
+ goto overflow;
+ count += width;
+ }
}
- }
- return count;
+ return count;
+ }
/* The total width has become > INT_MAX.
Continue searching for a non-printing wide character. */
size_t
wcsxfrm (wchar_t *s1, const wchar_t *s2, size_t n)
{
- char mbbuf2[1024];
- char *mbs2;
-
{
int saved_errno = errno;
- size_t result;
+ char mbbuf2[1024];
+ char *mbs2;
/* Convert s2 to a multibyte string, trying to avoid malloc(). */
{
- size_t ret;
-
- ret = wcstombs (mbbuf2, s2, sizeof (mbbuf2));
+ size_t ret = wcstombs (mbbuf2, s2, sizeof (mbbuf2));
if (ret == (size_t)-1)
goto failed;
if (ret < sizeof (mbbuf2))
/* Transform the multibyte string. */
errno = 0;
- result = strxfrm ((char *)s1, mbs2, n);
+ size_t result = strxfrm ((char *)s1, mbs2, n);
if (errno != 0)
{
/* An error occurred. */
else
{
mbstate_t state;
- size_t result;
-
mbszero (&state);
- result = wcrtomb (s, wc, &state);
+
+ size_t result = wcrtomb (s, wc, &state);
if (result == (size_t)-1)
return -1;
return result;
wchar_t *
wgetcwd (wchar_t *buf, size_t size)
{
- wchar_t *result;
-
/* Uses _wgetcwd.
Documentation:
<https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getcwd-wgetcwd>
errno = ENOMEM;
return NULL;
}
- result = _wgetcwd (buf, size + 2);
+ wchar_t *result = _wgetcwd (buf, size + 2);
if (!result)
{
free (buf);
wchar_t *ptr = _wgetcwd (tmp, size);
if (ptr)
{
- result = _wcsdup (ptr);
+ wchar_t *result = _wcsdup (ptr);
if (!result)
errno = ENOMEM;
return result;
}
/* My what a large directory name we have. */
+ wchar_t *result;
do
{
size <<= 1;
static struct glwthread_waitqueue_element *
glwthread_waitqueue_add (glwthread_waitqueue_t *wq)
{
- struct glwthread_waitqueue_element *elt;
- HANDLE event;
-
/* Allocate the memory for the waitqueue element on the heap, not on the
thread's stack. If the thread exits unexpectedly, we prefer to leak
some memory rather than to access unavailable memory and crash. */
- elt =
+ struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *)
malloc (sizeof (struct glwthread_waitqueue_element));
if (elt == NULL)
/* Whether the created event is a manual-reset one or an auto-reset one,
does not matter, since we will wait on it only once. */
- event = CreateEvent (NULL, TRUE, FALSE, NULL);
+ HANDLE event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (event == INVALID_HANDLE_VALUE)
{
/* No way to allocate an event. */
{
struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *) wq->wq_list.wql_next;
- struct glwthread_waitqueue_link *prev;
- struct glwthread_waitqueue_link *next;
/* Remove elt from the circular list. */
- prev = &wq->wq_list; /* = elt->link.wql_prev; */
- next = elt->link.wql_next;
+ struct glwthread_waitqueue_link *prev = &wq->wq_list; /* = elt->link.wql_prev; */
+ struct glwthread_waitqueue_link *next = elt->link.wql_next;
prev->wql_next = next;
next->wql_prev = prev;
elt->link.wql_next = NULL;
{
struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *) l;
- struct glwthread_waitqueue_link *prev;
- struct glwthread_waitqueue_link *next;
/* Remove elt from the circular list. */
- prev = &wq->wq_list; /* = elt->link.wql_prev; */
- next = elt->link.wql_next;
+ struct glwthread_waitqueue_link *prev = &wq->wq_list; /* = elt->link.wql_prev; */
+ struct glwthread_waitqueue_link *next = elt->link.wql_next;
prev->wql_next = next;
next->wql_prev = prev;
elt->link.wql_next = NULL;
else
{
HANDLE event = elt->event;
- int err;
- DWORD result;
/* Now release the mutex and let any other thread take it. */
- err = mutex_unlock (mutex);
+ int err = mutex_unlock (mutex);
if (err != 0)
{
EnterCriticalSection (&cond->lock);
This is fulfilled here, because the thread signalling is done
through SetEvent, not PulseEvent. */
/* Wait until another thread signals this event. */
- result = WaitForSingleObject (event, INFINITE);
+ DWORD result = WaitForSingleObject (event, INFINITE);
if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
abort ();
CloseHandle (event);
{
struct timeval currtime;
-
gettimeofday (&currtime, NULL);
if (currtime.tv_sec > abstime->tv_sec
|| (currtime.tv_sec == abstime->tv_sec
else
{
HANDLE event = elt->event;
- int err;
- DWORD timeout;
- DWORD result;
/* Now release the mutex and let any other thread take it. */
- err = mutex_unlock (mutex);
- if (err != 0)
- {
- EnterCriticalSection (&cond->lock);
- glwthread_waitqueue_remove (&cond->waiters, elt);
- LeaveCriticalSection (&cond->lock);
- CloseHandle (event);
- free (elt);
- return err;
- }
+ {
+ int err = mutex_unlock (mutex);
+ if (err != 0)
+ {
+ EnterCriticalSection (&cond->lock);
+ glwthread_waitqueue_remove (&cond->waiters, elt);
+ LeaveCriticalSection (&cond->lock);
+ CloseHandle (event);
+ free (elt);
+ return err;
+ }
+ }
/* POSIX says:
"If another thread is able to acquire the mutex after the
about-to-block thread has released it, then a subsequent call to
/* Wait until another thread signals this event or until the abstime
passes. */
gettimeofday (&currtime, NULL);
+ DWORD timeout;
if (currtime.tv_sec > abstime->tv_sec)
timeout = 0;
else
}
}
}
- result = WaitForSingleObject (event, timeout);
+ DWORD result = WaitForSingleObject (event, timeout);
if (result == WAIT_FAILED)
abort ();
if (result == WAIT_TIMEOUT)
free (elt);
/* Take the mutex again. It does not matter whether this is done
before or after the bookkeeping for WAIT_TIMEOUT. */
- err = mutex_lock (mutex);
+ int err = mutex_lock (mutex);
return (err ? err :
result == WAIT_OBJECT_0 ? 0 :
result == WAIT_TIMEOUT ? ETIMEDOUT :
execute_and_read_line (const char *progname,
const char *prog_path, const char * const *prog_argv)
{
- pid_t child;
- int fd[1];
- FILE *fp;
- char *line;
- size_t linesize;
- size_t linelen;
-
/* Open a pipe to the program. */
- child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
- DEV_NULL, false, true, false, fd);
+ int fd[1];
+ pid_t child = create_pipe_in (progname, prog_path, prog_argv, NULL, NULL,
+ DEV_NULL, false, true, false, fd);
if (child == -1)
return NULL;
/* Retrieve its result. */
- fp = fdopen (fd[0], "r");
+ FILE *fp = fdopen (fd[0], "r");
if (fp == NULL)
error (EXIT_FAILURE, errno, _("fdopen() failed"));
- line = NULL; linesize = 0;
- linelen = getline (&line, &linesize, fp);
+ char *line = NULL;
+ size_t linesize = 0;
+ size_t linelen = getline (&line, &linesize, fp);
if (linelen == (size_t)(-1))
{
error (0, 0, _("%s subprocess I/O error"), progname);
}
else
{
- int exitstatus;
-
if (linelen > 0 && line[linelen - 1] == '\n')
line[linelen - 1] = '\0';
fclose (fp);
/* Remove zombie process from process list, and retrieve exit status. */
- exitstatus =
+ int exitstatus =
wait_subprocess (child, progname, true, false, true, false, NULL);
if (exitstatus == 0)
return line;
{
/* It's an absolute POSIX-style file name. */
const char *argv[4];
-
argv[0] = "cygpath";
argv[1] = "-w";
argv[2] = filename;
static HANDLE
glwthread_waitqueue_add (glwthread_waitqueue_t *wq)
{
- HANDLE event;
- unsigned int index;
-
if (wq->count == wq->alloc)
{
unsigned int new_alloc = 2 * wq->alloc + 1;
}
/* Whether the created event is a manual-reset one or an auto-reset one,
does not matter, since we will wait on it only once. */
- event = CreateEvent (NULL, TRUE, FALSE, NULL);
+ HANDLE event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (event == INVALID_HANDLE_VALUE)
/* No way to allocate an event. */
return INVALID_HANDLE_VALUE;
- index = wq->offset + wq->count;
+ unsigned int index = wq->offset + wq->count;
if (index >= wq->alloc)
index -= wq->alloc;
wq->array[index] = event;
HANDLE event = glwthread_waitqueue_add (&lock->waiting_readers);
if (event != INVALID_HANDLE_VALUE)
{
- DWORD result;
LeaveCriticalSection (&lock->lock);
/* Wait until another thread signals this event. */
- result = WaitForSingleObject (event, INFINITE);
+ DWORD result = WaitForSingleObject (event, INFINITE);
if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
abort ();
CloseHandle (event);
HANDLE event = glwthread_waitqueue_add (&lock->waiting_writers);
if (event != INVALID_HANDLE_VALUE)
{
- DWORD result;
LeaveCriticalSection (&lock->lock);
/* Wait until another thread signals this event. */
- result = WaitForSingleObject (event, INFINITE);
+ DWORD result = WaitForSingleObject (event, INFINITE);
if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
abort ();
CloseHandle (event);
quoted_arg_length (const char *string)
{
bool quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
- size_t length;
- unsigned int backslashes;
- length = 0;
- backslashes = 0;
+ size_t length = 0;
+ unsigned int backslashes = 0;
if (quote_around)
length++;
for (const char *s = string; *s != '\0'; s++)
quoted_arg_string (const char *string, char *mem)
{
bool quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
- char *p;
- unsigned int backslashes;
- p = mem;
- backslashes = 0;
+ char *p = mem;
+ unsigned int backslashes = 0;
if (quote_around)
*p++ = '"';
for (const char *s = string; *s != '\0'; s++)
const char **
prepare_spawn (const char * const *argv, char **mem_to_free)
{
- size_t argc;
- const char **new_argv;
-
/* Count number of arguments. */
+ size_t argc;
for (argc = 0; argv[argc] != NULL; argc++)
;
/* Allocate new argument vector. */
- new_argv = (const char **) malloc ((1 + argc + 1) * sizeof (const char *));
+ const char **new_argv =
+ (const char **) malloc ((1 + argc + 1) * sizeof (const char *));
/* Add an element upfront that can be used when argv[0] turns out to be a
script, not a program.
for (size_t i = 0; i < argc; i++)
{
const char *string = argv[i];
- size_t length;
+ size_t length;
if (string[0] == '\0')
length = strlen ("\"\"");
else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
length = quoted_arg_length (string);
else
length = strlen (string);
+
needed_size += length + 1;
}
compose_command (const char * const *argv)
{
/* Just concatenate the argv[] strings, separated by spaces. */
- char *command;
/* Determine the size of the needed block of memory. */
size_t total_size = 0;
- const char *p;
- for (const char * const *ap = argv; (p = *ap) != NULL; ap++)
- total_size += strlen (p) + 1;
+ {
+ const char *p;
+ for (const char * const *ap = argv; (p = *ap) != NULL; ap++)
+ total_size += strlen (p) + 1;
+ }
size_t command_size = (total_size > 0 ? total_size : 1);
/* Allocate the block of memory. */
- command = (char *) malloc (command_size);
+ char *command = (char *) malloc (command_size);
if (command == NULL)
{
errno = ENOMEM;
if (total_size > 0)
{
char *cp = command;
+ const char *p;
for (const char * const *ap = argv; (p = *ap) != NULL; ap++)
{
size_t size = strlen (p) + 1;
/* Guess the size of the needed block of memory.
The guess will be exact if other threads don't make modifications. */
size_t total_size = 0;
- const char *p;
if (new_PATH != NULL)
total_size += strlen (new_PATH) + 1;
- for (const char * const *ep = envp; (p = *ep) != NULL; ep++)
- if (!(new_PATH != NULL && strncmp (p, "PATH=", 5) == 0))
- total_size += strlen (p) + 1;
+ {
+ const char *p;
+ for (const char * const *ep = envp; (p = *ep) != NULL; ep++)
+ if (!(new_PATH != NULL && strncmp (p, "PATH=", 5) == 0))
+ total_size += strlen (p) + 1;
+ }
size_t envblock_size = total_size;
/* Allocate the block of memory. */
memcpy (envblock + envblock_used, new_PATH, size);
envblock_used += size;
}
- for (const char * const *ep = envp; (p = *ep) != NULL; ep++)
- if (!(new_PATH != NULL && strncmp (p, "PATH=", 5) == 0))
- {
- size_t size = strlen (p) + 1;
- if (envblock_used + size > envblock_size)
- {
- /* Other threads did modifications. Need more memory. */
- envblock_size += envblock_size / 2;
- if (envblock_used + size > envblock_size)
- envblock_size = envblock_used + size;
-
- char *new_envblock =
- (char *) realloc (envblock, envblock_size + 1);
- if (new_envblock == NULL)
- {
- free (envblock);
- errno = ENOMEM;
- return NULL;
- }
+ {
+ const char *p;
+ for (const char * const *ep = envp; (p = *ep) != NULL; ep++)
+ if (!(new_PATH != NULL && strncmp (p, "PATH=", 5) == 0))
+ {
+ size_t size = strlen (p) + 1;
+ if (envblock_used + size > envblock_size)
+ {
+ /* Other threads did modifications. Need more memory. */
+ envblock_size += envblock_size / 2;
+ if (envblock_used + size > envblock_size)
+ envblock_size = envblock_used + size;
+
+ char *new_envblock =
+ (char *) realloc (envblock, envblock_size + 1);
+ if (new_envblock == NULL)
+ {
+ free (envblock);
+ errno = ENOMEM;
+ return NULL;
+ }
envblock = new_envblock;
}
- memcpy (envblock + envblock_used, p, size);
- envblock_used += size;
- if (envblock[envblock_used - 1] != '\0')
- {
- /* Other threads did modifications. Restart. */
- free (envblock);
- goto retry;
- }
- }
+ memcpy (envblock + envblock_used, p, size);
+ envblock_used += size;
+ if (envblock[envblock_used - 1] != '\0')
+ {
+ /* Other threads did modifications. Restart. */
+ free (envblock);
+ goto retry;
+ }
+ }
+ }
envblock[envblock_used] = '\0';
return envblock;
}
glwthread_thread_t
glwthread_thread_self (void)
{
- glwthread_thread_t thread;
-
if (self_key == (DWORD)-1)
init_self_key ();
- thread = TlsGetValue (self_key);
+ glwthread_thread_t thread = TlsGetValue (self_key);
if (thread == NULL)
{
/* This happens only in threads that have not been created through
{
unsigned int thread_id;
- HANDLE thread_handle;
-
- thread_handle = (HANDLE)
+ HANDLE thread_handle = (HANDLE)
_beginthreadex (NULL, 100000, wrapper_func, thread, 0, &thread_id);
/* calls CreateThread with the same arguments */
if (thread_handle == NULL)
{
struct timeval currtime;
- DWORD timeout;
- DWORD result;
-
gettimeofday (&currtime, NULL);
/* Wait until another thread signals the event or until the
abstime passes. */
+ DWORD timeout;
if (currtime.tv_sec > abstime->tv_sec)
timeout = 0;
else
/* WaitForSingleObject
<https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject> */
- result = WaitForSingleObject (mutex->event, timeout);
+ DWORD result = WaitForSingleObject (mutex->event, timeout);
if (result == WAIT_FAILED)
abort ();
if (result == WAIT_TIMEOUT)
{
struct timeval currtime;
- DWORD timeout;
- DWORD result;
-
gettimeofday (&currtime, NULL);
/* Wait until another thread signals the event or until the
abstime passes. */
+ DWORD timeout;
if (currtime.tv_sec > abstime->tv_sec)
timeout = 0;
else
/* WaitForSingleObject
<https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject> */
- result = WaitForSingleObject (mutex->event, timeout);
+ DWORD result = WaitForSingleObject (mutex->event, timeout);
if (result == WAIT_FAILED)
abort ();
if (result == WAIT_TIMEOUT)
static struct glwthread_waitqueue_element *
glwthread_waitqueue_add (glwthread_waitqueue_t *wq)
{
- struct glwthread_waitqueue_element *elt;
- HANDLE event;
-
/* Allocate the memory for the waitqueue element on the heap, not on the
thread's stack. If the thread exits unexpectedly, we prefer to leak
some memory rather than to access unavailable memory and crash. */
- elt =
+ struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *)
malloc (sizeof (struct glwthread_waitqueue_element));
if (elt == NULL)
/* Whether the created event is a manual-reset one or an auto-reset one,
does not matter, since we will wait on it only once. */
- event = CreateEvent (NULL, TRUE, FALSE, NULL);
+ HANDLE event = CreateEvent (NULL, TRUE, FALSE, NULL);
if (event == INVALID_HANDLE_VALUE)
{
/* No way to allocate an event. */
{
struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *) wq->wq_list.wql_next;
- struct glwthread_waitqueue_link *prev;
- struct glwthread_waitqueue_link *next;
/* Remove elt from the circular list. */
- prev = &wq->wq_list; /* = elt->link.wql_prev; */
- next = elt->link.wql_next;
+ struct glwthread_waitqueue_link *prev = &wq->wq_list; /* = elt->link.wql_prev; */
+ struct glwthread_waitqueue_link *next = elt->link.wql_next;
prev->wql_next = next;
next->wql_prev = prev;
elt->link.wql_next = NULL;
{
struct glwthread_waitqueue_element *elt =
(struct glwthread_waitqueue_element *) l;
- struct glwthread_waitqueue_link *prev;
- struct glwthread_waitqueue_link *next;
/* Remove elt from the circular list. */
- prev = &wq->wq_list; /* = elt->link.wql_prev; */
- next = elt->link.wql_next;
+ struct glwthread_waitqueue_link *prev = &wq->wq_list; /* = elt->link.wql_prev; */
+ struct glwthread_waitqueue_link *next = elt->link.wql_next;
prev->wql_next = next;
next->wql_prev = prev;
elt->link.wql_next = NULL;
if (elt != NULL)
{
HANDLE event = elt->event;
- DWORD result;
LeaveCriticalSection (&lock->lock);
/* Wait until another thread signals this event. */
- result = WaitForSingleObject (event, INFINITE);
+ DWORD result = WaitForSingleObject (event, INFINITE);
if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
abort ();
CloseHandle (event);
if (elt != NULL)
{
HANDLE event = elt->event;
- DWORD result;
LeaveCriticalSection (&lock->lock);
/* Wait until another thread signals this event. */
- result = WaitForSingleObject (event, INFINITE);
+ DWORD result = WaitForSingleObject (event, INFINITE);
if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
abort ();
CloseHandle (event);
if (elt != NULL)
{
HANDLE event = elt->event;
- struct timeval currtime;
- DWORD timeout;
- DWORD result;
- int retval;
LeaveCriticalSection (&lock->lock);
+ struct timeval currtime;
gettimeofday (&currtime, NULL);
/* Wait until another thread signals this event or until the
abstime passes. */
+ DWORD timeout;
if (currtime.tv_sec > abstime->tv_sec)
timeout = 0;
else
{
/* WaitForSingleObject
<https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject> */
- result = WaitForSingleObject (event, timeout);
+ DWORD result = WaitForSingleObject (event, timeout);
if (result == WAIT_FAILED)
abort ();
if (result != WAIT_TIMEOUT)
}
EnterCriticalSection (&lock->lock);
/* Remove ourselves from the waiting_readers. */
+ int retval;
if (glwthread_waitqueue_remove (&lock->waiting_readers, elt))
retval = ETIMEDOUT;
else
if (elt != NULL)
{
HANDLE event = elt->event;
- struct timeval currtime;
- DWORD timeout;
- DWORD result;
- int retval;
LeaveCriticalSection (&lock->lock);
+ struct timeval currtime;
gettimeofday (&currtime, NULL);
/* Wait until another thread signals this event or until the
abstime passes. */
+ DWORD timeout;
if (currtime.tv_sec > abstime->tv_sec)
timeout = 0;
else
{
/* WaitForSingleObject
<https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject> */
- result = WaitForSingleObject (event, timeout);
+ DWORD result = WaitForSingleObject (event, timeout);
if (result == WAIT_FAILED)
abort ();
if (result != WAIT_TIMEOUT)
}
EnterCriticalSection (&lock->lock);
/* Remove ourselves from the waiting_writers. */
+ int retval;
if (glwthread_waitqueue_remove (&lock->waiting_writers, elt))
retval = ETIMEDOUT;
else
xasprintf (const char *format, ...)
{
va_list args;
- char *result;
-
va_start (args, format);
- result = xvasprintf (format, args);
+ char *result = xvasprintf (format, args);
va_end (args);
return result;
xconcatenated_filename (const char *directory, const char *filename,
const char *suffix)
{
- char *result;
-
- result = concatenated_filename (directory, filename, suffix);
+ char *result = concatenated_filename (directory, filename, suffix);
if (result == NULL)
xalloc_die ();
void *
xpalloc (void *pa, idx_t *pn, idx_t n_incr_min, ptrdiff_t n_max, idx_t s)
{
- idx_t n0 = *pn;
-
/* The approximate size to use for initial small allocation
requests. This is the largest "small" request for the GNU C
library malloc. */
enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
+ idx_t n0 = *pn;
+
/* If the array is tiny, grow it to about (but no greater than)
DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
Adjust the growth according to three constraints: N_INCR_MIN,
void *
xmmalloca (size_t n)
{
- void *p;
-
- p = mmalloca (n);
+ void *p = mmalloca (n);
if (p == NULL)
xalloc_die ();
return p;
xprintf (char const *restrict format, ...)
{
va_list args;
- off64_t retval;
va_start (args, format);
- retval = xvprintf (format, args);
+ off64_t retval = xvprintf (format, args);
va_end (args);
return retval;
xfprintf (FILE *restrict stream, char const *restrict format, ...)
{
va_list args;
- off64_t retval;
va_start (args, format);
- retval = xvfprintf (stream, format, args);
+ off64_t retval = xvfprintf (stream, format, args);
va_end (args);
return retval;
sb_xappendf (struct string_buffer *buffer, const char *formatstring, ...)
{
va_list args;
- int ret;
-
va_start (args, formatstring);
- ret = sb_xappendvf (buffer, formatstring, args);
+ int ret = sb_xappendvf (buffer, formatstring, args);
va_end (args);
return ret;
}
const char *formatstring, ...)
{
va_list args;
- int ret;
-
va_start (args, formatstring);
- ret = sbr_xprependvf (buffer, formatstring, args);
+ int ret = sbr_xprependvf (buffer, formatstring, args);
va_end (args);
return ret;
}
XSTRTOD (char const *str, char const **ptr, DOUBLE *result,
DOUBLE (*convert) (char const *, char **))
{
- DOUBLE val;
- char *terminator;
- bool ok = true;
-
errno = 0;
- val = convert (str, &terminator);
+ char *terminator;
+ DOUBLE val = convert (str, &terminator);
/* Having a non-zero terminator is an error only when PTR is NULL. */
+ bool ok = true;
if (terminator == str || (ptr == NULL && *terminator != '\0'))
ok = false;
else
char const *arg,
int exit_status)
{
- char const *hyphens = "--";
char const *msgid;
- char const *option;
- char option_buffer[2];
-
switch (err)
{
case LONGINT_OK: default:
break;
}
+ char const *hyphens = "--";
+ char option_buffer[2];
+ char const *option;
if (opt_idx < 0)
{
hyphens -= opt_idx;
if (**p != '\0')
{
- int xbase = 1024;
- int suffixes = 1;
- strtol_error overflow;
-
if (!strchr (valid_suffixes, **p))
{
*val = tmp;
return err | LONGINT_INVALID_SUFFIX_CHAR;
}
+ int xbase = 1024;
+ int suffixes = 1;
switch (**p)
{
case 'E': case 'G': case 'g': case 'k': case 'K': case 'M': case 'm':
}
}
+ strtol_error overflow;
switch (**p)
{
case 'b':
static char *
xstrcat (size_t argcount, va_list args)
{
- char *result;
- va_list ap;
- size_t totalsize;
- char *p;
-
/* Determine the total size. */
- totalsize = 0;
- va_copy (ap, args);
- for (size_t i = argcount; i > 0; i--)
- {
- const char *next = va_arg (ap, const char *);
- totalsize = xsum (totalsize, strlen (next));
- }
- va_end (ap);
+ size_t totalsize = 0;
+ {
+ va_list ap;
+ va_copy (ap, args);
+ for (size_t i = argcount; i > 0; i--)
+ {
+ const char *next = va_arg (ap, const char *);
+ totalsize = xsum (totalsize, strlen (next));
+ }
+ va_end (ap);
+ }
/* Test for overflow in the summing pass above or in (totalsize + 1)
below. */
xalloc_die ();
/* Allocate and fill the result string. */
- result = XNMALLOC (totalsize + 1, char);
- p = result;
- for (size_t i = argcount; i > 0; i--)
- {
- const char *next = va_arg (args, const char *);
- size_t len = strlen (next);
- memcpy (p, next, len);
- p += len;
- }
- *p = '\0';
+ char *result = XNMALLOC (totalsize + 1, char);
+ {
+ char *p = result;
+ for (size_t i = argcount; i > 0; i--)
+ {
+ const char *next = va_arg (args, const char *);
+ size_t len = strlen (next);
+ memcpy (p, next, len);
+ p += len;
+ }
+ *p = '\0';
+ }
return result;
}
char *
xvasprintf (const char *format, va_list args)
{
- char *result;
/* Recognize the special case format = "%s...%s". It is a frequently used
idiom for string concatenation and needs to be fast. We don't want to
}
}
+ char *result;
if (vaszprintf (&result, format, args) < 0)
{
if (errno == ENOMEM)
zprintf (const char *format, ...)
{
va_list args;
- off64_t ret;
-
va_start (args, format);
- ret = vfzprintf (stdout, format, args);
+ off64_t ret = vfzprintf (stdout, format, args);
va_end (args);
return ret;