aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJoakim Verona2011-08-27 19:45:48 +0200
committerJoakim Verona2011-08-27 19:45:48 +0200
commit9fb7b0cab34a48a4c7b66abb6b8edc4ee20467b4 (patch)
treee94476d49f15747fcb9409d773702e88201855a4 /src
parentc7489583c30031c0ecfae9d20b20c149ca1935e9 (diff)
parentb75258b32810f3690442bddef2e10eef126d2d25 (diff)
downloademacs-9fb7b0cab34a48a4c7b66abb6b8edc4ee20467b4.tar.gz
emacs-9fb7b0cab34a48a4c7b66abb6b8edc4ee20467b4.zip
upstream
Diffstat (limited to 'src')
-rw-r--r--src/ChangeLog463
-rw-r--r--src/alloc.c88
-rw-r--r--src/bidi.c129
-rw-r--r--src/buffer.c69
-rw-r--r--src/callproc.c8
-rw-r--r--src/category.c2
-rw-r--r--src/ccl.c41
-rw-r--r--src/character.c10
-rw-r--r--src/character.h22
-rw-r--r--src/charset.c89
-rw-r--r--src/charset.h4
-rw-r--r--src/cmds.c2
-rw-r--r--src/coding.c17
-rw-r--r--src/coding.h2
-rw-r--r--src/composite.c67
-rw-r--r--src/composite.h12
-rw-r--r--src/dispextern.h32
-rw-r--r--src/dispnew.c129
-rw-r--r--src/doc.c37
-rw-r--r--src/editfns.c10
-rw-r--r--src/emacs.c29
-rw-r--r--src/eval.c25
-rw-r--r--src/fileio.c6
-rw-r--r--src/fns.c18
-rw-r--r--src/frame.c38
-rw-r--r--src/frame.h4
-rw-r--r--src/fringe.c13
-rw-r--r--src/ftfont.c34
-rw-r--r--src/gtkutil.c41
-rw-r--r--src/gtkutil.h7
-rw-r--r--src/image.c250
-rw-r--r--src/indent.c25
-rw-r--r--src/keyboard.c101
-rw-r--r--src/keyboard.h2
-rw-r--r--src/keymap.c15
-rw-r--r--src/keymap.h2
-rw-r--r--src/lisp.h30
-rw-r--r--src/lread.c20
-rw-r--r--src/macros.c4
-rw-r--r--src/makefile.w32-in1
-rw-r--r--src/minibuf.c2
-rw-r--r--src/nsmenu.m2
-rw-r--r--src/nsterm.h4
-rw-r--r--src/nsterm.m19
-rw-r--r--src/process.c41
-rw-r--r--src/region-cache.c84
-rw-r--r--src/region-cache.h12
-rw-r--r--src/scroll.c34
-rw-r--r--src/search.c61
-rw-r--r--src/sysdep.c8
-rw-r--r--src/term.c79
-rw-r--r--src/termcap.c17
-rw-r--r--src/termhooks.h6
-rw-r--r--src/tparam.c26
-rw-r--r--src/window.c2
-rw-r--r--src/xdisp.c137
-rw-r--r--src/xfaces.c23
-rw-r--r--src/xfns.c39
-rw-r--r--src/xgselect.c7
-rw-r--r--src/xrdb.c16
-rw-r--r--src/xselect.c316
-rw-r--r--src/xsmfns.c4
-rw-r--r--src/xterm.c55
63 files changed, 1803 insertions, 1089 deletions
diff --git a/src/ChangeLog b/src/ChangeLog
index 431a515def5..7eb18593993 100644
--- a/src/ChangeLog
+++ b/src/ChangeLog
@@ -1,3 +1,466 @@
12011-08-27 Paul Eggert <eggert@cs.ucla.edu>
2
3 * ccl.c: Improve and simplify overflow checking (Bug#9196).
4 (ccl_driver): Do not generate an out-of-range pointer.
5 (Fccl_execute_on_string): Remove unnecessary check for
6 integer overflow, noted by Stefan Monnier in
7 <http://lists.gnu.org/archive/html/emacs-devel/2011-08/msg00979.html>.
8 Remove a FIXME that didn't need fixing.
9 Simplify the newly-introduced buffer reallocation code.
10
112011-08-27 Juanma Barranquero <lekktu@gmail.com>
12
13 * makefile.w32-in ($(BLD)/alloc.$(O)): Depend on lib/verify.h.
14
152011-08-26 Paul Eggert <eggert@cs.ucla.edu>
16
17 Integer and memory overflow issues (Bug#9196).
18
19 * doc.c (get_doc_string): Rework so that
20 get_doc_string_buffer_size is the actual buffer size, rather than
21 being 1 less than the actual buffer size; this makes xpalloc more
22 convenient.
23
24 * image.c (x_allocate_bitmap_record, cache_image):
25 * xselect.c (Fx_register_dnd_atom):
26 Simplify previous changes by using xpalloc.
27
28 * buffer.c (overlay_str_len): Now ptrdiff_t, not EMACS_INT,
29 since either will do and ptrdiff_t is convenient with xpalloc.
30
31 * charset.c (charset_table_size)
32 (struct charset_sort_data.priority): Now ptrdiff_t.
33 (charset_compare): Don't overflow if priorities differ greatly.
34 (Fsort_charsets): Don't assume list length fits in int.
35 Check for size-calculation overflow when allocating sort data.
36 (syms_of_charset): Allocate an initial charset table that is
37 just under 64 KiB, to avoid problems with glibc malloc and mmap.
38
39 * cmds.c (internal_self_insert): Check for size-calculation overflow.
40
41 * composite.h (struct composition.glyph_len): Now int, not unsigned.
42 The actual value is always <= INT_MAX, and leaving it unsigned made
43 overflow checking harder.
44
45 * dispextern.h (struct glyph_matrix.rows_allocated)
46 (struct face_cache.size): Now ptrdiff_t, for convenience in use
47 with xpalloc. The values are still always <= INT_MAX.
48
49 * indent.c (compute_motion): Adjust to region_cache_forward sig change.
50
51 * lisp.h (xnmalloc, xnrealloc, xpalloc): New decls.
52 (SAFE_NALLOCA): New macro.
53
54 * region-cache.c (struct boundary.pos, find_cache_boundary)
55 (move_cache_gap, insert_cache_boundary, delete_cache_boundaries)
56 (set_cache_region, invalidate_region_cache)
57 (revalidate_region_cache, know_region_cache, region_cache_forward)
58 (region_cache_backward, pp_cache):
59 Use ptrdiff_t, not EMACS_INT, since either will do. This is needed
60 so that ptrdiff_t * can be passed to xpalloc.
61 (struct region_cache): Similarly, for gap_start, gap_len, cache_len,
62 beg_unchanged, end_unchanged, buffer_beg, buffer_end members.
63 (pp_cache): Don't assume cache_len fits in int.
64 * region-cache.h: Adjust extern decls to match.
65
66 * search.c (scan_buffer, Freplace_match): Use ptrdiff_t, not
67 EMACS_INT, since either will do, for xpalloc.
68
69 * alloc.c: Include verify.h, and check that int fits in ptrdiff_t.
70 (xnmalloc, xnrealloc, xpalloc): New functions.
71
72 * bidi.c (bidi_shelve_header_size): New constant.
73 (bidi_cache_ensure_space, bidi_shelve_cache): Use it.
74 (bidi_cache_ensure_space): Avoid integer overflow when allocating.
75
76 * bidi.c (bidi_cache_shrink):
77 * buffer.c (overlays_at, overlays_in, record_overlay_string)
78 (overlay_strings):
79 Don't update size of array until after memory allocation succeeds,
80 because xmalloc/xrealloc may not return.
81 (struct sortstrlist.bytes): Now ptrdiff_t, as EMACS_INT doesn't help
82 now that we have proper integer overflow checking.
83 (record_overlay_string, overlay_strings): Catch overflows when
84 calculating size of overlay_str_buf.
85
86 * callproc.c (Fcall_process): Check for size overflow when
87 calculating size of args2.
88 (child_setup): Avoid overflow by using size_t rather than ptrdiff_t.
89 Normally we prefer signed values, but sticking with ptrdiff_t would
90 require adding more-complicated checks.
91
92 * ccl.c (Fccl_execute_on_string): Check for memory overflow.
93 Use ptrdiff_t rather than EMACS_INT where ptrdiff_t will do.
94 Redo buffer-overflow calculations to avoid integer overflow.
95 Add a FIXME comment where memory seems to be over-allocated.
96
97 * character.c (Fstring): Check for size-calculation overflow.
98
99 * coding.c (produce_chars): Redo buffer-overflow calculations to avoid
100 unnecessary integer overflow. Check for size overflow.
101 (encode_coding_object): Don't update size until xmalloc succeeds.
102
103 * composite.c (get_composition_id): Check for overflow in glyph
104 length calculations.
105
106 Integer and memory overflow fixes for display code.
107 * dispextern.h (struct glyph_pool.nglyphs): Now ptrdiff_t, not int.
108 * dispnew.c (adjust_glyph_matrix, realloc_glyph_pool)
109 (scrolling_window): Check for overflow in size calculations.
110 (line_draw_cost, realloc_glyph_pool, add_row_entry):
111 Don't assume glyph table len fits in int.
112 (struct row_entry.bucket, row_entry_pool_size, row_entry_idx)
113 (row_table_size): Now ptrdiff_t, not int.
114 (scrolling_window): Avoid overflow in size calculations.
115 Don't update size until allocation succeeds.
116 * fns.c (concat): Check for overflow in size calculations.
117 (next_almost_prime): Verify NEXT_ALMOST_PRIME_LIMIT.
118 * lisp.h (RANGED_INTEGERP, TYPE_RANGED_INTEGERP): New macros.
119 (NEXT_ALMOST_PRIME_LIMIT): New constant.
120
121 * doc.c (get_doc_string_buffer_size): Now ptrdiff_t, not int.
122 (get_doc_string): Check for size calculation overflow.
123 Don't update size until allocation succeeds.
124 (get_doc_string, Fsubstitute_command_keys): Use ptrdiff_t, not
125 EMACS_INT, where ptrdiff_t will do.
126 (Fsubstitute_command_keys): Check for string overflow.
127
128 * editfns.c (set_time_zone_rule): Don't assume environment length
129 fits in int.
130 (message_length): Now ptrdiff_t, not int.
131 (Fmessage_box): Don't update size until allocation succeeds.
132 Don't assume message length fits in int.
133 (Fformat): Use ptrdiff_t, not EMACS_INT, where ptrdiff_t will do.
134
135 * emacs.c (main): Do not reallocate argv, since there is a null at
136 the end that can be overwritten, and this way there's no need to
137 worry about size-calculation overflow.
138 (sort_args): Check for size-calculation overflow.
139
140 * eval.c (init_eval_once, grow_specpdl): Don't update size until
141 alloc succeeds.
142 (call_debugger, grow_specpdl): Redo calculations to avoid overflow.
143
144 * frame.c (set_menu_bar_lines, x_set_frame_parameters)
145 (x_set_scroll_bar_width, x_figure_window_size):
146 Check for integer overflow.
147 (x_set_alpha): Do not assume XINT fits in int.
148
149 * frame.h (struct frame): Use int, not EMACS_INT, where int works.
150 This is for the members text_lines, text_cols, total_lines, total_cols,
151 where the system imposes an 'int' limit.
152
153 * fringe.c (Fdefine_fringe_bitmap):
154 Don't update size until alloc works.
155
156 * ftfont.c (ftfont_get_open_type_spec, setup_otf_gstring)
157 (ftfont_shape_by_flt): Check for integer overflow in size calculations.
158
159 * gtkutil.c (get_utf8_string, xg_store_widget_in_map):
160 Check for size-calculation overflow.
161 (get_utf8_string): Use ptrdiff_t, not size_t, where either will
162 do, as we prefer signed integers.
163 (id_to_widget.max_size, id_to_widget.used)
164 (xg_store_widget_in_map, xg_remove_widget_from_map)
165 (xg_get_widget_from_map, xg_get_scroll_id_for_window)
166 (xg_remove_scroll_bar, xg_update_scrollbar_pos):
167 Use and return ptrdiff_t, not int.
168 (xg_gtk_scroll_destroy): Don't assume ptrdiff_t fits in int.
169 * gtkutil.h: Change prototypes to match the above.
170
171 * image.c (RANGED_INTEGERP, TYPE_RANGED_INTEGERP): Remove; these
172 are duplicate now that they've been promoted to lisp.h.
173 (x_allocate_bitmap_record, x_alloc_image_color)
174 (make_image_cache, cache_image, xpm_load):
175 Don't update size until alloc is done.
176 (xpm_load, lookup_rgb_color, lookup_pixel_color, x_to_xcolors)
177 (x_detect_edges):
178 Check for size calculation overflow.
179 (ct_colors_allocated_max): New constant.
180 (x_to_xcolors, x_detect_edges): Reorder multiplicands to avoid
181 overflow.
182
183 * keyboard.c (read_char, menu_bar_items, tool_bar_items)
184 (read_char_x_menu_prompt, read_char_minibuf_menu_width)
185 (read_char_minibuf_menu_prompt, follow_key, read_key_sequence):
186 Use ptrdiff_t, not int, to count maps.
187 (read_char_minibuf_menu_prompt): Check for overflow in size
188 calculations. Don't update size until allocation succeeds. Redo
189 calculations to avoid overflow.
190 * keyboard.h: Change prototypes to match the above.
191
192 * keymap.c (cmm_size, current_minor_maps): Use ptrdiff_t, not int,
193 to count maps.
194 (current_minor_maps): Check for size calculation overflow.
195 * keymap.h: Change prototypes to match the above.
196
197 * lread.c (read1, init_obarray): Don't update size until alloc done.
198
199 * macros.c (Fstart_kbd_macro): Don't update size until alloc done.
200 (store_kbd_macro_char): Reorder multiplicands to avoid overflow.
201
202 * nsterm.h (struct ns_color_table.size, struct ns_color_table.avail):
203 Now ptrdiff_t, not int.
204 * nsterm.m (ns_index_color): Use ptrdiff_t, not int, for table indexes.
205 (ns_draw_fringe_bitmap): Rewrite to avoid overflow.
206
207 * process.c (Fnetwork_interface_list): Check for overflow
208 in size calculation.
209
210 * region-cache.c (move_cache_gap): Check for size calculation overflow.
211
212 * scroll.c (do_line_insertion_deletion_costs): Check for size calc
213 overflow. Don't bother calling xmalloc when xrealloc will do.
214
215 * search.c (Freplace_match): Check for size calculation overflow.
216 (Fset_match_data): Don't assume list lengths fit in 'int'.
217
218 * sysdep.c (system_process_attributes): Use ptrdiff_t, not int,
219 for command line length. Do not attempt to address one before the
220 beginning of an array, as that's not portable.
221
222 * term.c (max_frame_lines): Remove; unused.
223 (encode_terminal_src_size, encode_terminal_dst_size): Now ptrdiff_t,
224 not int.
225 (encode_terminal_code, calculate_costs): Check for size
226 calculation overflow.
227 (encode_terminal_code): Use ptrdiff_t, not int, to record glyph
228 table lengths and related sizes. Don't update size until alloc
229 done. Redo calculations to avoid overflow.
230 (calculate_costs): Don't bother calling xmalloc when xrealloc will do.
231
232 * termcap.c (tgetent): Use ptrdiff_t, not int, to record results of
233 subtracting pointers.
234 (gobble_line): Check for overflow more carefully. Don't update size
235 until alloc done.
236
237 * tparam.c (tparam1): Use ptrdiff_t, not int, for sizes.
238 Don't update size until alloc done.
239 Redo size calculations to avoid overflow.
240 Check for size calculation overflow.
241 (main) [DEBUG]: Fix typo in invoking tparam1.
242
243 * xdisp.c (store_mode_line_noprop_char, x_consider_frame_title):
244 Use ptrdiff_t, not int, for sizes.
245 (store_mode_line_noprop_char): Don't update size until alloc done.
246
247 * xfaces.c (lface_id_to_name_size, Finternal_make_lisp_face):
248 Use ptrdiff_t, not int, for sizes.
249 (Finternal_make_lisp_face, cache_face):
250 Check for size calculation overflow.
251 (cache_face): Treat size calculation overflows as if they were
252 memory exhaustion (the usual treatment), rather than aborting.
253
254 * xfns.c (x_encode_text, x_set_name_internal)
255 (Fx_change_window_property): Use ptrdiff_t, not int, to count
256 sizes, since they can exceed INT_MAX in size. Check for size
257 calculation overflow.
258
259 * xgselect.c (gfds_size): Now ptrdiff_t, for convenience with xpalloc.
260 (xg_select): Check for size calculation overflow.
261 Don't update size until alloc done.
262
263 * xrdb.c (get_environ_db): Don't assume path length fits in int,
264 as sprintf is limited to int lengths.
265
266 * xselect.c (X_LONG_SIZE, X_SHRT_MAX, X_SHRT_MIN, X_LONG_MAX)
267 (X_LONG_MIN): New macros.
268 Use them to make the following changes clearer.
269 (MAX_SELECTION_QUANTUM): Make the other bounds on this value clearer.
270 This change doesn't affect the value now, but it may help remind
271 future maintainers not to raise the value too much later.
272 (SELECTION_QUANTUM): Remove, replacing with ...
273 (selection_quantum): ... new function, which avoids overflow.
274 All uses changed.
275 (struct selection_data.size): Now ptrdiff_t, not int, to avoid
276 assumption that selection length fits in 'int'.
277 (x_reply_selection_request, x_handle_selection_request)
278 (x_get_window_property, receive_incremental_selection)
279 (x_get_window_property_as_lisp_data, selection_data_to_lisp_data)
280 (lisp_data_to_selection_data, clean_local_selection_data):
281 Use ptrdiff_t, not int, to record length of selection.
282 (x_reply_selection_request, x_get_window_property)
283 (receive_incremental_selection, x_property_data_to_lisp):
284 Redo calculations to avoid overflow.
285 (x_reply_selection_request): When sending hint, ceiling it at
286 X_LONG_MAX rather than relying on wraparound overflow to send
287 something.
288 (x_get_window_property, receive_incremental_selection)
289 (lisp_data_to_selection_data, x_property_data_to_lisp):
290 Check for size-calculation overflow.
291 (x_get_window_property, receive_incremental_selection)
292 (lisp_data_to_selection_data, Fx_register_dnd_atom):
293 Don't store size until memory allocation succeeds.
294 (x_get_window_property): Plug memory leak on memory exhaustion.
295 Don't double-block input; malloc is safe here. Don't assume 2**34
296 - 4 fits in unsigned long. Add an xassert to check
297 XGetWindowProperty overflow. Be more careful about overflow
298 calculations, and distinguish size from memory overflow better.
299 (receive_incremental_selection): When tracing, don't assume
300 unsigned int is less than INT_MAX.
301 (x_selection_data_to_lisp_data): Remove unnecessary (and in theory
302 harmful) conversions of unsigned short to int.
303 (lisp_data_to_selection_data): Don't assume that integers
304 in the range -65535 through -1 fit in an X unsigned short.
305 Don't assume that ULONG_MAX == X_ULONG_MAX. Don't store into
306 result parameters unless successful. Rely on cons_to_unsigned
307 to report problems with elements; the old code wasn't right anyway.
308 (x_check_property_data): Check for int overflow; we cannot use
309 a wider type due to X limits.
310 (x_handle_dnd_message): Use unsigned int, to avoid int overflow.
311
312 * xsmfns.c (smc_save_yourself_CB): Check for size calc overflow.
313
314 * xterm.c (x_color_cells, x_send_scrollbar_event, handle_one_xevent)
315 (x_term_init): Check for size calculation overflow.
316 (x_color_cells): Don't store size until memory allocation succeeds.
317 (handle_one_xevent): Use ptrdiff_t, not int, for byte counts.
318 Don't assume alloca size is less than MAX_ALLOCA.
319 (x_term_init): Don't assume length fits in int (sprintf is limited
320 to int size).
321
322 Use ptrdiff_t for composition IDs.
323 * character.c (lisp_string_width):
324 * composite.c (composition_table_size, n_compositions)
325 (get_composition_id, composition_gstring_from_id):
326 * dispextern.h (struct glyph_string.cmp_id, struct composition_it.id):
327 * xdisp.c (BUILD_COMPOSITE_GLYPH_STRING):
328 * window.c (Frecenter):
329 Use ptrdiff_t, not int, for composition IDs.
330 * composite.c (get_composition_id): Check for integer overflow.
331 * composite.h: Adjust prototypes to match the above changes.
332
333 Use ptrdiff_t for hash table indexes.
334 * category.c (hash_get_category_set):
335 * ccl.c (ccl_driver):
336 * charset.h (struct charset.hash_index, CHECK_CHARSET_GET_ID):
337 * coding.c (coding_system_charset_list, detect_coding_system):
338 * coding.h (struct coding_system.id):
339 * composite.c (get_composition_id, gstring_lookup_cache):
340 * fns.c (hash_lookup, hash_put, Fgethash, Fputhash):
341 * image.c (xpm_get_color_table_h):
342 * lisp.h (hash_lookup, hash_put):
343 * minibuf.c (Ftest_completion):
344 Use ptrdiff_t for hash table indexes, not int (which is too
345 narrow, on 64-bit hosts) or EMACS_INT (which is too wide, on
346 32-bit --with-wide-int hosts).
347
348 * charset.c (Fdefine_charset_internal): Check for integer overflow.
349 Add a FIXME comment about memory leaks.
350 (syms_of_charset): Don't assume xmalloc returns.
351
352 Don't assume that stated character widths fit in int.
353 * character.c (Fchar_width, c_string_width, lisp_string_width):
354 * character.h (CHAR_WIDTH):
355 * indent.c (MULTIBYTE_BYTES_WIDTH):
356 Use sanitize_char_width to avoid undefined and/or bad behavior
357 with outlandish widths.
358 * character.h (sanitize_tab_width): Renamed from sanitize_width,
359 now that we have two such functions. All uses changed.
360 (sanitize_char_width): New inline function.
361
362 Don't assume that tab-width fits in int.
363 * character.h (sanitize_width): New inline function.
364 (SANE_TAB_WIDTH): New macro.
365 (ASCII_CHAR_WIDTH): Use it.
366 * indent.c (sane_tab_width): Remove. All uses replaced by
367 SANE_TAB_WIDTH (current_buffer).
368 * xdisp.c (init_iterator): Use SANE_TAB_WIDTH.
369
370 * fileio.c: Integer overflow issues with file modes.
371 (Fset_file_modes, auto_save_1): Don't assume EMACS_INT fits in int.
372
373 * charset.c (read_hex): New arg OVERFLOW. All uses changed.
374 Remove unreachable code.
375 (read_hex, load_charset_map_from_file): Check for integer overflow.
376
377 * xterm.c: don't go over XClientMessageEvent limit
378 (scroll_bar_windows_size): Now ptrdiff_t, as we prefer signed.
379 (x_send_scroll_bar_event): Likewise. Check that the size does not
380 exceed limits imposed by XClientMessageEvent, as well as the usual
381 ptrdiff_t and size_t limits.
382
383 * keyboard.c: Overflow, signedness and related fixes.
384 (make_lispy_movement): Use same integer type in forward decl
385 that is used in the definition.
386 (read_key_sequence, keyremap_step):
387 Change bufsize argument back to int, undoing my 2011-03-30 change.
388 We prefer signed types, and int is wide enough here.
389 (parse_tool_bar_item): Don't assume tool_bar_max_label_size is less
390 than TYPE_MAXIMUM (EMACS_INT) / 2. Don't let the label size grow
391 larger than STRING_BYTES_BOUND. Use ptrdiff_t for Emacs string
392 length, not size_t. Use ptrdiff_t for index, not int.
393 (keyremap_step, read_key_sequence): Redo bufsize check to avoid
394 possibility of integer overflow.
395
396 Overflow, signedness and related fixes for images.
397
398 * dispextern.h (struct it.stack[0].u.image.image_id)
399 (struct_it.image_id, struct image.id, struct image_cache.size)
400 (struct image_cache.used, struct image_cache.ref_count):
401 * gtkutil.c (update_frame_tool_bar):
402 * image.c (x_reference_bitmap, Fimage_size, Fimage_mask_p)
403 (Fimage_metadata, free_image_cache, clear_image_cache, lookup_image)
404 (cache_image, mark_image_cache, x_kill_gs_process, Flookup_image):
405 * nsmenu.m (update_frame_tool_bar):
406 * xdisp.c (calc_pixel_width_or_height):
407 * xfns.c (image_cache_refcount):
408 Image IDs are now ptrdiff_t, not int, to avoid arbitrary limits
409 on typical 64-bit hosts.
410
411 * image.c (RANGED_INTEGERP, TYPE_RANGED_INTEGERP): New macros.
412 (x_bitmap_pixmap, x_create_x_image_and_pixmap):
413 Omit unnecessary casts to int.
414 (parse_image_spec): Check that integers fall into 'int' range
415 when the callers expect that.
416 (image_ascent): Redo ascent calculation to avoid int overflow.
417 (clear_image_cache): Avoid overflow when sqrt (INT_MAX) < nimages.
418 (lookup_image): Remove unnecessary tests.
419 (xbm_image_p): Locals are now of int, not EMACS_INT,
420 since parse_image_check makes sure they fit into int.
421 (png_load, gif_load, svg_load_image):
422 Prefer int to unsigned where either will do.
423 (tiff_handler): New function, combining the cores of the
424 old tiff_error_handler and tiff_warning_handler. This
425 function is rewritten to use vsnprintf and thereby avoid
426 stack buffer overflows. It uses only the features of vsnprintf
427 that are common to both POSIX and native Microsoft.
428 (tiff_error_handler, tiff_warning_handler): Use it.
429 (tiff_load, gif_load, imagemagick_load_image):
430 Don't assume :index value fits in 'int'.
431 (gif_load): Omit unnecessary cast to double, and avoid double-rounding.
432 (imagemagick_load_image): Check that crop parameters fit into
433 the integer types that MagickCropImage accepts. Don't assume
434 Vimagemagick_render_type has a nonnegative value. Don't assume
435 size_t fits in 'long'.
436 (gs_load): Use printmax_t to print the widest integers possible.
437 Check for integer overflow when computing image height and width.
438
4392011-08-26 Eli Zaretskii <eliz@gnu.org>
440
441 * xdisp.c (redisplay_window): Don't force window start if point
442 will be invisible in the resulting window. (Bug#9324)
443
4442011-08-25 Eli Zaretskii <eliz@gnu.org>
445
446 * xdisp.c (compute_display_string_pos): Return 2 in DISP_PROP when
447 the display spec is of the form `(space ...)'.
448 (handle_display_spec): Return the value returned by
449 handle_single_display_spec, not just 1 or zero.
450 (handle_single_display_spec): If the display spec is of the form
451 `(space ...)', and specifies display in the text area, return 2
452 rather than 1.
453 (try_cursor_movement): Check for the need to scroll more
454 accurately, and prefer exact match for point under bidi. Don't
455 advance `row' beyond the last row of the window.
456
457 * dispextern.h (struct bidi_it): Rename the disp_prop_p member
458 into disp_prop; all users changed.
459
460 * bidi.c (bidi_fetch_char): If compute_display_string_pos returns
461 DISP_PROP = 2, substitute the u+2029 PARAGRAPH SEPARATOR character
462 for the text covered by the display property.
463
12011-08-25 Chong Yidong <cyd@stupidchicken.com> 4642011-08-25 Chong Yidong <cyd@stupidchicken.com>
2 465
3 * buffer.c (Fbury_buffer_internal): Rename from Funrecord_buffer. 466 * buffer.c (Fbury_buffer_internal): Rename from Funrecord_buffer.
diff --git a/src/alloc.c b/src/alloc.c
index 36ad645612d..2d256800466 100644
--- a/src/alloc.c
+++ b/src/alloc.c
@@ -46,6 +46,7 @@ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
46#include "syssignal.h" 46#include "syssignal.h"
47#include "termhooks.h" /* For struct terminal. */ 47#include "termhooks.h" /* For struct terminal. */
48#include <setjmp.h> 48#include <setjmp.h>
49#include <verify.h>
49 50
50/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd 51/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
51 memory. Can do this only if using gmalloc.c. */ 52 memory. Can do this only if using gmalloc.c. */
@@ -733,6 +734,93 @@ xfree (POINTER_TYPE *block)
733} 734}
734 735
735 736
737/* Other parts of Emacs pass large int values to allocator functions
738 expecting ptrdiff_t. This is portable in practice, but check it to
739 be safe. */
740verify (INT_MAX <= PTRDIFF_MAX);
741
742
743/* Allocate an array of NITEMS items, each of size ITEM_SIZE.
744 Signal an error on memory exhaustion, and block interrupt input. */
745
746void *
747xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
748{
749 xassert (0 <= nitems && 0 < item_size);
750 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
751 memory_full (SIZE_MAX);
752 return xmalloc (nitems * item_size);
753}
754
755
756/* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
757 Signal an error on memory exhaustion, and block interrupt input. */
758
759void *
760xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
761{
762 xassert (0 <= nitems && 0 < item_size);
763 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
764 memory_full (SIZE_MAX);
765 return xrealloc (pa, nitems * item_size);
766}
767
768
769/* Grow PA, which points to an array of *NITEMS items, and return the
770 location of the reallocated array, updating *NITEMS to reflect its
771 new size. The new array will contain at least NITEMS_INCR_MIN more
772 items, but will not contain more than NITEMS_MAX items total.
773 ITEM_SIZE is the size of each item, in bytes.
774
775 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
776 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
777 infinity.
778
779 If PA is null, then allocate a new array instead of reallocating
780 the old one. Thus, to grow an array A without saving its old
781 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
782 &NITEMS, ...).
783
784 Block interrupt input as needed. If memory exhaustion occurs, set
785 *NITEMS to zero if PA is null, and signal an error (i.e., do not
786 return). */
787
788void *
789xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
790 ptrdiff_t nitems_max, ptrdiff_t item_size)
791{
792 /* The approximate size to use for initial small allocation
793 requests. This is the largest "small" request for the GNU C
794 library malloc. */
795 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
796
797 /* If the array is tiny, grow it to about (but no greater than)
798 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
799 ptrdiff_t n = *nitems;
800 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
801 ptrdiff_t half_again = n >> 1;
802 ptrdiff_t incr_estimate = max (tiny_max, half_again);
803
804 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
805 NITEMS_MAX, and what the C language can represent safely. */
806 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
807 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
808 ? nitems_max : C_language_max);
809 ptrdiff_t nitems_incr_max = n_max - n;
810 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
811
812 xassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
813 if (! pa)
814 *nitems = 0;
815 if (nitems_incr_max < incr)
816 memory_full (SIZE_MAX);
817 n += incr;
818 pa = xrealloc (pa, n * item_size);
819 *nitems = n;
820 return pa;
821}
822
823
736/* Like strdup, but uses xmalloc. */ 824/* Like strdup, but uses xmalloc. */
737 825
738char * 826char *
diff --git a/src/bidi.c b/src/bidi.c
index 425a0be9578..bb29647ea88 100644
--- a/src/bidi.c
+++ b/src/bidi.c
@@ -316,6 +316,21 @@ static ptrdiff_t bidi_cache_last_idx; /* slot of last cache hit */
316static ptrdiff_t bidi_cache_start = 0; /* start of cache for this 316static ptrdiff_t bidi_cache_start = 0; /* start of cache for this
317 "stack" level */ 317 "stack" level */
318 318
319/* 5-slot stack for saving the start of the previous level of the
320 cache. xdisp.c maintains a 5-slot stack for its iterator state,
321 and we need the same size of our stack. */
322static ptrdiff_t bidi_cache_start_stack[IT_STACK_SIZE];
323static int bidi_cache_sp;
324
325/* Size of header used by bidi_shelve_cache. */
326enum
327 {
328 bidi_shelve_header_size =
329 (sizeof (bidi_cache_idx) + sizeof (bidi_cache_start_stack)
330 + sizeof (bidi_cache_sp) + sizeof (bidi_cache_start)
331 + sizeof (bidi_cache_last_idx))
332 };
333
319/* Reset the cache state to the empty state. We only reset the part 334/* Reset the cache state to the empty state. We only reset the part
320 of the cache relevant to iteration of the current object. Previous 335 of the cache relevant to iteration of the current object. Previous
321 objects, which are pushed on the display iterator's stack, are left 336 objects, which are pushed on the display iterator's stack, are left
@@ -338,9 +353,9 @@ bidi_cache_shrink (void)
338{ 353{
339 if (bidi_cache_size > BIDI_CACHE_CHUNK) 354 if (bidi_cache_size > BIDI_CACHE_CHUNK)
340 { 355 {
341 bidi_cache_size = BIDI_CACHE_CHUNK;
342 bidi_cache = 356 bidi_cache =
343 (struct bidi_it *) xrealloc (bidi_cache, bidi_cache_size * elsz); 357 (struct bidi_it *) xrealloc (bidi_cache, BIDI_CACHE_CHUNK * elsz);
358 bidi_cache_size = BIDI_CACHE_CHUNK;
344 } 359 }
345 bidi_cache_reset (); 360 bidi_cache_reset ();
346} 361}
@@ -473,21 +488,19 @@ bidi_cache_ensure_space (ptrdiff_t idx)
473 /* Enlarge the cache as needed. */ 488 /* Enlarge the cache as needed. */
474 if (idx >= bidi_cache_size) 489 if (idx >= bidi_cache_size)
475 { 490 {
476 ptrdiff_t new_size;
477
478 /* The bidi cache cannot be larger than the largest Lisp string 491 /* The bidi cache cannot be larger than the largest Lisp string
479 or buffer. */ 492 or buffer. */
480 ptrdiff_t string_or_buffer_bound = 493 ptrdiff_t string_or_buffer_bound =
481 max (BUF_BYTES_MAX, STRING_BYTES_BOUND); 494 max (BUF_BYTES_MAX, STRING_BYTES_BOUND);
482 495
483 /* Also, it cannot be larger than what C can represent. */ 496 /* Also, it cannot be larger than what C can represent. */
484 ptrdiff_t c_bound = min (PTRDIFF_MAX, SIZE_MAX) / elsz; 497 ptrdiff_t c_bound =
498 (min (PTRDIFF_MAX, SIZE_MAX) - bidi_shelve_header_size) / elsz;
485 499
486 if (min (string_or_buffer_bound, c_bound) <= idx) 500 bidi_cache =
487 memory_full (SIZE_MAX); 501 xpalloc (bidi_cache, &bidi_cache_size,
488 new_size = idx - idx % BIDI_CACHE_CHUNK + BIDI_CACHE_CHUNK; 502 max (BIDI_CACHE_CHUNK, idx - bidi_cache_size + 1),
489 bidi_cache = (struct bidi_it *) xrealloc (bidi_cache, new_size * elsz); 503 min (string_or_buffer_bound, c_bound), elsz);
490 bidi_cache_size = new_size;
491 } 504 }
492} 505}
493 506
@@ -540,7 +553,7 @@ bidi_cache_iterator_state (struct bidi_it *bidi_it, int resolved)
540 bidi_cache[idx].next_for_ws = bidi_it->next_for_ws; 553 bidi_cache[idx].next_for_ws = bidi_it->next_for_ws;
541 bidi_cache[idx].ignore_bn_limit = bidi_it->ignore_bn_limit; 554 bidi_cache[idx].ignore_bn_limit = bidi_it->ignore_bn_limit;
542 bidi_cache[idx].disp_pos = bidi_it->disp_pos; 555 bidi_cache[idx].disp_pos = bidi_it->disp_pos;
543 bidi_cache[idx].disp_prop_p = bidi_it->disp_prop_p; 556 bidi_cache[idx].disp_prop = bidi_it->disp_prop;
544 } 557 }
545 558
546 bidi_cache_last_idx = idx; 559 bidi_cache_last_idx = idx;
@@ -580,11 +593,6 @@ bidi_peek_at_next_level (struct bidi_it *bidi_it)
580/*********************************************************************** 593/***********************************************************************
581 Pushing and popping the bidi iterator state 594 Pushing and popping the bidi iterator state
582 ***********************************************************************/ 595 ***********************************************************************/
583/* 5-slot stack for saving the start of the previous level of the
584 cache. xdisp.c maintains a 5-slot stack for its iterator state,
585 and we need the same size of our stack. */
586static ptrdiff_t bidi_cache_start_stack[IT_STACK_SIZE];
587static int bidi_cache_sp;
588 596
589/* Push the bidi iterator state in preparation for reordering a 597/* Push the bidi iterator state in preparation for reordering a
590 different object, e.g. display string found at certain buffer 598 different object, e.g. display string found at certain buffer
@@ -639,21 +647,16 @@ void *
639bidi_shelve_cache (void) 647bidi_shelve_cache (void)
640{ 648{
641 unsigned char *databuf; 649 unsigned char *databuf;
650 ptrdiff_t alloc;
642 651
643 /* Empty cache. */ 652 /* Empty cache. */
644 if (bidi_cache_idx == 0) 653 if (bidi_cache_idx == 0)
645 return NULL; 654 return NULL;
646 655
647 databuf = xmalloc (sizeof (bidi_cache_idx) 656 alloc = (bidi_shelve_header_size
648 + bidi_cache_idx * sizeof (struct bidi_it) 657 + bidi_cache_idx * sizeof (struct bidi_it));
649 + sizeof (bidi_cache_start_stack) 658 databuf = xmalloc (alloc);
650 + sizeof (bidi_cache_sp) + sizeof (bidi_cache_start) 659 bidi_cache_total_alloc += alloc;
651 + sizeof (bidi_cache_last_idx));
652 bidi_cache_total_alloc +=
653 sizeof (bidi_cache_idx) + bidi_cache_idx * sizeof (struct bidi_it)
654 + sizeof (bidi_cache_start_stack)
655 + sizeof (bidi_cache_sp) + sizeof (bidi_cache_start)
656 + sizeof (bidi_cache_last_idx);
657 660
658 memcpy (databuf, &bidi_cache_idx, sizeof (bidi_cache_idx)); 661 memcpy (databuf, &bidi_cache_idx, sizeof (bidi_cache_idx));
659 memcpy (databuf + sizeof (bidi_cache_idx), 662 memcpy (databuf + sizeof (bidi_cache_idx),
@@ -706,9 +709,7 @@ bidi_unshelve_cache (void *databuf, int just_free)
706 709
707 memcpy (&idx, p, sizeof (bidi_cache_idx)); 710 memcpy (&idx, p, sizeof (bidi_cache_idx));
708 bidi_cache_total_alloc -= 711 bidi_cache_total_alloc -=
709 sizeof (bidi_cache_idx) + idx * sizeof (struct bidi_it) 712 bidi_shelve_header_size + idx * sizeof (struct bidi_it);
710 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
711 + sizeof (bidi_cache_start) + sizeof (bidi_cache_last_idx);
712 } 713 }
713 else 714 else
714 { 715 {
@@ -737,9 +738,7 @@ bidi_unshelve_cache (void *databuf, int just_free)
737 + sizeof (bidi_cache_start), 738 + sizeof (bidi_cache_start),
738 sizeof (bidi_cache_last_idx)); 739 sizeof (bidi_cache_last_idx));
739 bidi_cache_total_alloc -= 740 bidi_cache_total_alloc -=
740 sizeof (bidi_cache_idx) + bidi_cache_idx * sizeof (struct bidi_it) 741 bidi_shelve_header_size + bidi_cache_idx * sizeof (struct bidi_it);
741 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
742 + sizeof (bidi_cache_start) + sizeof (bidi_cache_last_idx);
743 } 742 }
744 743
745 xfree (p); 744 xfree (p);
@@ -828,7 +827,7 @@ bidi_init_it (EMACS_INT charpos, EMACS_INT bytepos, int frame_window_p,
828 bidi_it->prev_for_neutral.orig_type = UNKNOWN_BT; 827 bidi_it->prev_for_neutral.orig_type = UNKNOWN_BT;
829 bidi_it->sor = L2R; /* FIXME: should it be user-selectable? */ 828 bidi_it->sor = L2R; /* FIXME: should it be user-selectable? */
830 bidi_it->disp_pos = -1; /* invalid/unknown */ 829 bidi_it->disp_pos = -1; /* invalid/unknown */
831 bidi_it->disp_prop_p = 0; 830 bidi_it->disp_prop = 0;
832 /* We can only shrink the cache if we are at the bottom level of its 831 /* We can only shrink the cache if we are at the bottom level of its
833 "stack". */ 832 "stack". */
834 if (bidi_cache_start == 0) 833 if (bidi_cache_start == 0)
@@ -908,19 +907,21 @@ bidi_char_at_pos (EMACS_INT bytepos, const unsigned char *s, int unibyte)
908 907
909/* Fetch and return the character at BYTEPOS/CHARPOS. If that 908/* Fetch and return the character at BYTEPOS/CHARPOS. If that
910 character is covered by a display string, treat the entire run of 909 character is covered by a display string, treat the entire run of
911 covered characters as a single character u+FFFC, and return their 910 covered characters as a single character, either u+2029 or u+FFFC,
912 combined length in CH_LEN and NCHARS. DISP_POS specifies the 911 and return their combined length in CH_LEN and NCHARS. DISP_POS
913 character position of the next display string, or -1 if not yet 912 specifies the character position of the next display string, or -1
914 computed. DISP_PROP_P non-zero means that there's really a display 913 if not yet computed. When the next character is at or beyond that
915 string at DISP_POS, as opposed to when we searched till DISP_POS
916 without findingone. When the next character is at or beyond that
917 position, the function updates DISP_POS with the position of the 914 position, the function updates DISP_POS with the position of the
918 next display string. STRING->s is the C string to iterate, or NULL 915 next display string. DISP_PROP non-zero means that there's really
919 if iterating over a buffer or a Lisp string; in the latter case, 916 a display string at DISP_POS, as opposed to when we searched till
920 STRING->lstring is the Lisp string. */ 917 DISP_POS without finding one. If DISP_PROP is 2, it means the
918 display spec is of the form `(space ...)', which is replaced with
919 u+2029 to handle it as a paragraph separator. STRING->s is the C
920 string to iterate, or NULL if iterating over a buffer or a Lisp
921 string; in the latter case, STRING->lstring is the Lisp string. */
921static inline int 922static inline int
922bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos, 923bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
923 int *disp_prop_p, struct bidi_string_data *string, 924 int *disp_prop, struct bidi_string_data *string,
924 int frame_window_p, EMACS_INT *ch_len, EMACS_INT *nchars) 925 int frame_window_p, EMACS_INT *ch_len, EMACS_INT *nchars)
925{ 926{
926 int ch; 927 int ch;
@@ -934,7 +935,7 @@ bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
934 { 935 {
935 SET_TEXT_POS (pos, charpos, bytepos); 936 SET_TEXT_POS (pos, charpos, bytepos);
936 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p, 937 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p,
937 disp_prop_p); 938 disp_prop);
938 } 939 }
939 940
940 /* Fetch the character at BYTEPOS. */ 941 /* Fetch the character at BYTEPOS. */
@@ -944,9 +945,9 @@ bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
944 *ch_len = 1; 945 *ch_len = 1;
945 *nchars = 1; 946 *nchars = 1;
946 *disp_pos = endpos; 947 *disp_pos = endpos;
947 *disp_prop_p = 0; 948 *disp_prop = 0;
948 } 949 }
949 else if (charpos >= *disp_pos && *disp_prop_p) 950 else if (charpos >= *disp_pos && *disp_prop)
950 { 951 {
951 EMACS_INT disp_end_pos; 952 EMACS_INT disp_end_pos;
952 953
@@ -954,9 +955,23 @@ bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
954 property. Hopefully, it will never be needed. */ 955 property. Hopefully, it will never be needed. */
955 if (charpos > *disp_pos) 956 if (charpos > *disp_pos)
956 abort (); 957 abort ();
957 /* Return the Unicode Object Replacement Character to represent 958 /* Text covered by `display' properties and overlays with
958 the entire run of characters covered by the display string. */ 959 display properties or display strings is handled as a single
959 ch = 0xFFFC; 960 character that represents the entire run of characters
961 covered by the display property. */
962 if (*disp_prop == 2)
963 {
964 /* `(space ...)' display specs are handled as paragraph
965 separators for the purposes of the reordering; see UAX#9
966 section 3 and clause HL1 in section 4.3 there. */
967 ch = 0x2029;
968 }
969 else
970 {
971 /* All other display specs are handled as the Unicode Object
972 Replacement Character. */
973 ch = 0xFFFC;
974 }
960 disp_end_pos = compute_display_string_end (*disp_pos, string); 975 disp_end_pos = compute_display_string_end (*disp_pos, string);
961 *nchars = disp_end_pos - *disp_pos; 976 *nchars = disp_end_pos - *disp_pos;
962 if (*nchars <= 0) 977 if (*nchars <= 0)
@@ -1014,11 +1029,11 @@ bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
1014 /* If we just entered a run of characters covered by a display 1029 /* If we just entered a run of characters covered by a display
1015 string, compute the position of the next display string. */ 1030 string, compute the position of the next display string. */
1016 if (charpos + *nchars <= endpos && charpos + *nchars > *disp_pos 1031 if (charpos + *nchars <= endpos && charpos + *nchars > *disp_pos
1017 && *disp_prop_p) 1032 && *disp_prop)
1018 { 1033 {
1019 SET_TEXT_POS (pos, charpos + *nchars, bytepos + *ch_len); 1034 SET_TEXT_POS (pos, charpos + *nchars, bytepos + *ch_len);
1020 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p, 1035 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p,
1021 disp_prop_p); 1036 disp_prop);
1022 } 1037 }
1023 1038
1024 return ch; 1039 return ch;
@@ -1126,7 +1141,7 @@ bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
1126 int ch; 1141 int ch;
1127 EMACS_INT ch_len, nchars; 1142 EMACS_INT ch_len, nchars;
1128 EMACS_INT pos, disp_pos = -1; 1143 EMACS_INT pos, disp_pos = -1;
1129 int disp_prop_p = 0; 1144 int disp_prop = 0;
1130 bidi_type_t type; 1145 bidi_type_t type;
1131 const unsigned char *s; 1146 const unsigned char *s;
1132 1147
@@ -1174,7 +1189,7 @@ bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
1174 bytepos = pstartbyte; 1189 bytepos = pstartbyte;
1175 if (!string_p) 1190 if (!string_p)
1176 pos = BYTE_TO_CHAR (bytepos); 1191 pos = BYTE_TO_CHAR (bytepos);
1177 ch = bidi_fetch_char (bytepos, pos, &disp_pos, &disp_prop_p, 1192 ch = bidi_fetch_char (bytepos, pos, &disp_pos, &disp_prop,
1178 &bidi_it->string, 1193 &bidi_it->string,
1179 bidi_it->frame_window_p, &ch_len, &nchars); 1194 bidi_it->frame_window_p, &ch_len, &nchars);
1180 type = bidi_get_type (ch, NEUTRAL_DIR); 1195 type = bidi_get_type (ch, NEUTRAL_DIR);
@@ -1199,7 +1214,7 @@ bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
1199 break; 1214 break;
1200 /* Fetch next character and advance to get past it. */ 1215 /* Fetch next character and advance to get past it. */
1201 ch = bidi_fetch_char (bytepos, pos, &disp_pos, 1216 ch = bidi_fetch_char (bytepos, pos, &disp_pos,
1202 &disp_prop_p, &bidi_it->string, 1217 &disp_prop, &bidi_it->string,
1203 bidi_it->frame_window_p, &ch_len, &nchars); 1218 bidi_it->frame_window_p, &ch_len, &nchars);
1204 pos += nchars; 1219 pos += nchars;
1205 bytepos += ch_len; 1220 bytepos += ch_len;
@@ -1336,7 +1351,7 @@ bidi_resolve_explicit_1 (struct bidi_it *bidi_it)
1336 bidi_it->ch_len = 1; 1351 bidi_it->ch_len = 1;
1337 bidi_it->nchars = 1; 1352 bidi_it->nchars = 1;
1338 bidi_it->disp_pos = (string_p ? bidi_it->string.schars : ZV); 1353 bidi_it->disp_pos = (string_p ? bidi_it->string.schars : ZV);
1339 bidi_it->disp_prop_p = 0; 1354 bidi_it->disp_prop = 0;
1340 } 1355 }
1341 else 1356 else
1342 { 1357 {
@@ -1344,7 +1359,7 @@ bidi_resolve_explicit_1 (struct bidi_it *bidi_it)
1344 display string, treat the entire run of covered characters as 1359 display string, treat the entire run of covered characters as
1345 a single character u+FFFC. */ 1360 a single character u+FFFC. */
1346 curchar = bidi_fetch_char (bidi_it->bytepos, bidi_it->charpos, 1361 curchar = bidi_fetch_char (bidi_it->bytepos, bidi_it->charpos,
1347 &bidi_it->disp_pos, &bidi_it->disp_prop_p, 1362 &bidi_it->disp_pos, &bidi_it->disp_prop,
1348 &bidi_it->string, bidi_it->frame_window_p, 1363 &bidi_it->string, bidi_it->frame_window_p,
1349 &bidi_it->ch_len, &bidi_it->nchars); 1364 &bidi_it->ch_len, &bidi_it->nchars);
1350 } 1365 }
@@ -2079,7 +2094,7 @@ bidi_level_of_next_char (struct bidi_it *bidi_it)
2079 struct bidi_string_data bs = bidi_it->string; 2094 struct bidi_string_data bs = bidi_it->string;
2080 bidi_type_t chtype; 2095 bidi_type_t chtype;
2081 int fwp = bidi_it->frame_window_p; 2096 int fwp = bidi_it->frame_window_p;
2082 int dpp = bidi_it->disp_prop_p; 2097 int dpp = bidi_it->disp_prop;
2083 2098
2084 if (bidi_it->nchars <= 0) 2099 if (bidi_it->nchars <= 0)
2085 abort (); 2100 abort ();
diff --git a/src/buffer.c b/src/buffer.c
index 832044ae6f4..37d2975c8c7 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -2557,13 +2557,10 @@ overlays_at (EMACS_INT pos, int extend, Lisp_Object **vec_ptr,
2557 Either make it bigger, or don't store any more in it. */ 2557 Either make it bigger, or don't store any more in it. */
2558 if (extend) 2558 if (extend)
2559 { 2559 {
2560 if ((OVERLAY_COUNT_MAX - 4) / 2 < len) 2560 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2561 memory_full (SIZE_MAX); 2561 sizeof *vec);
2562 /* Make it work with an initial len == 0. */
2563 len = len * 2 + 4;
2564 *len_ptr = len;
2565 vec = (Lisp_Object *) xrealloc (vec, len * sizeof (Lisp_Object));
2566 *vec_ptr = vec; 2562 *vec_ptr = vec;
2563 len = *len_ptr;
2567 } 2564 }
2568 else 2565 else
2569 inhibit_storing = 1; 2566 inhibit_storing = 1;
@@ -2600,13 +2597,10 @@ overlays_at (EMACS_INT pos, int extend, Lisp_Object **vec_ptr,
2600 { 2597 {
2601 if (extend) 2598 if (extend)
2602 { 2599 {
2603 if ((OVERLAY_COUNT_MAX - 4) / 2 < len) 2600 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2604 memory_full (SIZE_MAX); 2601 sizeof *vec);
2605 /* Make it work with an initial len == 0. */
2606 len = len * 2 + 4;
2607 *len_ptr = len;
2608 vec = (Lisp_Object *) xrealloc (vec, len * sizeof (Lisp_Object));
2609 *vec_ptr = vec; 2602 *vec_ptr = vec;
2603 len = *len_ptr;
2610 } 2604 }
2611 else 2605 else
2612 inhibit_storing = 1; 2606 inhibit_storing = 1;
@@ -2697,13 +2691,10 @@ overlays_in (EMACS_INT beg, EMACS_INT end, int extend,
2697 Either make it bigger, or don't store any more in it. */ 2691 Either make it bigger, or don't store any more in it. */
2698 if (extend) 2692 if (extend)
2699 { 2693 {
2700 if ((OVERLAY_COUNT_MAX - 4) / 2 < len) 2694 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2701 memory_full (SIZE_MAX); 2695 sizeof *vec);
2702 /* Make it work with an initial len == 0. */
2703 len = len * 2 + 4;
2704 *len_ptr = len;
2705 vec = (Lisp_Object *) xrealloc (vec, len * sizeof (Lisp_Object));
2706 *vec_ptr = vec; 2696 *vec_ptr = vec;
2697 len = *len_ptr;
2707 } 2698 }
2708 else 2699 else
2709 inhibit_storing = 1; 2700 inhibit_storing = 1;
@@ -2745,13 +2736,10 @@ overlays_in (EMACS_INT beg, EMACS_INT end, int extend,
2745 { 2736 {
2746 if (extend) 2737 if (extend)
2747 { 2738 {
2748 if ((OVERLAY_COUNT_MAX - 4) / 2 < len) 2739 vec = xpalloc (vec, len_ptr, 1, OVERLAY_COUNT_MAX,
2749 memory_full (SIZE_MAX); 2740 sizeof *vec);
2750 /* Make it work with an initial len == 0. */
2751 len = len * 2 + 4;
2752 *len_ptr = len;
2753 vec = (Lisp_Object *) xrealloc (vec, len * sizeof (Lisp_Object));
2754 *vec_ptr = vec; 2741 *vec_ptr = vec;
2742 len = *len_ptr;
2755 } 2743 }
2756 else 2744 else
2757 inhibit_storing = 1; 2745 inhibit_storing = 1;
@@ -2933,7 +2921,7 @@ struct sortstrlist
2933 struct sortstr *buf; /* An array that expands as needed; never freed. */ 2921 struct sortstr *buf; /* An array that expands as needed; never freed. */
2934 ptrdiff_t size; /* Allocated length of that array. */ 2922 ptrdiff_t size; /* Allocated length of that array. */
2935 ptrdiff_t used; /* How much of the array is currently in use. */ 2923 ptrdiff_t used; /* How much of the array is currently in use. */
2936 EMACS_INT bytes; /* Total length of the strings in buf. */ 2924 ptrdiff_t bytes; /* Total length of the strings in buf. */
2937}; 2925};
2938 2926
2939/* Buffers for storing information about the overlays touching a given 2927/* Buffers for storing information about the overlays touching a given
@@ -2944,7 +2932,7 @@ static struct sortstrlist overlay_heads, overlay_tails;
2944static unsigned char *overlay_str_buf; 2932static unsigned char *overlay_str_buf;
2945 2933
2946/* Allocated length of overlay_str_buf. */ 2934/* Allocated length of overlay_str_buf. */
2947static EMACS_INT overlay_str_len; 2935static ptrdiff_t overlay_str_len;
2948 2936
2949/* A comparison function suitable for passing to qsort. */ 2937/* A comparison function suitable for passing to qsort. */
2950static int 2938static int
@@ -2966,17 +2954,7 @@ record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
2966 EMACS_INT nbytes; 2954 EMACS_INT nbytes;
2967 2955
2968 if (ssl->used == ssl->size) 2956 if (ssl->used == ssl->size)
2969 { 2957 ssl->buf = xpalloc (ssl->buf, &ssl->size, 5, -1, sizeof *ssl->buf);
2970 if (min (PTRDIFF_MAX, SIZE_MAX) / (sizeof (struct sortstr) * 2)
2971 < ssl->size)
2972 memory_full (SIZE_MAX);
2973 else if (0 < ssl->size)
2974 ssl->size *= 2;
2975 else
2976 ssl->size = 5;
2977 ssl->buf = ((struct sortstr *)
2978 xrealloc (ssl->buf, ssl->size * sizeof (struct sortstr)));
2979 }
2980 ssl->buf[ssl->used].string = str; 2958 ssl->buf[ssl->used].string = str;
2981 ssl->buf[ssl->used].string2 = str2; 2959 ssl->buf[ssl->used].string2 = str2;
2982 ssl->buf[ssl->used].size = size; 2960 ssl->buf[ssl->used].size = size;
@@ -2991,6 +2969,8 @@ record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
2991 else 2969 else
2992 nbytes = SBYTES (str); 2970 nbytes = SBYTES (str);
2993 2971
2972 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
2973 memory_full (SIZE_MAX);
2994 ssl->bytes += nbytes; 2974 ssl->bytes += nbytes;
2995 2975
2996 if (STRINGP (str2)) 2976 if (STRINGP (str2))
@@ -3003,6 +2983,8 @@ record_overlay_string (struct sortstrlist *ssl, Lisp_Object str,
3003 else 2983 else
3004 nbytes = SBYTES (str2); 2984 nbytes = SBYTES (str2);
3005 2985
2986 if (INT_ADD_OVERFLOW (ssl->bytes, nbytes))
2987 memory_full (SIZE_MAX);
3006 ssl->bytes += nbytes; 2988 ssl->bytes += nbytes;
3007 } 2989 }
3008} 2990}
@@ -3096,14 +3078,15 @@ overlay_strings (EMACS_INT pos, struct window *w, unsigned char **pstr)
3096 Lisp_Object tem; 3078 Lisp_Object tem;
3097 EMACS_INT i; 3079 EMACS_INT i;
3098 unsigned char *p; 3080 unsigned char *p;
3099 EMACS_INT total = overlay_heads.bytes + overlay_tails.bytes; 3081 ptrdiff_t total;
3100 3082
3083 if (INT_ADD_OVERFLOW (overlay_heads.bytes, overlay_tails.bytes))
3084 memory_full (SIZE_MAX);
3085 total = overlay_heads.bytes + overlay_tails.bytes;
3101 if (total > overlay_str_len) 3086 if (total > overlay_str_len)
3102 { 3087 overlay_str_buf = xpalloc (overlay_str_buf, &overlay_str_len,
3103 overlay_str_len = total; 3088 total - overlay_str_len, -1, 1);
3104 overlay_str_buf = (unsigned char *)xrealloc (overlay_str_buf, 3089
3105 total);
3106 }
3107 p = overlay_str_buf; 3090 p = overlay_str_buf;
3108 for (i = overlay_tails.used; --i >= 0;) 3091 for (i = overlay_tails.used; --i >= 0;)
3109 { 3092 {
diff --git a/src/callproc.c b/src/callproc.c
index 3a91be3d8da..1bdb57a27d0 100644
--- a/src/callproc.c
+++ b/src/callproc.c
@@ -252,7 +252,7 @@ usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
252 val = Qraw_text; 252 val = Qraw_text;
253 else 253 else
254 { 254 {
255 SAFE_ALLOCA (args2, Lisp_Object *, (nargs + 1) * sizeof *args2); 255 SAFE_NALLOCA (args2, 1, nargs + 1);
256 args2[0] = Qcall_process; 256 args2[0] = Qcall_process;
257 for (i = 0; i < nargs; i++) args2[i + 1] = args[i]; 257 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
258 coding_systems = Ffind_operation_coding_system (nargs + 1, args2); 258 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
@@ -726,7 +726,7 @@ usage: (call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS) */)
726 { 726 {
727 ptrdiff_t i; 727 ptrdiff_t i;
728 728
729 SAFE_ALLOCA (args2, Lisp_Object *, (nargs + 1) * sizeof *args2); 729 SAFE_NALLOCA (args2, 1, nargs + 1);
730 args2[0] = Qcall_process; 730 args2[0] = Qcall_process;
731 for (i = 0; i < nargs; i++) args2[i + 1] = args[i]; 731 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
732 coding_systems 732 coding_systems
@@ -1024,7 +1024,7 @@ usage: (call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &r
1024 else 1024 else
1025 { 1025 {
1026 USE_SAFE_ALLOCA; 1026 USE_SAFE_ALLOCA;
1027 SAFE_ALLOCA (args2, Lisp_Object *, (nargs + 1) * sizeof *args2); 1027 SAFE_NALLOCA (args2, 1, nargs + 1);
1028 args2[0] = Qcall_process_region; 1028 args2[0] = Qcall_process_region;
1029 for (i = 0; i < nargs; i++) args2[i + 1] = args[i]; 1029 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1030 coding_systems = Ffind_operation_coding_system (nargs + 1, args2); 1030 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
@@ -1153,7 +1153,7 @@ child_setup (int in, int out, int err, register char **new_argv, int set_pgrp, L
1153 cleaned up in the usual way. */ 1153 cleaned up in the usual way. */
1154 { 1154 {
1155 register char *temp; 1155 register char *temp;
1156 register int i; 1156 size_t i; /* size_t, because ptrdiff_t might overflow here! */
1157 1157
1158 i = SBYTES (current_dir); 1158 i = SBYTES (current_dir);
1159#ifdef MSDOS 1159#ifdef MSDOS
diff --git a/src/category.c b/src/category.c
index 08eadb04730..a822bb654b0 100644
--- a/src/category.c
+++ b/src/category.c
@@ -67,7 +67,7 @@ static Lisp_Object
67hash_get_category_set (Lisp_Object table, Lisp_Object category_set) 67hash_get_category_set (Lisp_Object table, Lisp_Object category_set)
68{ 68{
69 struct Lisp_Hash_Table *h; 69 struct Lisp_Hash_Table *h;
70 EMACS_INT i; 70 ptrdiff_t i;
71 EMACS_UINT hash; 71 EMACS_UINT hash;
72 72
73 if (NILP (XCHAR_TABLE (table)->extras[1])) 73 if (NILP (XCHAR_TABLE (table)->extras[1]))
diff --git a/src/ccl.c b/src/ccl.c
index 9cfcbfe8703..b28a284f70a 100644
--- a/src/ccl.c
+++ b/src/ccl.c
@@ -1303,7 +1303,7 @@ ccl_driver (struct ccl_program *ccl, int *source, int *destination, int src_size
1303 1303
1304 case CCL_LookupIntConstTbl: 1304 case CCL_LookupIntConstTbl:
1305 { 1305 {
1306 EMACS_INT eop; 1306 ptrdiff_t eop;
1307 struct Lisp_Hash_Table *h; 1307 struct Lisp_Hash_Table *h;
1308 GET_CCL_RANGE (eop, ccl_prog, ic++, 0, 1308 GET_CCL_RANGE (eop, ccl_prog, ic++, 0,
1309 (VECTORP (Vtranslation_hash_table_vector) 1309 (VECTORP (Vtranslation_hash_table_vector)
@@ -1329,7 +1329,7 @@ ccl_driver (struct ccl_program *ccl, int *source, int *destination, int src_size
1329 1329
1330 case CCL_LookupCharConstTbl: 1330 case CCL_LookupCharConstTbl:
1331 { 1331 {
1332 EMACS_INT eop; 1332 ptrdiff_t eop;
1333 struct Lisp_Hash_Table *h; 1333 struct Lisp_Hash_Table *h;
1334 GET_CCL_RANGE (eop, ccl_prog, ic++, 0, 1334 GET_CCL_RANGE (eop, ccl_prog, ic++, 0,
1335 (VECTORP (Vtranslation_hash_table_vector) 1335 (VECTORP (Vtranslation_hash_table_vector)
@@ -1770,7 +1770,7 @@ ccl_driver (struct ccl_program *ccl, int *source, int *destination, int src_size
1770 } 1770 }
1771 1771
1772 msglen = strlen (msg); 1772 msglen = strlen (msg);
1773 if (dst + msglen <= dst_end) 1773 if (msglen <= dst_end - dst)
1774 { 1774 {
1775 for (i = 0; i < msglen; i++) 1775 for (i = 0; i < msglen; i++)
1776 *dst++ = msg[i]; 1776 *dst++ = msg[i];
@@ -2061,12 +2061,13 @@ usage: (ccl-execute-on-string CCL-PROGRAM STATUS STRING &optional CONTINUE UNIBY
2061 Lisp_Object val; 2061 Lisp_Object val;
2062 struct ccl_program ccl; 2062 struct ccl_program ccl;
2063 int i; 2063 int i;
2064 EMACS_INT outbufsize; 2064 ptrdiff_t outbufsize;
2065 unsigned char *outbuf, *outp; 2065 unsigned char *outbuf, *outp;
2066 EMACS_INT str_chars, str_bytes; 2066 ptrdiff_t str_chars, str_bytes;
2067#define CCL_EXECUTE_BUF_SIZE 1024 2067#define CCL_EXECUTE_BUF_SIZE 1024
2068 int source[CCL_EXECUTE_BUF_SIZE], destination[CCL_EXECUTE_BUF_SIZE]; 2068 int source[CCL_EXECUTE_BUF_SIZE], destination[CCL_EXECUTE_BUF_SIZE];
2069 EMACS_INT consumed_chars, consumed_bytes, produced_chars; 2069 ptrdiff_t consumed_chars, consumed_bytes, produced_chars;
2070 int buf_magnification;
2070 2071
2071 if (setup_ccl_program (&ccl, ccl_prog) < 0) 2072 if (setup_ccl_program (&ccl, ccl_prog) < 0)
2072 error ("Invalid CCL program"); 2073 error ("Invalid CCL program");
@@ -2093,6 +2094,10 @@ usage: (ccl-execute-on-string CCL-PROGRAM STATUS STRING &optional CONTINUE UNIBY
2093 ccl.ic = i; 2094 ccl.ic = i;
2094 } 2095 }
2095 2096
2097 buf_magnification = ccl.buf_magnification ? ccl.buf_magnification : 1;
2098
2099 if ((min (PTRDIFF_MAX, SIZE_MAX) - 256) / buf_magnification < str_bytes)
2100 memory_full (SIZE_MAX);
2096 outbufsize = (ccl.buf_magnification 2101 outbufsize = (ccl.buf_magnification
2097 ? str_bytes * ccl.buf_magnification + 256 2102 ? str_bytes * ccl.buf_magnification + 256
2098 : str_bytes + 256); 2103 : str_bytes + 256);
@@ -2122,31 +2127,25 @@ usage: (ccl-execute-on-string CCL-PROGRAM STATUS STRING &optional CONTINUE UNIBY
2122 src_size = j; 2127 src_size = j;
2123 while (1) 2128 while (1)
2124 { 2129 {
2130 int max_expansion = NILP (unibyte_p) ? MAX_MULTIBYTE_LENGTH : 1;
2131 ptrdiff_t offset, shortfall;
2125 ccl_driver (&ccl, src, destination, src_size, CCL_EXECUTE_BUF_SIZE, 2132 ccl_driver (&ccl, src, destination, src_size, CCL_EXECUTE_BUF_SIZE,
2126 Qnil); 2133 Qnil);
2127 produced_chars += ccl.produced; 2134 produced_chars += ccl.produced;
2135 offset = outp - outbuf;
2136 shortfall = ccl.produced * max_expansion - (outbufsize - offset);
2137 if (0 < shortfall)
2138 {
2139 outbuf = xpalloc (outbuf, &outbufsize, shortfall, -1, 1);
2140 outp = outbuf + offset;
2141 }
2128 if (NILP (unibyte_p)) 2142 if (NILP (unibyte_p))
2129 { 2143 {
2130 if (outp - outbuf + MAX_MULTIBYTE_LENGTH * ccl.produced
2131 > outbufsize)
2132 {
2133 EMACS_INT offset = outp - outbuf;
2134 outbufsize += MAX_MULTIBYTE_LENGTH * ccl.produced;
2135 outbuf = (unsigned char *) xrealloc (outbuf, outbufsize);
2136 outp = outbuf + offset;
2137 }
2138 for (j = 0; j < ccl.produced; j++) 2144 for (j = 0; j < ccl.produced; j++)
2139 CHAR_STRING_ADVANCE (destination[j], outp); 2145 CHAR_STRING_ADVANCE (destination[j], outp);
2140 } 2146 }
2141 else 2147 else
2142 { 2148 {
2143 if (outp - outbuf + ccl.produced > outbufsize)
2144 {
2145 EMACS_INT offset = outp - outbuf;
2146 outbufsize += ccl.produced;
2147 outbuf = (unsigned char *) xrealloc (outbuf, outbufsize);
2148 outp = outbuf + offset;
2149 }
2150 for (j = 0; j < ccl.produced; j++) 2149 for (j = 0; j < ccl.produced; j++)
2151 *outp++ = destination[j]; 2150 *outp++ = destination[j];
2152 } 2151 }
diff --git a/src/character.c b/src/character.c
index 8e9b3e3775e..fb9b8a9b93e 100644
--- a/src/character.c
+++ b/src/character.c
@@ -326,7 +326,7 @@ usage: (char-width CHAR) */)
326 disp = dp ? DISP_CHAR_VECTOR (dp, c) : Qnil; 326 disp = dp ? DISP_CHAR_VECTOR (dp, c) : Qnil;
327 327
328 if (VECTORP (disp)) 328 if (VECTORP (disp))
329 width = ASIZE (disp); 329 width = sanitize_char_width (ASIZE (disp));
330 else 330 else
331 width = CHAR_WIDTH (c); 331 width = CHAR_WIDTH (c);
332 332
@@ -358,7 +358,7 @@ c_string_width (const unsigned char *str, EMACS_INT len, int precision,
358 { 358 {
359 val = DISP_CHAR_VECTOR (dp, c); 359 val = DISP_CHAR_VECTOR (dp, c);
360 if (VECTORP (val)) 360 if (VECTORP (val))
361 thiswidth = ASIZE (val); 361 thiswidth = sanitize_char_width (ASIZE (val));
362 else 362 else
363 thiswidth = CHAR_WIDTH (c); 363 thiswidth = CHAR_WIDTH (c);
364 } 364 }
@@ -423,7 +423,7 @@ lisp_string_width (Lisp_Object string, EMACS_INT precision,
423 { 423 {
424 EMACS_INT chars, bytes, thiswidth; 424 EMACS_INT chars, bytes, thiswidth;
425 Lisp_Object val; 425 Lisp_Object val;
426 int cmp_id; 426 ptrdiff_t cmp_id;
427 EMACS_INT ignore, end; 427 EMACS_INT ignore, end;
428 428
429 if (find_composition (i, -1, &ignore, &end, &val, string) 429 if (find_composition (i, -1, &ignore, &end, &val, string)
@@ -451,7 +451,7 @@ lisp_string_width (Lisp_Object string, EMACS_INT precision,
451 { 451 {
452 val = DISP_CHAR_VECTOR (dp, c); 452 val = DISP_CHAR_VECTOR (dp, c);
453 if (VECTORP (val)) 453 if (VECTORP (val))
454 thiswidth = ASIZE (val); 454 thiswidth = sanitize_char_width (ASIZE (val));
455 else 455 else
456 thiswidth = CHAR_WIDTH (c); 456 thiswidth = CHAR_WIDTH (c);
457 } 457 }
@@ -902,7 +902,7 @@ usage: (string &rest CHARACTERS) */)
902 Lisp_Object str; 902 Lisp_Object str;
903 USE_SAFE_ALLOCA; 903 USE_SAFE_ALLOCA;
904 904
905 SAFE_ALLOCA (buf, unsigned char *, MAX_MULTIBYTE_LENGTH * n); 905 SAFE_NALLOCA (buf, MAX_MULTIBYTE_LENGTH, n);
906 p = buf; 906 p = buf;
907 907
908 for (i = 0; i < n; i++) 908 for (i = 0; i < n; i++)
diff --git a/src/character.h b/src/character.h
index 063b5147dc9..09bcf17ab96 100644
--- a/src/character.h
+++ b/src/character.h
@@ -556,6 +556,16 @@ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
556 } while (0) 556 } while (0)
557 557
558 558
559/* Return a non-outlandish value for the tab width. */
560
561#define SANE_TAB_WIDTH(buf) \
562 sanitize_tab_width (XFASTINT (BVAR (buf, tab_width)))
563static inline int
564sanitize_tab_width (EMACS_INT width)
565{
566 return 0 < width && width <= 1000 ? width : 8;
567}
568
559/* Return the width of ASCII character C. The width is measured by 569/* Return the width of ASCII character C. The width is measured by
560 how many columns C will occupy on the screen when displayed in the 570 how many columns C will occupy on the screen when displayed in the
561 current buffer. */ 571 current buffer. */
@@ -563,12 +573,20 @@ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
563#define ASCII_CHAR_WIDTH(c) \ 573#define ASCII_CHAR_WIDTH(c) \
564 (c < 0x20 \ 574 (c < 0x20 \
565 ? (c == '\t' \ 575 ? (c == '\t' \
566 ? XFASTINT (BVAR (current_buffer, tab_width)) \ 576 ? SANE_TAB_WIDTH (current_buffer) \
567 : (c == '\n' ? 0 : (NILP (BVAR (current_buffer, ctl_arrow)) ? 4 : 2))) \ 577 : (c == '\n' ? 0 : (NILP (BVAR (current_buffer, ctl_arrow)) ? 4 : 2))) \
568 : (c < 0x7f \ 578 : (c < 0x7f \
569 ? 1 \ 579 ? 1 \
570 : ((NILP (BVAR (current_buffer, ctl_arrow)) ? 4 : 2)))) 580 : ((NILP (BVAR (current_buffer, ctl_arrow)) ? 4 : 2))))
571 581
582/* Return a non-outlandish value for a character width. */
583
584static inline int
585sanitize_char_width (EMACS_INT width)
586{
587 return 0 <= width && width <= 1000 ? width : 1000;
588}
589
572/* Return the width of character C. The width is measured by how many 590/* Return the width of character C. The width is measured by how many
573 columns C will occupy on the screen when displayed in the current 591 columns C will occupy on the screen when displayed in the current
574 buffer. */ 592 buffer. */
@@ -576,7 +594,7 @@ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
576#define CHAR_WIDTH(c) \ 594#define CHAR_WIDTH(c) \
577 (ASCII_CHAR_P (c) \ 595 (ASCII_CHAR_P (c) \
578 ? ASCII_CHAR_WIDTH (c) \ 596 ? ASCII_CHAR_WIDTH (c) \
579 : XINT (CHAR_TABLE_REF (Vchar_width_table, c))) 597 : sanitize_char_width (XINT (CHAR_TABLE_REF (Vchar_width_table, c))))
580 598
581/* If C is a variation selector, return the index numnber of the 599/* If C is a variation selector, return the index numnber of the
582 variation selector (1..256). Otherwise, return 0. */ 600 variation selector (1..256). Otherwise, return 0. */
diff --git a/src/charset.c b/src/charset.c
index 55234aa76aa..6967b9df611 100644
--- a/src/charset.c
+++ b/src/charset.c
@@ -61,7 +61,7 @@ Lisp_Object Vcharset_hash_table;
61/* Table of struct charset. */ 61/* Table of struct charset. */
62struct charset *charset_table; 62struct charset *charset_table;
63 63
64static int charset_table_size; 64static ptrdiff_t charset_table_size;
65static int charset_table_used; 65static int charset_table_used;
66 66
67Lisp_Object Qcharsetp; 67Lisp_Object Qcharsetp;
@@ -419,7 +419,7 @@ load_charset_map (struct charset *charset, struct charset_map_entries *entries,
419 paying attention to comment character '#'. */ 419 paying attention to comment character '#'. */
420 420
421static inline unsigned 421static inline unsigned
422read_hex (FILE *fp, int *eof) 422read_hex (FILE *fp, int *eof, int *overflow)
423{ 423{
424 int c; 424 int c;
425 unsigned n; 425 unsigned n;
@@ -441,15 +441,16 @@ read_hex (FILE *fp, int *eof)
441 *eof = 1; 441 *eof = 1;
442 return 0; 442 return 0;
443 } 443 }
444 *eof = 0;
445 n = 0; 444 n = 0;
446 if (c == 'x') 445 while (isxdigit (c = getc (fp)))
447 while ((c = getc (fp)) != EOF && isxdigit (c)) 446 {
447 if (UINT_MAX >> 4 < n)
448 *overflow = 1;
448 n = ((n << 4) 449 n = ((n << 4)
449 | (c <= '9' ? c - '0' : c <= 'F' ? c - 'A' + 10 : c - 'a' + 10)); 450 | (c - ('0' <= c && c <= '9' ? '0'
450 else 451 : 'A' <= c && c <= 'F' ? 'A' - 10
451 while ((c = getc (fp)) != EOF && isdigit (c)) 452 : 'a' - 10)));
452 n = (n * 10) + c - '0'; 453 }
453 if (c != EOF) 454 if (c != EOF)
454 ungetc (c, fp); 455 ungetc (c, fp);
455 return n; 456 return n;
@@ -479,7 +480,6 @@ load_charset_map_from_file (struct charset *charset, Lisp_Object mapfile, int co
479 unsigned max_code = CHARSET_MAX_CODE (charset); 480 unsigned max_code = CHARSET_MAX_CODE (charset);
480 int fd; 481 int fd;
481 FILE *fp; 482 FILE *fp;
482 int eof;
483 Lisp_Object suffixes; 483 Lisp_Object suffixes;
484 struct charset_map_entries *head, *entries; 484 struct charset_map_entries *head, *entries;
485 int n_entries, count; 485 int n_entries, count;
@@ -504,22 +504,27 @@ load_charset_map_from_file (struct charset *charset, Lisp_Object mapfile, int co
504 memset (entries, 0, sizeof (struct charset_map_entries)); 504 memset (entries, 0, sizeof (struct charset_map_entries));
505 505
506 n_entries = 0; 506 n_entries = 0;
507 eof = 0;
508 while (1) 507 while (1)
509 { 508 {
510 unsigned from, to; 509 unsigned from, to, c;
511 int c;
512 int idx; 510 int idx;
511 int eof = 0, overflow = 0;
513 512
514 from = read_hex (fp, &eof); 513 from = read_hex (fp, &eof, &overflow);
515 if (eof) 514 if (eof)
516 break; 515 break;
517 if (getc (fp) == '-') 516 if (getc (fp) == '-')
518 to = read_hex (fp, &eof); 517 to = read_hex (fp, &eof, &overflow);
519 else 518 else
520 to = from; 519 to = from;
521 c = (int) read_hex (fp, &eof); 520 if (eof)
521 break;
522 c = read_hex (fp, &eof, &overflow);
523 if (eof)
524 break;
522 525
526 if (overflow)
527 continue;
523 if (from < min_code || to > max_code || from > to || c > MAX_CHAR) 528 if (from < min_code || to > max_code || from > to || c > MAX_CHAR)
524 continue; 529 continue;
525 530
@@ -1145,13 +1150,25 @@ usage: (define-charset-internal ...) */)
1145 hash_code); 1150 hash_code);
1146 if (charset_table_used == charset_table_size) 1151 if (charset_table_used == charset_table_size)
1147 { 1152 {
1148 struct charset *new_table 1153 /* Ensure that charset IDs fit into 'int' as well as into the
1149 = (struct charset *) xmalloc (sizeof (struct charset) 1154 restriction imposed by fixnums. Although the 'int' restriction
1150 * (charset_table_size + 16)); 1155 could be removed, too much other code would need altering; for
1151 memcpy (new_table, charset_table, 1156 example, the IDs are stuffed into struct
1152 sizeof (struct charset) * charset_table_size); 1157 coding_system.charbuf[i] entries, which are 'int'. */
1153 charset_table_size += 16; 1158 int old_size = charset_table_size;
1159 struct charset *new_table =
1160 xpalloc (0, &charset_table_size, 1,
1161 min (INT_MAX, MOST_POSITIVE_FIXNUM),
1162 sizeof *charset_table);
1163 memcpy (new_table, charset_table, old_size * sizeof *new_table);
1154 charset_table = new_table; 1164 charset_table = new_table;
1165 /* FIXME: Doesn't this leak memory? The old charset_table becomes
1166 unreachable. It could be that this is intentional, because the
1167 old charset table may be in a dumped emacs, and reallocating such
1168 a table may not work. If the memory leak is intentional, a
1169 comment should be added to explain this. If not, the old
1170 charset_table should be freed, by passing it as the 1st argument
1171 to xpalloc and removing the memcpy. */
1155 } 1172 }
1156 id = charset_table_used++; 1173 id = charset_table_used++;
1157 new_definition_p = 1; 1174 new_definition_p = 1;
@@ -2210,14 +2227,16 @@ struct charset_sort_data
2210{ 2227{
2211 Lisp_Object charset; 2228 Lisp_Object charset;
2212 int id; 2229 int id;
2213 int priority; 2230 ptrdiff_t priority;
2214}; 2231};
2215 2232
2216static int 2233static int
2217charset_compare (const void *d1, const void *d2) 2234charset_compare (const void *d1, const void *d2)
2218{ 2235{
2219 const struct charset_sort_data *data1 = d1, *data2 = d2; 2236 const struct charset_sort_data *data1 = d1, *data2 = d2;
2220 return (data1->priority - data2->priority); 2237 if (data1->priority != data2->priority)
2238 return data1->priority < data2->priority ? -1 : 1;
2239 return 0;
2221} 2240}
2222 2241
2223DEFUN ("sort-charsets", Fsort_charsets, Ssort_charsets, 1, 1, 0, 2242DEFUN ("sort-charsets", Fsort_charsets, Ssort_charsets, 1, 1, 0,
@@ -2227,7 +2246,8 @@ See also `charset-priority-list' and `set-charset-priority'. */)
2227 (Lisp_Object charsets) 2246 (Lisp_Object charsets)
2228{ 2247{
2229 Lisp_Object len = Flength (charsets); 2248 Lisp_Object len = Flength (charsets);
2230 int n = XFASTINT (len), i, j, done; 2249 ptrdiff_t n = XFASTINT (len), i, j;
2250 int done;
2231 Lisp_Object tail, elt, attrs; 2251 Lisp_Object tail, elt, attrs;
2232 struct charset_sort_data *sort_data; 2252 struct charset_sort_data *sort_data;
2233 int id, min_id = INT_MAX, max_id = INT_MIN; 2253 int id, min_id = INT_MAX, max_id = INT_MIN;
@@ -2235,7 +2255,7 @@ See also `charset-priority-list' and `set-charset-priority'. */)
2235 2255
2236 if (n == 0) 2256 if (n == 0)
2237 return Qnil; 2257 return Qnil;
2238 SAFE_ALLOCA (sort_data, struct charset_sort_data *, sizeof (*sort_data) * n); 2258 SAFE_NALLOCA (sort_data, 1, n);
2239 for (tail = charsets, i = 0; CONSP (tail); tail = XCDR (tail), i++) 2259 for (tail = charsets, i = 0; CONSP (tail); tail = XCDR (tail), i++)
2240 { 2260 {
2241 elt = XCAR (tail); 2261 elt = XCAR (tail);
@@ -2310,6 +2330,17 @@ init_charset_once (void)
2310void 2330void
2311syms_of_charset (void) 2331syms_of_charset (void)
2312{ 2332{
2333 /* Allocate an initial charset table that is just under 64 KiB in size.
2334 This should be large enough so that the charset table need not be
2335 reallocated during an initial bootstrap. Allocating anything larger than
2336 64 KiB in an initial run may not work, because glibc malloc might use
2337 mmap for larger allocations, and these don't work well across dumped
2338 systems. */
2339 enum {
2340 initial_malloc_max = (1 << 16) - 1,
2341 charset_table_size_init = initial_malloc_max / sizeof (struct charset)
2342 };
2343
2313 DEFSYM (Qcharsetp, "charsetp"); 2344 DEFSYM (Qcharsetp, "charsetp");
2314 2345
2315 DEFSYM (Qascii, "ascii"); 2346 DEFSYM (Qascii, "ascii");
@@ -2342,9 +2373,9 @@ syms_of_charset (void)
2342 Vcharset_hash_table = Fmake_hash_table (2, args); 2373 Vcharset_hash_table = Fmake_hash_table (2, args);
2343 } 2374 }
2344 2375
2345 charset_table_size = 128; 2376 charset_table = (struct charset *) xmalloc (sizeof (struct charset)
2346 charset_table = ((struct charset *) 2377 * charset_table_size_init);
2347 xmalloc (sizeof (struct charset) * charset_table_size)); 2378 charset_table_size = charset_table_size_init;
2348 charset_table_used = 0; 2379 charset_table_used = 0;
2349 2380
2350 defsubr (&Scharsetp); 2381 defsubr (&Scharsetp);
diff --git a/src/charset.h b/src/charset.h
index c2a52a38e7e..be02bc0feae 100644
--- a/src/charset.h
+++ b/src/charset.h
@@ -148,7 +148,7 @@ struct charset
148 int id; 148 int id;
149 149
150 /* Index to Vcharset_hash_table. */ 150 /* Index to Vcharset_hash_table. */
151 EMACS_INT hash_index; 151 ptrdiff_t hash_index;
152 152
153 /* Dimension of the charset: 1, 2, 3, or 4. */ 153 /* Dimension of the charset: 1, 2, 3, or 4. */
154 int dimension; 154 int dimension;
@@ -341,7 +341,7 @@ extern int emacs_mule_charset[256];
341 number of the charset. Otherwise, signal an error. */ 341 number of the charset. Otherwise, signal an error. */
342#define CHECK_CHARSET_GET_ID(x, id) \ 342#define CHECK_CHARSET_GET_ID(x, id) \
343 do { \ 343 do { \
344 int idx; \ 344 ptrdiff_t idx; \
345 \ 345 \
346 if (! SYMBOLP (x) || (idx = CHARSET_SYMBOL_HASH_INDEX (x)) < 0) \ 346 if (! SYMBOLP (x) || (idx = CHARSET_SYMBOL_HASH_INDEX (x)) < 0) \
347 wrong_type_argument (Qcharsetp, (x)); \ 347 wrong_type_argument (Qcharsetp, (x)); \
diff --git a/src/cmds.c b/src/cmds.c
index c079ad7168f..5a155ac77a5 100644
--- a/src/cmds.c
+++ b/src/cmds.c
@@ -472,7 +472,7 @@ internal_self_insert (int c, EMACS_INT n)
472 { 472 {
473 USE_SAFE_ALLOCA; 473 USE_SAFE_ALLOCA;
474 char *strn, *p; 474 char *strn, *p;
475 SAFE_ALLOCA (strn, char *, n * len); 475 SAFE_NALLOCA (strn, len, n);
476 for (p = strn; n > 0; n--, p += len) 476 for (p = strn; n > 0; n--, p += len)
477 memcpy (p, str, len); 477 memcpy (p, str, len);
478 insert_and_inherit (strn, p - strn); 478 insert_and_inherit (strn, p - strn);
diff --git a/src/coding.c b/src/coding.c
index 65c8a767c2b..5fd59d394d9 100644
--- a/src/coding.c
+++ b/src/coding.c
@@ -5838,7 +5838,7 @@ coding_charset_list (struct coding_system *coding)
5838Lisp_Object 5838Lisp_Object
5839coding_system_charset_list (Lisp_Object coding_system) 5839coding_system_charset_list (Lisp_Object coding_system)
5840{ 5840{
5841 int id; 5841 ptrdiff_t id;
5842 Lisp_Object attrs, charset_list; 5842 Lisp_Object attrs, charset_list;
5843 5843
5844 CHECK_CODING_SYSTEM_GET_ID (coding_system, id); 5844 CHECK_CODING_SYSTEM_GET_ID (coding_system, id);
@@ -6683,8 +6683,12 @@ produce_chars (struct coding_system *coding, Lisp_Object translation_table,
6683 break; 6683 break;
6684 } 6684 }
6685 6685
6686 if (dst + MAX_MULTIBYTE_LENGTH * to_nchars > dst_end) 6686 if ((dst_end - dst) / MAX_MULTIBYTE_LENGTH < to_nchars)
6687 { 6687 {
6688 if (((min (PTRDIFF_MAX, SIZE_MAX) - (buf_end - buf))
6689 / MAX_MULTIBYTE_LENGTH)
6690 < to_nchars)
6691 memory_full (SIZE_MAX);
6688 dst = alloc_destination (coding, 6692 dst = alloc_destination (coding,
6689 buf_end - buf 6693 buf_end - buf
6690 + MAX_MULTIBYTE_LENGTH * to_nchars, 6694 + MAX_MULTIBYTE_LENGTH * to_nchars,
@@ -7888,11 +7892,10 @@ encode_coding_object (struct coding_system *coding,
7888 } 7892 }
7889 else if (EQ (dst_object, Qt)) 7893 else if (EQ (dst_object, Qt))
7890 { 7894 {
7895 ptrdiff_t dst_bytes = max (1, coding->src_chars);
7891 coding->dst_object = Qnil; 7896 coding->dst_object = Qnil;
7892 coding->dst_bytes = coding->src_chars; 7897 coding->destination = (unsigned char *) xmalloc (dst_bytes);
7893 if (coding->dst_bytes == 0) 7898 coding->dst_bytes = dst_bytes;
7894 coding->dst_bytes = 1;
7895 coding->destination = (unsigned char *) xmalloc (coding->dst_bytes);
7896 coding->dst_multibyte = 0; 7899 coding->dst_multibyte = 0;
7897 } 7900 }
7898 else 7901 else
@@ -8076,7 +8079,7 @@ detect_coding_system (const unsigned char *src,
8076 Lisp_Object attrs, eol_type; 8079 Lisp_Object attrs, eol_type;
8077 Lisp_Object val = Qnil; 8080 Lisp_Object val = Qnil;
8078 struct coding_system coding; 8081 struct coding_system coding;
8079 int id; 8082 ptrdiff_t id;
8080 struct coding_detection_info detect_info; 8083 struct coding_detection_info detect_info;
8081 enum coding_category base_category; 8084 enum coding_category base_category;
8082 int null_byte_found = 0, eight_bit_found = 0; 8085 int null_byte_found = 0, eight_bit_found = 0;
diff --git a/src/coding.h b/src/coding.h
index 85e153dcc3a..fdf9b762e75 100644
--- a/src/coding.h
+++ b/src/coding.h
@@ -415,7 +415,7 @@ struct coding_system
415 setup_coding_system. At the early stage of building time, this 415 setup_coding_system. At the early stage of building time, this
416 value is -1 in the array coding_categories to indicate that no 416 value is -1 in the array coding_categories to indicate that no
417 coding-system of that category is yet defined. */ 417 coding-system of that category is yet defined. */
418 int id; 418 ptrdiff_t id;
419 419
420 /* Flag bits of the coding system. The meaning of each bit is common 420 /* Flag bits of the coding system. The meaning of each bit is common
421 to all types of coding systems. */ 421 to all types of coding systems. */
diff --git a/src/composite.c b/src/composite.c
index 3308a028042..2a3fbe29552 100644
--- a/src/composite.c
+++ b/src/composite.c
@@ -142,10 +142,10 @@ Lisp_Object Qcomposition;
142struct composition **composition_table; 142struct composition **composition_table;
143 143
144/* The current size of `composition_table'. */ 144/* The current size of `composition_table'. */
145static int composition_table_size; 145static ptrdiff_t composition_table_size;
146 146
147/* Number of compositions currently made. */ 147/* Number of compositions currently made. */
148int n_compositions; 148ptrdiff_t n_compositions;
149 149
150/* Hash table for compositions. The key is COMPONENTS-VEC of 150/* Hash table for compositions. The key is COMPONENTS-VEC of
151 `composition' property. The value is the corresponding 151 `composition' property. The value is the corresponding
@@ -172,19 +172,30 @@ Lisp_Object composition_temp;
172 172
173 If the composition is invalid, return -1. */ 173 If the composition is invalid, return -1. */
174 174
175int 175ptrdiff_t
176get_composition_id (EMACS_INT charpos, EMACS_INT bytepos, EMACS_INT nchars, 176get_composition_id (EMACS_INT charpos, EMACS_INT bytepos, EMACS_INT nchars,
177 Lisp_Object prop, Lisp_Object string) 177 Lisp_Object prop, Lisp_Object string)
178{ 178{
179 Lisp_Object id, length, components, key, *key_contents; 179 Lisp_Object id, length, components, key, *key_contents;
180 int glyph_len; 180 ptrdiff_t glyph_len;
181 struct Lisp_Hash_Table *hash_table = XHASH_TABLE (composition_hash_table); 181 struct Lisp_Hash_Table *hash_table = XHASH_TABLE (composition_hash_table);
182 EMACS_INT hash_index; 182 ptrdiff_t hash_index;
183 EMACS_UINT hash_code; 183 EMACS_UINT hash_code;
184 enum composition_method method;
184 struct composition *cmp; 185 struct composition *cmp;
185 EMACS_INT i; 186 EMACS_INT i;
186 int ch; 187 int ch;
187 188
189 /* Maximum length of a string of glyphs. XftGlyphExtents limits
190 this to INT_MAX, and Emacs limits it further. Divide INT_MAX - 1
191 by 2 because x_produce_glyphs computes glyph_len * 2 + 1. Divide
192 the size by MAX_MULTIBYTE_LENGTH because encode_terminal_code
193 multiplies glyph_len by MAX_MULTIBYTE_LENGTH. */
194 enum {
195 GLYPH_LEN_MAX = min ((INT_MAX - 1) / 2,
196 min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH)
197 };
198
188 /* PROP should be 199 /* PROP should be
189 Form-A: ((LENGTH . COMPONENTS) . MODIFICATION-FUNC) 200 Form-A: ((LENGTH . COMPONENTS) . MODIFICATION-FUNC)
190 or 201 or
@@ -258,21 +269,9 @@ get_composition_id (EMACS_INT charpos, EMACS_INT bytepos, EMACS_INT nchars,
258 /* This composition is a new one. We must register it. */ 269 /* This composition is a new one. We must register it. */
259 270
260 /* Check if we have sufficient memory to store this information. */ 271 /* Check if we have sufficient memory to store this information. */
261 if (composition_table_size == 0) 272 if (composition_table_size <= n_compositions)
262 { 273 composition_table = xpalloc (composition_table, &composition_table_size,
263 composition_table_size = 256; 274 1, -1, sizeof *composition_table);
264 composition_table
265 = (struct composition **) xmalloc (sizeof (composition_table[0])
266 * composition_table_size);
267 }
268 else if (composition_table_size <= n_compositions)
269 {
270 composition_table_size += 256;
271 composition_table
272 = (struct composition **) xrealloc (composition_table,
273 sizeof (composition_table[0])
274 * composition_table_size);
275 }
276 275
277 key_contents = XVECTOR (key)->contents; 276 key_contents = XVECTOR (key)->contents;
278 277
@@ -316,20 +315,26 @@ get_composition_id (EMACS_INT charpos, EMACS_INT bytepos, EMACS_INT nchars,
316 /* Register the composition in composition_hash_table. */ 315 /* Register the composition in composition_hash_table. */
317 hash_index = hash_put (hash_table, key, id, hash_code); 316 hash_index = hash_put (hash_table, key, id, hash_code);
318 317
318 method = (NILP (components)
319 ? COMPOSITION_RELATIVE
320 : ((INTEGERP (components) || STRINGP (components))
321 ? COMPOSITION_WITH_ALTCHARS
322 : COMPOSITION_WITH_RULE_ALTCHARS));
323
324 glyph_len = (method == COMPOSITION_WITH_RULE_ALTCHARS
325 ? (ASIZE (key) + 1) / 2
326 : ASIZE (key));
327
328 if (GLYPH_LEN_MAX < glyph_len)
329 memory_full (SIZE_MAX);
330
319 /* Register the composition in composition_table. */ 331 /* Register the composition in composition_table. */
320 cmp = (struct composition *) xmalloc (sizeof (struct composition)); 332 cmp = (struct composition *) xmalloc (sizeof (struct composition));
321 333
322 cmp->method = (NILP (components) 334 cmp->method = method;
323 ? COMPOSITION_RELATIVE
324 : ((INTEGERP (components) || STRINGP (components))
325 ? COMPOSITION_WITH_ALTCHARS
326 : COMPOSITION_WITH_RULE_ALTCHARS));
327 cmp->hash_index = hash_index; 335 cmp->hash_index = hash_index;
328 glyph_len = (cmp->method == COMPOSITION_WITH_RULE_ALTCHARS
329 ? (ASIZE (key) + 1) / 2
330 : ASIZE (key));
331 cmp->glyph_len = glyph_len; 336 cmp->glyph_len = glyph_len;
332 cmp->offsets = (short *) xmalloc (sizeof (short) * glyph_len * 2); 337 cmp->offsets = xnmalloc (glyph_len, 2 * sizeof *cmp->offsets);
333 cmp->font = NULL; 338 cmp->font = NULL;
334 339
335 if (cmp->method != COMPOSITION_WITH_RULE_ALTCHARS) 340 if (cmp->method != COMPOSITION_WITH_RULE_ALTCHARS)
@@ -656,7 +661,7 @@ static Lisp_Object
656gstring_lookup_cache (Lisp_Object header) 661gstring_lookup_cache (Lisp_Object header)
657{ 662{
658 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table); 663 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
659 EMACS_INT i = hash_lookup (h, header, NULL); 664 ptrdiff_t i = hash_lookup (h, header, NULL);
660 665
661 return (i >= 0 ? HASH_VALUE (h, i) : Qnil); 666 return (i >= 0 ? HASH_VALUE (h, i) : Qnil);
662} 667}
@@ -691,7 +696,7 @@ composition_gstring_put_cache (Lisp_Object gstring, EMACS_INT len)
691} 696}
692 697
693Lisp_Object 698Lisp_Object
694composition_gstring_from_id (int id) 699composition_gstring_from_id (ptrdiff_t id)
695{ 700{
696 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table); 701 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
697 702
diff --git a/src/composite.h b/src/composite.h
index 8cedfdbe352..c57e2a0e9b3 100644
--- a/src/composite.h
+++ b/src/composite.h
@@ -170,7 +170,7 @@ extern Lisp_Object composition_temp;
170 170
171struct composition { 171struct composition {
172 /* Number of glyphs of the composition components. */ 172 /* Number of glyphs of the composition components. */
173 unsigned glyph_len; 173 int glyph_len;
174 174
175 /* Width, ascent, and descent pixels of the composition. */ 175 /* Width, ascent, and descent pixels of the composition. */
176 short pixel_width, ascent, descent; 176 short pixel_width, ascent, descent;
@@ -193,7 +193,7 @@ struct composition {
193 void *font; 193 void *font;
194 194
195 /* Pointer to an array of x-offset and y-offset (by pixels) of 195 /* Pointer to an array of x-offset and y-offset (by pixels) of
196 glyphs. This points to a sufficient memory space (sizeof (int) * 196 glyphs. This points to a sufficient memory space (sizeof (short) *
197 glyph_len * 2) that is allocated when the composition is 197 glyph_len * 2) that is allocated when the composition is
198 registered in composition_table. X-offset and Y-offset of Nth 198 registered in composition_table. X-offset and Y-offset of Nth
199 glyph are (2N)th and (2N+1)th elements respectively. */ 199 glyph are (2N)th and (2N+1)th elements respectively. */
@@ -204,7 +204,7 @@ struct composition {
204 COMPOSITION-ID. */ 204 COMPOSITION-ID. */
205extern struct composition **composition_table; 205extern struct composition **composition_table;
206/* Number of the currently registered compositions. */ 206/* Number of the currently registered compositions. */
207extern int n_compositions; 207extern ptrdiff_t n_compositions;
208 208
209/* Mask bits for CHECK_MASK arg to update_compositions. 209/* Mask bits for CHECK_MASK arg to update_compositions.
210 For a change in the region FROM and TO, check compositions ... */ 210 For a change in the region FROM and TO, check compositions ... */
@@ -216,8 +216,8 @@ extern int n_compositions;
216 216
217extern Lisp_Object Qcomposition; 217extern Lisp_Object Qcomposition;
218extern Lisp_Object composition_hash_table; 218extern Lisp_Object composition_hash_table;
219extern int get_composition_id (EMACS_INT, EMACS_INT, EMACS_INT, 219extern ptrdiff_t get_composition_id (EMACS_INT, EMACS_INT, EMACS_INT,
220 Lisp_Object, Lisp_Object); 220 Lisp_Object, Lisp_Object);
221extern int find_composition (EMACS_INT, EMACS_INT, EMACS_INT *, EMACS_INT *, 221extern int find_composition (EMACS_INT, EMACS_INT, EMACS_INT *, EMACS_INT *,
222 Lisp_Object *, Lisp_Object); 222 Lisp_Object *, Lisp_Object);
223extern void update_compositions (EMACS_INT, EMACS_INT, int); 223extern void update_compositions (EMACS_INT, EMACS_INT, int);
@@ -299,7 +299,7 @@ struct face;
299struct font_metrics; 299struct font_metrics;
300 300
301extern Lisp_Object composition_gstring_put_cache (Lisp_Object, EMACS_INT); 301extern Lisp_Object composition_gstring_put_cache (Lisp_Object, EMACS_INT);
302extern Lisp_Object composition_gstring_from_id (int); 302extern Lisp_Object composition_gstring_from_id (ptrdiff_t);
303extern int composition_gstring_p (Lisp_Object); 303extern int composition_gstring_p (Lisp_Object);
304extern int composition_gstring_width (Lisp_Object, EMACS_INT, EMACS_INT, 304extern int composition_gstring_width (Lisp_Object, EMACS_INT, EMACS_INT,
305 struct font_metrics *); 305 struct font_metrics *);
diff --git a/src/dispextern.h b/src/dispextern.h
index 4d890fe6a37..641391b8c9c 100644
--- a/src/dispextern.h
+++ b/src/dispextern.h
@@ -582,7 +582,7 @@ struct glyph_pool
582 struct glyph *glyphs; 582 struct glyph *glyphs;
583 583
584 /* Allocated size of `glyphs'. */ 584 /* Allocated size of `glyphs'. */
585 int nglyphs; 585 ptrdiff_t nglyphs;
586 586
587 /* Number of rows and columns in a matrix. */ 587 /* Number of rows and columns in a matrix. */
588 int nrows, ncolumns; 588 int nrows, ncolumns;
@@ -632,7 +632,7 @@ struct glyph_matrix
632 struct glyph_row *rows; 632 struct glyph_row *rows;
633 633
634 /* Number of elements allocated for the vector rows above. */ 634 /* Number of elements allocated for the vector rows above. */
635 int rows_allocated; 635 ptrdiff_t rows_allocated;
636 636
637 /* The number of rows used by the window if all lines were displayed 637 /* The number of rows used by the window if all lines were displayed
638 with the smallest possible character height. */ 638 with the smallest possible character height. */
@@ -1247,7 +1247,7 @@ struct glyph_string
1247 struct composition *cmp; 1247 struct composition *cmp;
1248 1248
1249 /* If not negative, this string describes a compos. */ 1249 /* If not negative, this string describes a compos. */
1250 int cmp_id; 1250 ptrdiff_t cmp_id;
1251 1251
1252 /* Start and end glyph indices in a glyph-string. */ 1252 /* Start and end glyph indices in a glyph-string. */
1253 int cmp_from, cmp_to; 1253 int cmp_from, cmp_to;
@@ -1718,7 +1718,8 @@ struct face_cache
1718 struct face **faces_by_id; 1718 struct face **faces_by_id;
1719 1719
1720 /* The allocated size, and number of used slots of faces_by_id. */ 1720 /* The allocated size, and number of used slots of faces_by_id. */
1721 int size, used; 1721 ptrdiff_t size;
1722 int used;
1722 1723
1723 /* Flag indicating that attributes of the `menu' face have been 1724 /* Flag indicating that attributes of the `menu' face have been
1724 changed. */ 1725 changed. */
@@ -1870,8 +1871,9 @@ struct bidi_it {
1870 bidi_dir_t sor; /* direction of start-of-run in effect */ 1871 bidi_dir_t sor; /* direction of start-of-run in effect */
1871 int scan_dir; /* direction of text scan, 1: forw, -1: back */ 1872 int scan_dir; /* direction of text scan, 1: forw, -1: back */
1872 EMACS_INT disp_pos; /* position of display string after ch */ 1873 EMACS_INT disp_pos; /* position of display string after ch */
1873 int disp_prop_p; /* if non-zero, there really is a 1874 int disp_prop; /* if non-zero, there really is a
1874 `display' property/string at disp_pos */ 1875 `display' property/string at disp_pos;
1876 if 2, the property is a `space' spec */
1875 int stack_idx; /* index of current data on the stack */ 1877 int stack_idx; /* index of current data on the stack */
1876 /* Note: Everything from here on is not copied/saved when the bidi 1878 /* Note: Everything from here on is not copied/saved when the bidi
1877 iterator state is saved, pushed, or popped. So only put here 1879 iterator state is saved, pushed, or popped. So only put here
@@ -2075,7 +2077,7 @@ struct composition_it
2075 EMACS_INT stop_pos; 2077 EMACS_INT stop_pos;
2076 /* ID number of the composition or glyph-string. If negative, we 2078 /* ID number of the composition or glyph-string. If negative, we
2077 are not iterating over a composition now. */ 2079 are not iterating over a composition now. */
2078 int id; 2080 ptrdiff_t id;
2079 /* If non-negative, character that triggers the automatic 2081 /* If non-negative, character that triggers the automatic
2080 composition at `stop_pos', and this is an automatic composition. 2082 composition at `stop_pos', and this is an automatic composition.
2081 If negative, this is a static composition. This is set to -2 2083 If negative, this is a static composition. This is set to -2
@@ -2265,7 +2267,7 @@ struct it
2265 struct { 2267 struct {
2266 Lisp_Object object; 2268 Lisp_Object object;
2267 struct it_slice slice; 2269 struct it_slice slice;
2268 int image_id; 2270 ptrdiff_t image_id;
2269 } image; 2271 } image;
2270 /* method == GET_FROM_COMPOSITION */ 2272 /* method == GET_FROM_COMPOSITION */
2271 struct { 2273 struct {
@@ -2402,7 +2404,7 @@ struct it
2402 enum glyphless_display_method glyphless_method; 2404 enum glyphless_display_method glyphless_method;
2403 2405
2404 /* If what == IT_IMAGE, the id of the image to display. */ 2406 /* If what == IT_IMAGE, the id of the image to display. */
2405 int image_id; 2407 ptrdiff_t image_id;
2406 2408
2407#ifdef HAVE_XWIDGETS 2409#ifdef HAVE_XWIDGETS
2408 /* If what == IT_XWIDGET*/ 2410 /* If what == IT_XWIDGET*/
@@ -2856,7 +2858,7 @@ struct image
2856 EMACS_UINT hash; 2858 EMACS_UINT hash;
2857 2859
2858 /* Image id of this image. */ 2860 /* Image id of this image. */
2859 int id; 2861 ptrdiff_t id;
2860 2862
2861 /* Hash collision chain. */ 2863 /* Hash collision chain. */
2862 struct image *next, *prev; 2864 struct image *next, *prev;
@@ -2875,13 +2877,13 @@ struct image_cache
2875 struct image **images; 2877 struct image **images;
2876 2878
2877 /* Allocated size of `images'. */ 2879 /* Allocated size of `images'. */
2878 unsigned size; 2880 ptrdiff_t size;
2879 2881
2880 /* Number of images in the cache. */ 2882 /* Number of images in the cache. */
2881 unsigned used; 2883 ptrdiff_t used;
2882 2884
2883 /* Reference count (number of frames sharing this cache). */ 2885 /* Reference count (number of frames sharing this cache). */
2884 int refcount; 2886 ptrdiff_t refcount;
2885}; 2887};
2886 2888
2887 2889
@@ -3148,7 +3150,7 @@ void w32_reset_fringes (void);
3148extern int x_bitmap_height (struct frame *, ptrdiff_t); 3150extern int x_bitmap_height (struct frame *, ptrdiff_t);
3149extern int x_bitmap_width (struct frame *, ptrdiff_t); 3151extern int x_bitmap_width (struct frame *, ptrdiff_t);
3150extern int x_bitmap_pixmap (struct frame *, ptrdiff_t); 3152extern int x_bitmap_pixmap (struct frame *, ptrdiff_t);
3151extern void x_reference_bitmap (struct frame *, int); 3153extern void x_reference_bitmap (struct frame *, ptrdiff_t);
3152extern ptrdiff_t x_create_bitmap_from_data (struct frame *, char *, 3154extern ptrdiff_t x_create_bitmap_from_data (struct frame *, char *,
3153 unsigned int, unsigned int); 3155 unsigned int, unsigned int);
3154extern ptrdiff_t x_create_bitmap_from_file (struct frame *, Lisp_Object); 3156extern ptrdiff_t x_create_bitmap_from_file (struct frame *, Lisp_Object);
@@ -3169,7 +3171,7 @@ void clear_image_caches (Lisp_Object);
3169void mark_image_cache (struct image_cache *); 3171void mark_image_cache (struct image_cache *);
3170int valid_image_p (Lisp_Object); 3172int valid_image_p (Lisp_Object);
3171void prepare_image_for_display (struct frame *, struct image *); 3173void prepare_image_for_display (struct frame *, struct image *);
3172int lookup_image (struct frame *, Lisp_Object); 3174ptrdiff_t lookup_image (struct frame *, Lisp_Object);
3173 3175
3174unsigned long image_background (struct image *, struct frame *, 3176unsigned long image_background (struct image *, struct frame *,
3175 XImagePtr_or_DC ximg); 3177 XImagePtr_or_DC ximg);
diff --git a/src/dispnew.c b/src/dispnew.c
index a09421a9f15..751ff04f4d7 100644
--- a/src/dispnew.c
+++ b/src/dispnew.c
@@ -497,12 +497,12 @@ adjust_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int x, int y
497 /* Enlarge MATRIX->rows if necessary. New rows are cleared. */ 497 /* Enlarge MATRIX->rows if necessary. New rows are cleared. */
498 if (matrix->rows_allocated < dim.height) 498 if (matrix->rows_allocated < dim.height)
499 { 499 {
500 ptrdiff_t size = dim.height * sizeof (struct glyph_row); 500 int old_alloc = matrix->rows_allocated;
501 new_rows = dim.height - matrix->rows_allocated; 501 new_rows = dim.height - matrix->rows_allocated;
502 matrix->rows = (struct glyph_row *) xrealloc (matrix->rows, size); 502 matrix->rows = xpalloc (matrix->rows, &matrix->rows_allocated,
503 memset (matrix->rows + matrix->rows_allocated, 0, 503 new_rows, INT_MAX, sizeof *matrix->rows);
504 new_rows * sizeof *matrix->rows); 504 memset (matrix->rows + old_alloc, 0,
505 matrix->rows_allocated = dim.height; 505 (matrix->rows_allocated - old_alloc) * sizeof *matrix->rows);
506 } 506 }
507 else 507 else
508 new_rows = 0; 508 new_rows = 0;
@@ -574,9 +574,8 @@ adjust_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int x, int y
574 while (row < end) 574 while (row < end)
575 { 575 {
576 row->glyphs[LEFT_MARGIN_AREA] 576 row->glyphs[LEFT_MARGIN_AREA]
577 = (struct glyph *) xrealloc (row->glyphs[LEFT_MARGIN_AREA], 577 = xnrealloc (row->glyphs[LEFT_MARGIN_AREA],
578 (dim.width 578 dim.width, sizeof (struct glyph));
579 * sizeof (struct glyph)));
580 579
581 /* The mode line never has marginal areas. */ 580 /* The mode line never has marginal areas. */
582 if (row == matrix->rows + dim.height - 1 581 if (row == matrix->rows + dim.height - 1
@@ -1215,7 +1214,7 @@ line_draw_cost (struct glyph_matrix *matrix, int vpos)
1215 struct glyph *end = beg + row->used[TEXT_AREA]; 1214 struct glyph *end = beg + row->used[TEXT_AREA];
1216 int len; 1215 int len;
1217 Lisp_Object *glyph_table_base = GLYPH_TABLE_BASE; 1216 Lisp_Object *glyph_table_base = GLYPH_TABLE_BASE;
1218 int glyph_table_len = GLYPH_TABLE_LENGTH; 1217 ptrdiff_t glyph_table_len = GLYPH_TABLE_LENGTH;
1219 1218
1220 /* Ignore trailing and leading spaces if we can. */ 1219 /* Ignore trailing and leading spaces if we can. */
1221 if (!FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */ 1220 if (!FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */
@@ -1389,7 +1388,7 @@ free_glyph_pool (struct glyph_pool *pool)
1389static int 1388static int
1390realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim) 1389realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim)
1391{ 1390{
1392 int needed; 1391 ptrdiff_t needed;
1393 int changed_p; 1392 int changed_p;
1394 1393
1395 changed_p = (pool->glyphs == 0 1394 changed_p = (pool->glyphs == 0
@@ -1397,24 +1396,17 @@ realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim)
1397 || matrix_dim.width != pool->ncolumns); 1396 || matrix_dim.width != pool->ncolumns);
1398 1397
1399 /* Enlarge the glyph pool. */ 1398 /* Enlarge the glyph pool. */
1400 needed = matrix_dim.width * matrix_dim.height; 1399 needed = matrix_dim.width;
1400 if (INT_MULTIPLY_OVERFLOW (needed, matrix_dim.height))
1401 memory_full (SIZE_MAX);
1402 needed *= matrix_dim.height;
1401 if (needed > pool->nglyphs) 1403 if (needed > pool->nglyphs)
1402 { 1404 {
1403 ptrdiff_t size = needed * sizeof (struct glyph); 1405 ptrdiff_t old_nglyphs = pool->nglyphs;
1404 1406 pool->glyphs = xpalloc (pool->glyphs, &pool->nglyphs,
1405 if (pool->glyphs) 1407 needed - old_nglyphs, -1, sizeof *pool->glyphs);
1406 { 1408 memset (pool->glyphs + old_nglyphs, 0,
1407 pool->glyphs = (struct glyph *) xrealloc (pool->glyphs, size); 1409 (pool->nglyphs - old_nglyphs) * sizeof *pool->glyphs);
1408 memset (pool->glyphs + pool->nglyphs, 0,
1409 size - pool->nglyphs * sizeof (struct glyph));
1410 }
1411 else
1412 {
1413 pool->glyphs = (struct glyph *) xmalloc (size);
1414 memset (pool->glyphs, 0, size);
1415 }
1416
1417 pool->nglyphs = needed;
1418 } 1410 }
1419 1411
1420 /* Remember the number of rows and columns because (a) we use them 1412 /* Remember the number of rows and columns because (a) we use them
@@ -4167,7 +4159,7 @@ struct row_entry
4167 int new_line_number; 4159 int new_line_number;
4168 4160
4169 /* Bucket index of this row_entry in the hash table row_table. */ 4161 /* Bucket index of this row_entry in the hash table row_table. */
4170 int bucket; 4162 ptrdiff_t bucket;
4171 4163
4172 /* The row described by this entry. */ 4164 /* The row described by this entry. */
4173 struct glyph_row *row; 4165 struct glyph_row *row;
@@ -4181,29 +4173,29 @@ struct row_entry
4181 that we need a larger one. */ 4173 that we need a larger one. */
4182 4174
4183static struct row_entry *row_entry_pool; 4175static struct row_entry *row_entry_pool;
4184static int row_entry_pool_size; 4176static ptrdiff_t row_entry_pool_size;
4185 4177
4186/* Index of next free entry in row_entry_pool. */ 4178/* Index of next free entry in row_entry_pool. */
4187 4179
4188static int row_entry_idx; 4180static ptrdiff_t row_entry_idx;
4189 4181
4190/* The hash table used during scrolling, and the table's size. This 4182/* The hash table used during scrolling, and the table's size. This
4191 table is used to quickly identify equal rows in the desired and 4183 table is used to quickly identify equal rows in the desired and
4192 current matrix. */ 4184 current matrix. */
4193 4185
4194static struct row_entry **row_table; 4186static struct row_entry **row_table;
4195static int row_table_size; 4187static ptrdiff_t row_table_size;
4196 4188
4197/* Vectors of pointers to row_entry structures belonging to the 4189/* Vectors of pointers to row_entry structures belonging to the
4198 current and desired matrix, and the size of the vectors. */ 4190 current and desired matrix, and the size of the vectors. */
4199 4191
4200static struct row_entry **old_lines, **new_lines; 4192static struct row_entry **old_lines, **new_lines;
4201static int old_lines_size, new_lines_size; 4193static ptrdiff_t old_lines_size, new_lines_size;
4202 4194
4203/* A pool to allocate run structures from, and its size. */ 4195/* A pool to allocate run structures from, and its size. */
4204 4196
4205static struct run *run_pool; 4197static struct run *run_pool;
4206static int runs_size; 4198static ptrdiff_t runs_size;
4207 4199
4208/* A vector of runs of lines found during scrolling. */ 4200/* A vector of runs of lines found during scrolling. */
4209 4201
@@ -4215,7 +4207,7 @@ static inline struct row_entry *
4215add_row_entry (struct glyph_row *row) 4207add_row_entry (struct glyph_row *row)
4216{ 4208{
4217 struct row_entry *entry; 4209 struct row_entry *entry;
4218 int i = row->hash % row_table_size; 4210 ptrdiff_t i = row->hash % row_table_size;
4219 4211
4220 entry = row_table[i]; 4212 entry = row_table[i];
4221 while (entry && !row_equal_p (entry->row, row, 1)) 4213 while (entry && !row_equal_p (entry->row, row, 1))
@@ -4268,9 +4260,10 @@ scrolling_window (struct window *w, int header_line_p)
4268 struct glyph_matrix *desired_matrix = w->desired_matrix; 4260 struct glyph_matrix *desired_matrix = w->desired_matrix;
4269 struct glyph_matrix *current_matrix = w->current_matrix; 4261 struct glyph_matrix *current_matrix = w->current_matrix;
4270 int yb = window_text_bottom_y (w); 4262 int yb = window_text_bottom_y (w);
4271 int i, j, first_old, first_new, last_old, last_new; 4263 ptrdiff_t i;
4272 int nruns, n, run_idx; 4264 int j, first_old, first_new, last_old, last_new;
4273 ptrdiff_t nbytes; 4265 int nruns, run_idx;
4266 ptrdiff_t n;
4274 struct row_entry *entry; 4267 struct row_entry *entry;
4275 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w))); 4268 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
4276 4269
@@ -4361,45 +4354,59 @@ scrolling_window (struct window *w, int header_line_p)
4361 if (last_new == first_new) 4354 if (last_new == first_new)
4362 return 0; 4355 return 0;
4363 4356
4357 /* Check for integer overflow in size calculation.
4358
4359 If next_almost_prime checks (N) for divisibility by 2..10, then
4360 it can return at most N + 10, e.g., next_almost_prime (1) == 11.
4361 So, set next_almost_prime_increment_max to 10.
4362
4363 It's just a coincidence that next_almost_prime_increment_max ==
4364 NEXT_ALMOST_PRIME_LIMIT - 1. If NEXT_ALMOST_PRIME_LIMIT were
4365 13, then next_almost_prime_increment_max would be 14, e.g.,
4366 because next_almost_prime (113) would be 127. */
4367 {
4368 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
4369 enum { next_almost_prime_increment_max = 10 };
4370 ptrdiff_t row_table_max =
4371 (min (PTRDIFF_MAX, SIZE_MAX) / (3 * sizeof *row_table)
4372 - next_almost_prime_increment_max);
4373 ptrdiff_t current_nrows_max = row_table_max - desired_matrix->nrows;
4374 if (current_nrows_max < current_matrix->nrows)
4375 memory_full (SIZE_MAX);
4376 }
4377
4364 /* Reallocate vectors, tables etc. if necessary. */ 4378 /* Reallocate vectors, tables etc. if necessary. */
4365 4379
4366 if (current_matrix->nrows > old_lines_size) 4380 if (current_matrix->nrows > old_lines_size)
4367 { 4381 old_lines = xpalloc (old_lines, &old_lines_size,
4368 old_lines_size = current_matrix->nrows; 4382 current_matrix->nrows - old_lines_size,
4369 nbytes = old_lines_size * sizeof *old_lines; 4383 INT_MAX, sizeof *old_lines);
4370 old_lines = (struct row_entry **) xrealloc (old_lines, nbytes);
4371 }
4372 4384
4373 if (desired_matrix->nrows > new_lines_size) 4385 if (desired_matrix->nrows > new_lines_size)
4374 { 4386 new_lines = xpalloc (new_lines, &new_lines_size,
4375 new_lines_size = desired_matrix->nrows; 4387 desired_matrix->nrows - new_lines_size,
4376 nbytes = new_lines_size * sizeof *new_lines; 4388 INT_MAX, sizeof *new_lines);
4377 new_lines = (struct row_entry **) xrealloc (new_lines, nbytes);
4378 }
4379 4389
4380 n = desired_matrix->nrows + current_matrix->nrows; 4390 n = desired_matrix->nrows;
4381 if (3 * n > row_table_size) 4391 n += current_matrix->nrows;
4392 if (row_table_size < 3 * n)
4382 { 4393 {
4383 row_table_size = next_almost_prime (3 * n); 4394 ptrdiff_t size = next_almost_prime (3 * n);
4384 nbytes = row_table_size * sizeof *row_table; 4395 row_table = xnrealloc (row_table, size, sizeof *row_table);
4385 row_table = (struct row_entry **) xrealloc (row_table, nbytes); 4396 row_table_size = size;
4386 memset (row_table, 0, nbytes); 4397 memset (row_table, 0, size * sizeof *row_table);
4387 } 4398 }
4388 4399
4389 if (n > row_entry_pool_size) 4400 if (n > row_entry_pool_size)
4390 { 4401 row_entry_pool = xpalloc (row_entry_pool, &row_entry_pool_size,
4391 row_entry_pool_size = n; 4402 n - row_entry_pool_size,
4392 nbytes = row_entry_pool_size * sizeof *row_entry_pool; 4403 -1, sizeof *row_entry_pool);
4393 row_entry_pool = (struct row_entry *) xrealloc (row_entry_pool, nbytes);
4394 }
4395 4404
4396 if (desired_matrix->nrows > runs_size) 4405 if (desired_matrix->nrows > runs_size)
4397 { 4406 {
4407 runs = xnrealloc (runs, desired_matrix->nrows, sizeof *runs);
4408 run_pool = xnrealloc (run_pool, desired_matrix->nrows, sizeof *run_pool);
4398 runs_size = desired_matrix->nrows; 4409 runs_size = desired_matrix->nrows;
4399 nbytes = runs_size * sizeof *runs;
4400 runs = (struct run **) xrealloc (runs, nbytes);
4401 nbytes = runs_size * sizeof *run_pool;
4402 run_pool = (struct run *) xrealloc (run_pool, nbytes);
4403 } 4410 }
4404 4411
4405 nruns = run_idx = 0; 4412 nruns = run_idx = 0;
diff --git a/src/doc.c b/src/doc.c
index 69646f5af51..83e943c42b8 100644
--- a/src/doc.c
+++ b/src/doc.c
@@ -39,7 +39,7 @@ Lisp_Object Qfunction_documentation;
39extern Lisp_Object Qclosure; 39extern Lisp_Object Qclosure;
40/* Buffer used for reading from documentation file. */ 40/* Buffer used for reading from documentation file. */
41static char *get_doc_string_buffer; 41static char *get_doc_string_buffer;
42static int get_doc_string_buffer_size; 42static ptrdiff_t get_doc_string_buffer_size;
43 43
44static unsigned char *read_bytecode_pointer; 44static unsigned char *read_bytecode_pointer;
45static Lisp_Object Fdocumentation_property (Lisp_Object, Lisp_Object, 45static Lisp_Object Fdocumentation_property (Lisp_Object, Lisp_Object,
@@ -166,20 +166,19 @@ get_doc_string (Lisp_Object filepos, int unibyte, int definition)
166 p = get_doc_string_buffer; 166 p = get_doc_string_buffer;
167 while (1) 167 while (1)
168 { 168 {
169 EMACS_INT space_left = (get_doc_string_buffer_size 169 ptrdiff_t space_left = (get_doc_string_buffer_size - 1
170 - (p - get_doc_string_buffer)); 170 - (p - get_doc_string_buffer));
171 int nread; 171 int nread;
172 172
173 /* Allocate or grow the buffer if we need to. */ 173 /* Allocate or grow the buffer if we need to. */
174 if (space_left == 0) 174 if (space_left <= 0)
175 { 175 {
176 EMACS_INT in_buffer = p - get_doc_string_buffer; 176 ptrdiff_t in_buffer = p - get_doc_string_buffer;
177 get_doc_string_buffer_size += 16 * 1024; 177 get_doc_string_buffer =
178 get_doc_string_buffer 178 xpalloc (get_doc_string_buffer, &get_doc_string_buffer_size,
179 = (char *) xrealloc (get_doc_string_buffer, 179 16 * 1024, -1, 1);
180 get_doc_string_buffer_size + 1);
181 p = get_doc_string_buffer + in_buffer; 180 p = get_doc_string_buffer + in_buffer;
182 space_left = (get_doc_string_buffer_size 181 space_left = (get_doc_string_buffer_size - 1
183 - (p - get_doc_string_buffer)); 182 - (p - get_doc_string_buffer));
184 } 183 }
185 184
@@ -713,16 +712,16 @@ a new string, without any text properties, is returned. */)
713 int changed = 0; 712 int changed = 0;
714 register unsigned char *strp; 713 register unsigned char *strp;
715 register char *bufp; 714 register char *bufp;
716 EMACS_INT idx; 715 ptrdiff_t idx;
717 EMACS_INT bsize; 716 ptrdiff_t bsize;
718 Lisp_Object tem; 717 Lisp_Object tem;
719 Lisp_Object keymap; 718 Lisp_Object keymap;
720 unsigned char *start; 719 unsigned char *start;
721 EMACS_INT length, length_byte; 720 ptrdiff_t length, length_byte;
722 Lisp_Object name; 721 Lisp_Object name;
723 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4; 722 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
724 int multibyte; 723 int multibyte;
725 EMACS_INT nchars; 724 ptrdiff_t nchars;
726 725
727 if (NILP (string)) 726 if (NILP (string))
728 return Qnil; 727 return Qnil;
@@ -774,7 +773,7 @@ a new string, without any text properties, is returned. */)
774 } 773 }
775 else if (strp[0] == '\\' && strp[1] == '[') 774 else if (strp[0] == '\\' && strp[1] == '[')
776 { 775 {
777 EMACS_INT start_idx; 776 ptrdiff_t start_idx;
778 int follow_remap = 1; 777 int follow_remap = 1;
779 778
780 changed = 1; 779 changed = 1;
@@ -813,7 +812,9 @@ a new string, without any text properties, is returned. */)
813 812
814 if (NILP (tem)) /* but not on any keys */ 813 if (NILP (tem)) /* but not on any keys */
815 { 814 {
816 EMACS_INT offset = bufp - buf; 815 ptrdiff_t offset = bufp - buf;
816 if (STRING_BYTES_BOUND - 4 < bsize)
817 string_overflow ();
817 buf = (char *) xrealloc (buf, bsize += 4); 818 buf = (char *) xrealloc (buf, bsize += 4);
818 bufp = buf + offset; 819 bufp = buf + offset;
819 memcpy (bufp, "M-x ", 4); 820 memcpy (bufp, "M-x ", 4);
@@ -836,7 +837,7 @@ a new string, without any text properties, is returned. */)
836 else if (strp[0] == '\\' && (strp[1] == '{' || strp[1] == '<')) 837 else if (strp[0] == '\\' && (strp[1] == '{' || strp[1] == '<'))
837 { 838 {
838 struct buffer *oldbuf; 839 struct buffer *oldbuf;
839 EMACS_INT start_idx; 840 ptrdiff_t start_idx;
840 /* This is for computing the SHADOWS arg for describe_map_tree. */ 841 /* This is for computing the SHADOWS arg for describe_map_tree. */
841 Lisp_Object active_maps = Fcurrent_active_maps (Qnil, Qnil); 842 Lisp_Object active_maps = Fcurrent_active_maps (Qnil, Qnil);
842 Lisp_Object earlier_maps; 843 Lisp_Object earlier_maps;
@@ -907,7 +908,9 @@ a new string, without any text properties, is returned. */)
907 length_byte = SBYTES (tem); 908 length_byte = SBYTES (tem);
908 subst: 909 subst:
909 { 910 {
910 EMACS_INT offset = bufp - buf; 911 ptrdiff_t offset = bufp - buf;
912 if (STRING_BYTES_BOUND - length_byte < bsize)
913 string_overflow ();
911 buf = (char *) xrealloc (buf, bsize += length_byte); 914 buf = (char *) xrealloc (buf, bsize += length_byte);
912 bufp = buf + offset; 915 bufp = buf + offset;
913 memcpy (bufp, start, length_byte); 916 memcpy (bufp, start, length_byte);
diff --git a/src/editfns.c b/src/editfns.c
index 297f7b6d7e4..6759016766f 100644
--- a/src/editfns.c
+++ b/src/editfns.c
@@ -2107,7 +2107,7 @@ static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2107void 2107void
2108set_time_zone_rule (const char *tzstring) 2108set_time_zone_rule (const char *tzstring)
2109{ 2109{
2110 int envptrs; 2110 ptrdiff_t envptrs;
2111 char **from, **to, **newenv; 2111 char **from, **to, **newenv;
2112 2112
2113 /* Make the ENVIRON vector longer with room for TZSTRING. */ 2113 /* Make the ENVIRON vector longer with room for TZSTRING. */
@@ -3357,7 +3357,7 @@ usage: (save-restriction &rest BODY) */)
3357static char *message_text; 3357static char *message_text;
3358 3358
3359/* Allocated length of that buffer. */ 3359/* Allocated length of that buffer. */
3360static int message_length; 3360static ptrdiff_t message_length;
3361 3361
3362DEFUN ("message", Fmessage, Smessage, 1, MANY, 0, 3362DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3363 doc: /* Display a message at the bottom of the screen. 3363 doc: /* Display a message at the bottom of the screen.
@@ -3439,8 +3439,8 @@ usage: (message-box FORMAT-STRING &rest ARGS) */)
3439 } 3439 }
3440 if (SBYTES (val) > message_length) 3440 if (SBYTES (val) > message_length)
3441 { 3441 {
3442 message_text = (char *) xrealloc (message_text, SBYTES (val));
3442 message_length = SBYTES (val); 3443 message_length = SBYTES (val);
3443 message_text = (char *)xrealloc (message_text, message_length);
3444 } 3444 }
3445 memcpy (message_text, SDATA (val), SBYTES (val)); 3445 memcpy (message_text, SDATA (val), SBYTES (val));
3446 message2 (message_text, SBYTES (val), 3446 message2 (message_text, SBYTES (val),
@@ -3889,7 +3889,7 @@ usage: (format STRING &rest OBJECTS) */)
3889 : -1)), 3889 : -1)),
3890 3890
3891 /* Maximum number of bytes generated by any format, if 3891 /* Maximum number of bytes generated by any format, if
3892 precision is no more than DBL_USEFUL_PRECISION_MAX. 3892 precision is no more than USEFUL_PRECISION_MAX.
3893 On all practical hosts, %f is the worst case. */ 3893 On all practical hosts, %f is the worst case. */
3894 SPRINTF_BUFSIZE = 3894 SPRINTF_BUFSIZE =
3895 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX, 3895 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
@@ -4165,7 +4165,7 @@ usage: (format STRING &rest OBJECTS) */)
4165 character. CONVBYTES says how much room is needed. Allocate 4165 character. CONVBYTES says how much room is needed. Allocate
4166 enough room (and then some) and do it again. */ 4166 enough room (and then some) and do it again. */
4167 { 4167 {
4168 EMACS_INT used = p - buf; 4168 ptrdiff_t used = p - buf;
4169 4169
4170 if (max_bufsize - used < convbytes) 4170 if (max_bufsize - used < convbytes)
4171 string_overflow (); 4171 string_overflow ();
diff --git a/src/emacs.c b/src/emacs.c
index 868df894353..b89d3d82e82 100644
--- a/src/emacs.c
+++ b/src/emacs.c
@@ -1361,24 +1361,17 @@ Using an Emacs configured with --with-x-toolkit=lucid does not have this problem
1361 /* If we have the form --display=NAME, 1361 /* If we have the form --display=NAME,
1362 convert it into -d name. 1362 convert it into -d name.
1363 This requires inserting a new element into argv. */ 1363 This requires inserting a new element into argv. */
1364 if (displayname != 0 && skip_args - count_before == 1) 1364 if (displayname && count_before < skip_args)
1365 { 1365 {
1366 char **new = (char **) xmalloc (sizeof (char *) * (argc + 2)); 1366 if (skip_args == count_before + 1)
1367 int j; 1367 {
1368 1368 memmove (argv + count_before + 3, argv + count_before + 2,
1369 for (j = 0; j < count_before + 1; j++) 1369 (argc - (count_before + 2)) * sizeof *argv);
1370 new[j] = argv[j]; 1370 argv[count_before + 2] = displayname;
1371 new[count_before + 1] = (char *) "-d"; 1371 argc++;
1372 new[count_before + 2] = displayname; 1372 }
1373 for (j = count_before + 2; j <argc; j++) 1373 argv[count_before + 1] = (char *) "-d";
1374 new[j + 1] = argv[j];
1375 argv = new;
1376 argc++;
1377 } 1374 }
1378 /* Change --display to -d, when its arg is separate. */
1379 else if (displayname != 0 && skip_args > count_before
1380 && argv[count_before + 1][1] == '-')
1381 argv[count_before + 1] = (char *) "-d";
1382 1375
1383 if (! no_site_lisp) 1376 if (! no_site_lisp)
1384 { 1377 {
@@ -1844,8 +1837,8 @@ sort_args (int argc, char **argv)
1844 0 for an option that takes no arguments, 1837 0 for an option that takes no arguments,
1845 1 for an option that takes one argument, etc. 1838 1 for an option that takes one argument, etc.
1846 -1 for an ordinary non-option argument. */ 1839 -1 for an ordinary non-option argument. */
1847 int *options = (int *) xmalloc (sizeof (int) * argc); 1840 int *options = xnmalloc (argc, sizeof *options);
1848 int *priority = (int *) xmalloc (sizeof (int) * argc); 1841 int *priority = xnmalloc (argc, sizeof *priority);
1849 int to = 1; 1842 int to = 1;
1850 int incoming_used = 1; 1843 int incoming_used = 1;
1851 int from; 1844 int from;
diff --git a/src/eval.c b/src/eval.c
index 372e9954620..e722b53fb72 100644
--- a/src/eval.c
+++ b/src/eval.c
@@ -133,8 +133,9 @@ static Lisp_Object Ffetch_bytecode (Lisp_Object);
133void 133void
134init_eval_once (void) 134init_eval_once (void)
135{ 135{
136 specpdl_size = 50; 136 enum { size = 50 };
137 specpdl = (struct specbinding *) xmalloc (specpdl_size * sizeof (struct specbinding)); 137 specpdl = (struct specbinding *) xmalloc (size * sizeof (struct specbinding));
138 specpdl_size = size;
138 specpdl_ptr = specpdl; 139 specpdl_ptr = specpdl;
139 /* Don't forget to update docs (lispref node "Local Variables"). */ 140 /* Don't forget to update docs (lispref node "Local Variables"). */
140 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */ 141 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
@@ -192,7 +193,7 @@ call_debugger (Lisp_Object arg)
192 if (lisp_eval_depth + 40 > max_lisp_eval_depth) 193 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
193 max_lisp_eval_depth = lisp_eval_depth + 40; 194 max_lisp_eval_depth = lisp_eval_depth + 40;
194 195
195 if (SPECPDL_INDEX () + 100 > max_specpdl_size) 196 if (max_specpdl_size - 100 < SPECPDL_INDEX ())
196 max_specpdl_size = SPECPDL_INDEX () + 100; 197 max_specpdl_size = SPECPDL_INDEX () + 100;
197 198
198#ifdef HAVE_WINDOW_SYSTEM 199#ifdef HAVE_WINDOW_SYSTEM
@@ -3254,17 +3255,21 @@ static void
3254grow_specpdl (void) 3255grow_specpdl (void)
3255{ 3256{
3256 register int count = SPECPDL_INDEX (); 3257 register int count = SPECPDL_INDEX ();
3257 if (specpdl_size >= max_specpdl_size) 3258 int max_size =
3259 min (max_specpdl_size,
3260 min (max (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct specbinding),
3261 INT_MAX));
3262 int size;
3263 if (max_size <= specpdl_size)
3258 { 3264 {
3259 if (max_specpdl_size < 400) 3265 if (max_specpdl_size < 400)
3260 max_specpdl_size = 400; 3266 max_size = max_specpdl_size = 400;
3261 if (specpdl_size >= max_specpdl_size) 3267 if (max_size <= specpdl_size)
3262 signal_error ("Variable binding depth exceeds max-specpdl-size", Qnil); 3268 signal_error ("Variable binding depth exceeds max-specpdl-size", Qnil);
3263 } 3269 }
3264 specpdl_size *= 2; 3270 size = specpdl_size < max_size / 2 ? 2 * specpdl_size : max_size;
3265 if (specpdl_size > max_specpdl_size) 3271 specpdl = xnrealloc (specpdl, size, sizeof *specpdl);
3266 specpdl_size = max_specpdl_size; 3272 specpdl_size = size;
3267 specpdl = (struct specbinding *) xrealloc (specpdl, specpdl_size * sizeof (struct specbinding));
3268 specpdl_ptr = specpdl + count; 3273 specpdl_ptr = specpdl + count;
3269} 3274}
3270 3275
diff --git a/src/fileio.c b/src/fileio.c
index 61713689351..60ee35bb399 100644
--- a/src/fileio.c
+++ b/src/fileio.c
@@ -2912,7 +2912,7 @@ symbolic notation, like the `chmod' command from GNU Coreutils. */)
2912 2912
2913 encoded_absname = ENCODE_FILE (absname); 2913 encoded_absname = ENCODE_FILE (absname);
2914 2914
2915 if (chmod (SSDATA (encoded_absname), XINT (mode)) < 0) 2915 if (chmod (SSDATA (encoded_absname), XINT (mode) & 07777) < 0)
2916 report_file_error ("Doing chmod", Fcons (absname, Qnil)); 2916 report_file_error ("Doing chmod", Fcons (absname, Qnil));
2917 2917
2918 return Qnil; 2918 return Qnil;
@@ -5114,11 +5114,11 @@ auto_save_1 (void)
5114 { 5114 {
5115 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0) 5115 if (stat (SSDATA (BVAR (current_buffer, filename)), &st) >= 0)
5116 /* But make sure we can overwrite it later! */ 5116 /* But make sure we can overwrite it later! */
5117 auto_save_mode_bits = st.st_mode | 0600; 5117 auto_save_mode_bits = (st.st_mode | 0600) & 0777;
5118 else if ((modes = Ffile_modes (BVAR (current_buffer, filename)), 5118 else if ((modes = Ffile_modes (BVAR (current_buffer, filename)),
5119 INTEGERP (modes))) 5119 INTEGERP (modes)))
5120 /* Remote files don't cooperate with stat. */ 5120 /* Remote files don't cooperate with stat. */
5121 auto_save_mode_bits = XINT (modes) | 0600; 5121 auto_save_mode_bits = (XINT (modes) | 0600) & 0777;
5122 } 5122 }
5123 5123
5124 return 5124 return
diff --git a/src/fns.c b/src/fns.c
index 9c9d19fe26a..a3af6b8c15a 100644
--- a/src/fns.c
+++ b/src/fns.c
@@ -602,7 +602,7 @@ concat (ptrdiff_t nargs, Lisp_Object *args,
602 602
603 prev = Qnil; 603 prev = Qnil;
604 if (STRINGP (val)) 604 if (STRINGP (val))
605 SAFE_ALLOCA (textprops, struct textprop_rec *, sizeof (struct textprop_rec) * nargs); 605 SAFE_NALLOCA (textprops, 1, nargs);
606 606
607 for (argnum = 0; argnum < nargs; argnum++) 607 for (argnum = 0; argnum < nargs; argnum++)
608 { 608 {
@@ -3395,11 +3395,13 @@ check_hash_table (Lisp_Object obj)
3395 3395
3396 3396
3397/* Value is the next integer I >= N, N >= 0 which is "almost" a prime 3397/* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3398 number. */ 3398 number. A number is "almost" a prime number if it is not divisible
3399 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3399 3400
3400EMACS_INT 3401EMACS_INT
3401next_almost_prime (EMACS_INT n) 3402next_almost_prime (EMACS_INT n)
3402{ 3403{
3404 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3403 for (n |= 1; ; n += 2) 3405 for (n |= 1; ; n += 2)
3404 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0) 3406 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3405 return n; 3407 return n;
@@ -3787,11 +3789,11 @@ maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3787 the hash code of KEY. Value is the index of the entry in H 3789 the hash code of KEY. Value is the index of the entry in H
3788 matching KEY, or -1 if not found. */ 3790 matching KEY, or -1 if not found. */
3789 3791
3790EMACS_INT 3792ptrdiff_t
3791hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash) 3793hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3792{ 3794{
3793 EMACS_UINT hash_code; 3795 EMACS_UINT hash_code;
3794 EMACS_INT start_of_bucket; 3796 ptrdiff_t start_of_bucket;
3795 Lisp_Object idx; 3797 Lisp_Object idx;
3796 3798
3797 hash_code = h->hashfn (h, key); 3799 hash_code = h->hashfn (h, key);
@@ -3821,11 +3823,11 @@ hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
3821 HASH is a previously computed hash code of KEY. 3823 HASH is a previously computed hash code of KEY.
3822 Value is the index of the entry in H matching KEY. */ 3824 Value is the index of the entry in H matching KEY. */
3823 3825
3824EMACS_INT 3826ptrdiff_t
3825hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value, 3827hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
3826 EMACS_UINT hash) 3828 EMACS_UINT hash)
3827{ 3829{
3828 EMACS_INT start_of_bucket, i; 3830 ptrdiff_t start_of_bucket, i;
3829 3831
3830 xassert ((hash & ~INTMASK) == 0); 3832 xassert ((hash & ~INTMASK) == 0);
3831 3833
@@ -4482,7 +4484,7 @@ If KEY is not found, return DFLT which defaults to nil. */)
4482 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt) 4484 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4483{ 4485{
4484 struct Lisp_Hash_Table *h = check_hash_table (table); 4486 struct Lisp_Hash_Table *h = check_hash_table (table);
4485 EMACS_INT i = hash_lookup (h, key, NULL); 4487 ptrdiff_t i = hash_lookup (h, key, NULL);
4486 return i >= 0 ? HASH_VALUE (h, i) : dflt; 4488 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4487} 4489}
4488 4490
@@ -4494,7 +4496,7 @@ VALUE. In any case, return VALUE. */)
4494 (Lisp_Object key, Lisp_Object value, Lisp_Object table) 4496 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4495{ 4497{
4496 struct Lisp_Hash_Table *h = check_hash_table (table); 4498 struct Lisp_Hash_Table *h = check_hash_table (table);
4497 EMACS_INT i; 4499 ptrdiff_t i;
4498 EMACS_UINT hash; 4500 EMACS_UINT hash;
4499 4501
4500 i = hash_lookup (h, key, &hash); 4502 i = hash_lookup (h, key, &hash);
diff --git a/src/frame.c b/src/frame.c
index 19ce78dfd9c..711109a70c6 100644
--- a/src/frame.c
+++ b/src/frame.c
@@ -160,7 +160,7 @@ set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
160 if (FRAME_MINIBUF_ONLY_P (f)) 160 if (FRAME_MINIBUF_ONLY_P (f))
161 return; 161 return;
162 162
163 if (INTEGERP (value)) 163 if (TYPE_RANGED_INTEGERP (int, value))
164 nlines = XINT (value); 164 nlines = XINT (value);
165 else 165 else
166 nlines = 0; 166 nlines = 0;
@@ -2992,7 +2992,7 @@ x_set_frame_parameters (FRAME_PTR f, Lisp_Object alist)
2992 f->size_hint_flags &= ~ (XNegative | YNegative); 2992 f->size_hint_flags &= ~ (XNegative | YNegative);
2993 if (EQ (left, Qminus)) 2993 if (EQ (left, Qminus))
2994 f->size_hint_flags |= XNegative; 2994 f->size_hint_flags |= XNegative;
2995 else if (INTEGERP (left)) 2995 else if (TYPE_RANGED_INTEGERP (int, left))
2996 { 2996 {
2997 leftpos = XINT (left); 2997 leftpos = XINT (left);
2998 if (leftpos < 0) 2998 if (leftpos < 0)
@@ -3000,21 +3000,21 @@ x_set_frame_parameters (FRAME_PTR f, Lisp_Object alist)
3000 } 3000 }
3001 else if (CONSP (left) && EQ (XCAR (left), Qminus) 3001 else if (CONSP (left) && EQ (XCAR (left), Qminus)
3002 && CONSP (XCDR (left)) 3002 && CONSP (XCDR (left))
3003 && INTEGERP (XCAR (XCDR (left)))) 3003 && RANGED_INTEGERP (-INT_MAX, XCAR (XCDR (left)), INT_MAX))
3004 { 3004 {
3005 leftpos = - XINT (XCAR (XCDR (left))); 3005 leftpos = - XINT (XCAR (XCDR (left)));
3006 f->size_hint_flags |= XNegative; 3006 f->size_hint_flags |= XNegative;
3007 } 3007 }
3008 else if (CONSP (left) && EQ (XCAR (left), Qplus) 3008 else if (CONSP (left) && EQ (XCAR (left), Qplus)
3009 && CONSP (XCDR (left)) 3009 && CONSP (XCDR (left))
3010 && INTEGERP (XCAR (XCDR (left)))) 3010 && TYPE_RANGED_INTEGERP (int, XCAR (XCDR (left))))
3011 { 3011 {
3012 leftpos = XINT (XCAR (XCDR (left))); 3012 leftpos = XINT (XCAR (XCDR (left)));
3013 } 3013 }
3014 3014
3015 if (EQ (top, Qminus)) 3015 if (EQ (top, Qminus))
3016 f->size_hint_flags |= YNegative; 3016 f->size_hint_flags |= YNegative;
3017 else if (INTEGERP (top)) 3017 else if (TYPE_RANGED_INTEGERP (int, top))
3018 { 3018 {
3019 toppos = XINT (top); 3019 toppos = XINT (top);
3020 if (toppos < 0) 3020 if (toppos < 0)
@@ -3022,14 +3022,14 @@ x_set_frame_parameters (FRAME_PTR f, Lisp_Object alist)
3022 } 3022 }
3023 else if (CONSP (top) && EQ (XCAR (top), Qminus) 3023 else if (CONSP (top) && EQ (XCAR (top), Qminus)
3024 && CONSP (XCDR (top)) 3024 && CONSP (XCDR (top))
3025 && INTEGERP (XCAR (XCDR (top)))) 3025 && RANGED_INTEGERP (-INT_MAX, XCAR (XCDR (top)), INT_MAX))
3026 { 3026 {
3027 toppos = - XINT (XCAR (XCDR (top))); 3027 toppos = - XINT (XCAR (XCDR (top)));
3028 f->size_hint_flags |= YNegative; 3028 f->size_hint_flags |= YNegative;
3029 } 3029 }
3030 else if (CONSP (top) && EQ (XCAR (top), Qplus) 3030 else if (CONSP (top) && EQ (XCAR (top), Qplus)
3031 && CONSP (XCDR (top)) 3031 && CONSP (XCDR (top))
3032 && INTEGERP (XCAR (XCDR (top)))) 3032 && TYPE_RANGED_INTEGERP (int, XCAR (XCDR (top))))
3033 { 3033 {
3034 toppos = XINT (XCAR (XCDR (top))); 3034 toppos = XINT (XCAR (XCDR (top)));
3035 } 3035 }
@@ -3481,7 +3481,7 @@ x_set_scroll_bar_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
3481 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f)); 3481 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
3482 do_pending_window_change (0); 3482 do_pending_window_change (0);
3483 } 3483 }
3484 else if (INTEGERP (arg) && XINT (arg) > 0 3484 else if (RANGED_INTEGERP (1, arg, INT_MAX)
3485 && XFASTINT (arg) != FRAME_CONFIG_SCROLL_BAR_WIDTH (f)) 3485 && XFASTINT (arg) != FRAME_CONFIG_SCROLL_BAR_WIDTH (f))
3486 { 3486 {
3487 if (XFASTINT (arg) <= 2 * VERTICAL_SCROLL_BAR_WIDTH_TRIM) 3487 if (XFASTINT (arg) <= 2 * VERTICAL_SCROLL_BAR_WIDTH_TRIM)
@@ -3520,7 +3520,7 @@ x_set_alpha (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
3520{ 3520{
3521 double alpha = 1.0; 3521 double alpha = 1.0;
3522 double newval[2]; 3522 double newval[2];
3523 int i, ialpha; 3523 int i;
3524 Lisp_Object item; 3524 Lisp_Object item;
3525 3525
3526 for (i = 0; i < 2; i++) 3526 for (i = 0; i < 2; i++)
@@ -3544,7 +3544,7 @@ x_set_alpha (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
3544 } 3544 }
3545 else if (INTEGERP (item)) 3545 else if (INTEGERP (item))
3546 { 3546 {
3547 ialpha = XINT (item); 3547 EMACS_INT ialpha = XINT (item);
3548 if (ialpha < 0 || 100 < ialpha) 3548 if (ialpha < 0 || 100 < ialpha)
3549 args_out_of_range (make_number (0), make_number (100)); 3549 args_out_of_range (make_number (0), make_number (100));
3550 else 3550 else
@@ -4031,11 +4031,15 @@ x_figure_window_size (struct frame *f, Lisp_Object parms, int toolbar_p)
4031 if (!EQ (tem0, Qunbound)) 4031 if (!EQ (tem0, Qunbound))
4032 { 4032 {
4033 CHECK_NUMBER (tem0); 4033 CHECK_NUMBER (tem0);
4034 if (! (0 <= XINT (tem0) && XINT (tem0) <= INT_MAX))
4035 xsignal1 (Qargs_out_of_range, tem0);
4034 FRAME_LINES (f) = XINT (tem0); 4036 FRAME_LINES (f) = XINT (tem0);
4035 } 4037 }
4036 if (!EQ (tem1, Qunbound)) 4038 if (!EQ (tem1, Qunbound))
4037 { 4039 {
4038 CHECK_NUMBER (tem1); 4040 CHECK_NUMBER (tem1);
4041 if (! (0 <= XINT (tem1) && XINT (tem1) <= INT_MAX))
4042 xsignal1 (Qargs_out_of_range, tem1);
4039 SET_FRAME_COLS (f, XINT (tem1)); 4043 SET_FRAME_COLS (f, XINT (tem1));
4040 } 4044 }
4041 if (!NILP (tem2) && !EQ (tem2, Qunbound)) 4045 if (!NILP (tem2) && !EQ (tem2, Qunbound))
@@ -4066,12 +4070,10 @@ x_figure_window_size (struct frame *f, Lisp_Object parms, int toolbar_p)
4066 ? tool_bar_button_relief 4070 ? tool_bar_button_relief
4067 : DEFAULT_TOOL_BAR_BUTTON_RELIEF); 4071 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
4068 4072
4069 if (INTEGERP (Vtool_bar_button_margin) 4073 if (RANGED_INTEGERP (1, Vtool_bar_button_margin, INT_MAX))
4070 && XINT (Vtool_bar_button_margin) > 0)
4071 margin = XFASTINT (Vtool_bar_button_margin); 4074 margin = XFASTINT (Vtool_bar_button_margin);
4072 else if (CONSP (Vtool_bar_button_margin) 4075 else if (CONSP (Vtool_bar_button_margin)
4073 && INTEGERP (XCDR (Vtool_bar_button_margin)) 4076 && RANGED_INTEGERP (1, XCDR (Vtool_bar_button_margin), INT_MAX))
4074 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
4075 margin = XFASTINT (XCDR (Vtool_bar_button_margin)); 4077 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
4076 else 4078 else
4077 margin = 0; 4079 margin = 0;
@@ -4097,14 +4099,14 @@ x_figure_window_size (struct frame *f, Lisp_Object parms, int toolbar_p)
4097 } 4099 }
4098 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus) 4100 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
4099 && CONSP (XCDR (tem0)) 4101 && CONSP (XCDR (tem0))
4100 && INTEGERP (XCAR (XCDR (tem0)))) 4102 && RANGED_INTEGERP (-INT_MAX, XCAR (XCDR (tem0)), INT_MAX))
4101 { 4103 {
4102 f->top_pos = - XINT (XCAR (XCDR (tem0))); 4104 f->top_pos = - XINT (XCAR (XCDR (tem0)));
4103 window_prompting |= YNegative; 4105 window_prompting |= YNegative;
4104 } 4106 }
4105 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus) 4107 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
4106 && CONSP (XCDR (tem0)) 4108 && CONSP (XCDR (tem0))
4107 && INTEGERP (XCAR (XCDR (tem0)))) 4109 && TYPE_RANGED_INTEGERP (int, XCAR (XCDR (tem0))))
4108 { 4110 {
4109 f->top_pos = XINT (XCAR (XCDR (tem0))); 4111 f->top_pos = XINT (XCAR (XCDR (tem0)));
4110 } 4112 }
@@ -4125,14 +4127,14 @@ x_figure_window_size (struct frame *f, Lisp_Object parms, int toolbar_p)
4125 } 4127 }
4126 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus) 4128 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
4127 && CONSP (XCDR (tem1)) 4129 && CONSP (XCDR (tem1))
4128 && INTEGERP (XCAR (XCDR (tem1)))) 4130 && RANGED_INTEGERP (-INT_MAX, XCAR (XCDR (tem1)), INT_MAX))
4129 { 4131 {
4130 f->left_pos = - XINT (XCAR (XCDR (tem1))); 4132 f->left_pos = - XINT (XCAR (XCDR (tem1)));
4131 window_prompting |= XNegative; 4133 window_prompting |= XNegative;
4132 } 4134 }
4133 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus) 4135 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
4134 && CONSP (XCDR (tem1)) 4136 && CONSP (XCDR (tem1))
4135 && INTEGERP (XCAR (XCDR (tem1)))) 4137 && TYPE_RANGED_INTEGERP (int, XCAR (XCDR (tem1))))
4136 { 4138 {
4137 f->left_pos = XINT (XCAR (XCDR (tem1))); 4139 f->left_pos = XINT (XCAR (XCDR (tem1)));
4138 } 4140 }
diff --git a/src/frame.h b/src/frame.h
index 8dccfb8540a..3775403810f 100644
--- a/src/frame.h
+++ b/src/frame.h
@@ -258,11 +258,11 @@ struct frame
258 258
259 /* Size of this frame, excluding fringes, scroll bars etc., 259 /* Size of this frame, excluding fringes, scroll bars etc.,
260 in units of canonical characters. */ 260 in units of canonical characters. */
261 EMACS_INT text_lines, text_cols; 261 int text_lines, text_cols;
262 262
263 /* Total size of this frame (i.e. its native window), in units of 263 /* Total size of this frame (i.e. its native window), in units of
264 canonical characters. */ 264 canonical characters. */
265 EMACS_INT total_lines, total_cols; 265 int total_lines, total_cols;
266 266
267 /* New text height and width for pending size change. 267 /* New text height and width for pending size change.
268 0 if no change pending. */ 268 0 if no change pending. */
diff --git a/src/fringe.c b/src/fringe.c
index a4dc9433aff..5878c541247 100644
--- a/src/fringe.c
+++ b/src/fringe.c
@@ -1610,22 +1610,25 @@ If BITMAP already exists, the existing definition is replaced. */)
1610 1610
1611 if (n == max_fringe_bitmaps) 1611 if (n == max_fringe_bitmaps)
1612 { 1612 {
1613 if ((max_fringe_bitmaps + 20) > MAX_FRINGE_BITMAPS) 1613 int bitmaps = max_fringe_bitmaps + 20;
1614 if (MAX_FRINGE_BITMAPS < bitmaps)
1614 error ("No free fringe bitmap slots"); 1615 error ("No free fringe bitmap slots");
1615 1616
1616 i = max_fringe_bitmaps; 1617 i = max_fringe_bitmaps;
1617 max_fringe_bitmaps += 20;
1618 fringe_bitmaps 1618 fringe_bitmaps
1619 = ((struct fringe_bitmap **) 1619 = ((struct fringe_bitmap **)
1620 xrealloc (fringe_bitmaps, max_fringe_bitmaps * sizeof (struct fringe_bitmap *))); 1620 xrealloc (fringe_bitmaps, bitmaps * sizeof *fringe_bitmaps));
1621 fringe_faces 1621 fringe_faces
1622 = (Lisp_Object *) xrealloc (fringe_faces, max_fringe_bitmaps * sizeof (Lisp_Object)); 1622 = (Lisp_Object *) xrealloc (fringe_faces,
1623 bitmaps * sizeof *fringe_faces);
1623 1624
1624 for (; i < max_fringe_bitmaps; i++) 1625 for (i = max_fringe_bitmaps; i < bitmaps; i++)
1625 { 1626 {
1626 fringe_bitmaps[i] = NULL; 1627 fringe_bitmaps[i] = NULL;
1627 fringe_faces[i] = Qnil; 1628 fringe_faces[i] = Qnil;
1628 } 1629 }
1630
1631 max_fringe_bitmaps = bitmaps;
1629 } 1632 }
1630 } 1633 }
1631 1634
diff --git a/src/ftfont.c b/src/ftfont.c
index 5c98073057c..7858a31be21 100644
--- a/src/ftfont.c
+++ b/src/ftfont.c
@@ -686,7 +686,10 @@ ftfont_get_open_type_spec (Lisp_Object otf_spec)
686 if (NILP (val)) 686 if (NILP (val))
687 continue; 687 continue;
688 len = Flength (val); 688 len = Flength (val);
689 spec->features[i] = malloc (sizeof (int) * XINT (len)); 689 spec->features[i] =
690 (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) < XINT (len)
691 ? 0
692 : malloc (sizeof (int) * XINT (len)));
690 if (! spec->features[i]) 693 if (! spec->features[i])
691 { 694 {
692 if (i > 0 && spec->features[0]) 695 if (i > 0 && spec->features[0])
@@ -1765,15 +1768,10 @@ static OTF_GlyphString otf_gstring;
1765static void 1768static void
1766setup_otf_gstring (int size) 1769setup_otf_gstring (int size)
1767{ 1770{
1768 if (otf_gstring.size == 0) 1771 if (otf_gstring.size < size)
1769 { 1772 {
1770 otf_gstring.glyphs = (OTF_Glyph *) xmalloc (sizeof (OTF_Glyph) * size); 1773 otf_gstring.glyphs = xnrealloc (otf_gstring.glyphs,
1771 otf_gstring.size = size; 1774 size, sizeof (OTF_Glyph));
1772 }
1773 else if (otf_gstring.size < size)
1774 {
1775 otf_gstring.glyphs = xrealloc (otf_gstring.glyphs,
1776 sizeof (OTF_Glyph) * size);
1777 otf_gstring.size = size; 1775 otf_gstring.size = size;
1778 } 1776 }
1779 otf_gstring.used = size; 1777 otf_gstring.used = size;
@@ -2449,17 +2447,19 @@ ftfont_shape_by_flt (Lisp_Object lgstring, struct font *font,
2449 } 2447 }
2450 } 2448 }
2451 2449
2450 if (INT_MAX / 2 < len)
2451 memory_full (SIZE_MAX);
2452
2452 if (gstring.allocated == 0) 2453 if (gstring.allocated == 0)
2453 { 2454 {
2454 gstring.allocated = len * 2;
2455 gstring.glyph_size = sizeof (MFLTGlyph); 2455 gstring.glyph_size = sizeof (MFLTGlyph);
2456 gstring.glyphs = xmalloc (sizeof (MFLTGlyph) * gstring.allocated); 2456 gstring.glyphs = xnmalloc (len * 2, sizeof (MFLTGlyph));
2457 gstring.allocated = len * 2;
2457 } 2458 }
2458 else if (gstring.allocated < len * 2) 2459 else if (gstring.allocated < len * 2)
2459 { 2460 {
2461 gstring.glyphs = xnrealloc (gstring.glyphs, len * 2, sizeof (MFLTGlyph));
2460 gstring.allocated = len * 2; 2462 gstring.allocated = len * 2;
2461 gstring.glyphs = xrealloc (gstring.glyphs,
2462 sizeof (MFLTGlyph) * gstring.allocated);
2463 } 2463 }
2464 memset (gstring.glyphs, 0, sizeof (MFLTGlyph) * len); 2464 memset (gstring.glyphs, 0, sizeof (MFLTGlyph) * len);
2465 for (i = 0; i < len; i++) 2465 for (i = 0; i < len; i++)
@@ -2508,9 +2508,11 @@ ftfont_shape_by_flt (Lisp_Object lgstring, struct font *font,
2508 int result = mflt_run (&gstring, 0, len, &flt_font_ft.flt_font, flt); 2508 int result = mflt_run (&gstring, 0, len, &flt_font_ft.flt_font, flt);
2509 if (result != -2) 2509 if (result != -2)
2510 break; 2510 break;
2511 gstring.allocated += gstring.allocated; 2511 if (INT_MAX / 2 < gstring.allocated)
2512 gstring.glyphs = xrealloc (gstring.glyphs, 2512 memory_full (SIZE_MAX);
2513 sizeof (MFLTGlyph) * gstring.allocated); 2513 gstring.glyphs = xnrealloc (gstring.glyphs,
2514 gstring.allocated, 2 * sizeof (MFLTGlyph));
2515 gstring.allocated *= 2;
2514 } 2516 }
2515 if (gstring.used > LGSTRING_GLYPH_LEN (lgstring)) 2517 if (gstring.used > LGSTRING_GLYPH_LEN (lgstring))
2516 return Qnil; 2518 return Qnil;
diff --git a/src/gtkutil.c b/src/gtkutil.c
index dd4d99b9d33..c39119c8151 100644
--- a/src/gtkutil.c
+++ b/src/gtkutil.c
@@ -487,7 +487,8 @@ get_utf8_string (const char *str)
487 if (!utf8_str) 487 if (!utf8_str)
488 { 488 {
489 /* Probably some control characters in str. Escape them. */ 489 /* Probably some control characters in str. Escape them. */
490 size_t nr_bad = 0; 490 ptrdiff_t len;
491 ptrdiff_t nr_bad = 0;
491 gsize bytes_read; 492 gsize bytes_read;
492 gsize bytes_written; 493 gsize bytes_written;
493 unsigned char *p = (unsigned char *)str; 494 unsigned char *p = (unsigned char *)str;
@@ -511,7 +512,10 @@ get_utf8_string (const char *str)
511 } 512 }
512 if (cp) g_free (cp); 513 if (cp) g_free (cp);
513 514
514 up = utf8_str = xmalloc (strlen (str) + nr_bad * 4 + 1); 515 len = strlen (str);
516 if ((min (PTRDIFF_MAX, SIZE_MAX) - len - 1) / 4 < nr_bad)
517 memory_full (SIZE_MAX);
518 up = utf8_str = xmalloc (len + nr_bad * 4 + 1);
515 p = (unsigned char *)str; 519 p = (unsigned char *)str;
516 520
517 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read, 521 while (! (cp = g_locale_to_utf8 ((char *)p, -1, &bytes_read,
@@ -3296,8 +3300,8 @@ static int scroll_bar_width_for_theme;
3296static struct 3300static struct
3297{ 3301{
3298 GtkWidget **widgets; 3302 GtkWidget **widgets;
3299 int max_size; 3303 ptrdiff_t max_size;
3300 int used; 3304 ptrdiff_t used;
3301} id_to_widget; 3305} id_to_widget;
3302 3306
3303/* Grow this much every time we need to allocate more */ 3307/* Grow this much every time we need to allocate more */
@@ -3306,17 +3310,20 @@ static struct
3306 3310
3307/* Store the widget pointer W in id_to_widget and return the integer index. */ 3311/* Store the widget pointer W in id_to_widget and return the integer index. */
3308 3312
3309static int 3313static ptrdiff_t
3310xg_store_widget_in_map (GtkWidget *w) 3314xg_store_widget_in_map (GtkWidget *w)
3311{ 3315{
3312 int i; 3316 ptrdiff_t i;
3313 3317
3314 if (id_to_widget.max_size == id_to_widget.used) 3318 if (id_to_widget.max_size == id_to_widget.used)
3315 { 3319 {
3316 int new_size = id_to_widget.max_size + ID_TO_WIDGET_INCR; 3320 ptrdiff_t new_size;
3321 if (TYPE_MAXIMUM (Window) - ID_TO_WIDGET_INCR < id_to_widget.max_size)
3322 memory_full (SIZE_MAX);
3317 3323
3318 id_to_widget.widgets = xrealloc (id_to_widget.widgets, 3324 new_size = id_to_widget.max_size + ID_TO_WIDGET_INCR;
3319 sizeof (GtkWidget *)*new_size); 3325 id_to_widget.widgets = xnrealloc (id_to_widget.widgets,
3326 new_size, sizeof (GtkWidget *));
3320 3327
3321 for (i = id_to_widget.max_size; i < new_size; ++i) 3328 for (i = id_to_widget.max_size; i < new_size; ++i)
3322 id_to_widget.widgets[i] = 0; 3329 id_to_widget.widgets[i] = 0;
@@ -3345,7 +3352,7 @@ xg_store_widget_in_map (GtkWidget *w)
3345 Called when scroll bar is destroyed. */ 3352 Called when scroll bar is destroyed. */
3346 3353
3347static void 3354static void
3348xg_remove_widget_from_map (int idx) 3355xg_remove_widget_from_map (ptrdiff_t idx)
3349{ 3356{
3350 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0) 3357 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3351 { 3358 {
@@ -3357,7 +3364,7 @@ xg_remove_widget_from_map (int idx)
3357/* Get the widget pointer at IDX from id_to_widget. */ 3364/* Get the widget pointer at IDX from id_to_widget. */
3358 3365
3359static GtkWidget * 3366static GtkWidget *
3360xg_get_widget_from_map (int idx) 3367xg_get_widget_from_map (ptrdiff_t idx)
3361{ 3368{
3362 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0) 3369 if (idx < id_to_widget.max_size && id_to_widget.widgets[idx] != 0)
3363 return id_to_widget.widgets[idx]; 3370 return id_to_widget.widgets[idx];
@@ -3396,10 +3403,10 @@ xg_get_default_scrollbar_width (void)
3396/* Return the scrollbar id for X Window WID on display DPY. 3403/* Return the scrollbar id for X Window WID on display DPY.
3397 Return -1 if WID not in id_to_widget. */ 3404 Return -1 if WID not in id_to_widget. */
3398 3405
3399int 3406ptrdiff_t
3400xg_get_scroll_id_for_window (Display *dpy, Window wid) 3407xg_get_scroll_id_for_window (Display *dpy, Window wid)
3401{ 3408{
3402 int idx; 3409 ptrdiff_t idx;
3403 GtkWidget *w; 3410 GtkWidget *w;
3404 3411
3405 w = xg_win_to_widget (dpy, wid); 3412 w = xg_win_to_widget (dpy, wid);
@@ -3421,7 +3428,7 @@ xg_get_scroll_id_for_window (Display *dpy, Window wid)
3421static void 3428static void
3422xg_gtk_scroll_destroy (GtkWidget *widget, gpointer data) 3429xg_gtk_scroll_destroy (GtkWidget *widget, gpointer data)
3423{ 3430{
3424 int id = (intptr_t) data; 3431 intptr_t id = (intptr_t) data;
3425 xg_remove_widget_from_map (id); 3432 xg_remove_widget_from_map (id);
3426} 3433}
3427 3434
@@ -3496,7 +3503,7 @@ xg_create_scroll_bar (FRAME_PTR f,
3496/* Remove the scroll bar represented by SCROLLBAR_ID from the frame F. */ 3503/* Remove the scroll bar represented by SCROLLBAR_ID from the frame F. */
3497 3504
3498void 3505void
3499xg_remove_scroll_bar (FRAME_PTR f, int scrollbar_id) 3506xg_remove_scroll_bar (FRAME_PTR f, ptrdiff_t scrollbar_id)
3500{ 3507{
3501 GtkWidget *w = xg_get_widget_from_map (scrollbar_id); 3508 GtkWidget *w = xg_get_widget_from_map (scrollbar_id);
3502 if (w) 3509 if (w)
@@ -3515,7 +3522,7 @@ xg_remove_scroll_bar (FRAME_PTR f, int scrollbar_id)
3515 3522
3516void 3523void
3517xg_update_scrollbar_pos (FRAME_PTR f, 3524xg_update_scrollbar_pos (FRAME_PTR f,
3518 int scrollbar_id, 3525 ptrdiff_t scrollbar_id,
3519 int top, 3526 int top,
3520 int left, 3527 int left,
3521 int width, 3528 int width,
@@ -4429,7 +4436,7 @@ update_frame_tool_bar (FRAME_PTR f)
4429 int enabled_p = !NILP (PROP (TOOL_BAR_ITEM_ENABLED_P)); 4436 int enabled_p = !NILP (PROP (TOOL_BAR_ITEM_ENABLED_P));
4430 int selected_p = !NILP (PROP (TOOL_BAR_ITEM_SELECTED_P)); 4437 int selected_p = !NILP (PROP (TOOL_BAR_ITEM_SELECTED_P));
4431 int idx; 4438 int idx;
4432 int img_id; 4439 ptrdiff_t img_id;
4433 int icon_size = 0; 4440 int icon_size = 0;
4434 struct image *img = NULL; 4441 struct image *img = NULL;
4435 Lisp_Object image; 4442 Lisp_Object image;
diff --git a/src/gtkutil.h b/src/gtkutil.h
index 769e56da917..2dfb3a5ed6c 100644
--- a/src/gtkutil.h
+++ b/src/gtkutil.h
@@ -114,17 +114,17 @@ extern int xg_event_is_for_menubar (FRAME_PTR f, XEvent *event);
114 114
115extern int xg_have_tear_offs (void); 115extern int xg_have_tear_offs (void);
116 116
117extern int xg_get_scroll_id_for_window (Display *dpy, Window wid); 117extern ptrdiff_t xg_get_scroll_id_for_window (Display *dpy, Window wid);
118 118
119extern void xg_create_scroll_bar (FRAME_PTR f, 119extern void xg_create_scroll_bar (FRAME_PTR f,
120 struct scroll_bar *bar, 120 struct scroll_bar *bar,
121 GCallback scroll_callback, 121 GCallback scroll_callback,
122 GCallback end_callback, 122 GCallback end_callback,
123 const char *scroll_bar_name); 123 const char *scroll_bar_name);
124extern void xg_remove_scroll_bar (FRAME_PTR f, int scrollbar_id); 124extern void xg_remove_scroll_bar (FRAME_PTR f, ptrdiff_t scrollbar_id);
125 125
126extern void xg_update_scrollbar_pos (FRAME_PTR f, 126extern void xg_update_scrollbar_pos (FRAME_PTR f,
127 int scrollbar_id, 127 ptrdiff_t scrollbar_id,
128 int top, 128 int top,
129 int left, 129 int left,
130 int width, 130 int width,
@@ -185,4 +185,3 @@ extern int xg_ignore_gtk_scrollbar;
185 185
186#endif /* USE_GTK */ 186#endif /* USE_GTK */
187#endif /* GTKUTIL_H */ 187#endif /* GTKUTIL_H */
188
diff --git a/src/image.c b/src/image.c
index 65be22b087a..d0d28bea582 100644
--- a/src/image.c
+++ b/src/image.c
@@ -196,7 +196,7 @@ x_bitmap_width (FRAME_PTR f, ptrdiff_t id)
196int 196int
197x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id) 197x_bitmap_pixmap (FRAME_PTR f, ptrdiff_t id)
198{ 198{
199 return (int) FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap; 199 return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
200} 200}
201#endif 201#endif
202 202
@@ -216,15 +216,6 @@ x_allocate_bitmap_record (FRAME_PTR f)
216 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f); 216 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
217 ptrdiff_t i; 217 ptrdiff_t i;
218 218
219 if (dpyinfo->bitmaps == NULL)
220 {
221 dpyinfo->bitmaps_size = 10;
222 dpyinfo->bitmaps
223 = (Bitmap_Record *) xmalloc (dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
224 dpyinfo->bitmaps_last = 1;
225 return 1;
226 }
227
228 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size) 219 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
229 return ++dpyinfo->bitmaps_last; 220 return ++dpyinfo->bitmaps_last;
230 221
@@ -232,20 +223,16 @@ x_allocate_bitmap_record (FRAME_PTR f)
232 if (dpyinfo->bitmaps[i].refcount == 0) 223 if (dpyinfo->bitmaps[i].refcount == 0)
233 return i + 1; 224 return i + 1;
234 225
235 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (Bitmap_Record) / 2 226 dpyinfo->bitmaps =
236 < dpyinfo->bitmaps_size) 227 xpalloc (dpyinfo->bitmaps, &dpyinfo->bitmaps_size,
237 memory_full (SIZE_MAX); 228 10, -1, sizeof *dpyinfo->bitmaps);
238 dpyinfo->bitmaps_size *= 2;
239 dpyinfo->bitmaps
240 = (Bitmap_Record *) xrealloc (dpyinfo->bitmaps,
241 dpyinfo->bitmaps_size * sizeof (Bitmap_Record));
242 return ++dpyinfo->bitmaps_last; 229 return ++dpyinfo->bitmaps_last;
243} 230}
244 231
245/* Add one reference to the reference count of the bitmap with id ID. */ 232/* Add one reference to the reference count of the bitmap with id ID. */
246 233
247void 234void
248x_reference_bitmap (FRAME_PTR f, int id) 235x_reference_bitmap (FRAME_PTR f, ptrdiff_t id)
249{ 236{
250 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount; 237 ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
251} 238}
@@ -807,29 +794,30 @@ parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
807 break; 794 break;
808 795
809 case IMAGE_POSITIVE_INTEGER_VALUE: 796 case IMAGE_POSITIVE_INTEGER_VALUE:
810 if (!INTEGERP (value) || XINT (value) <= 0) 797 if (! RANGED_INTEGERP (1, value, INT_MAX))
811 return 0; 798 return 0;
812 break; 799 break;
813 800
814 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR: 801 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
815 if (INTEGERP (value) && XINT (value) >= 0) 802 if (RANGED_INTEGERP (1, value, INT_MAX))
816 break; 803 break;
817 if (CONSP (value) 804 if (CONSP (value)
818 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value)) 805 && RANGED_INTEGERP (1, XCAR (value), INT_MAX)
819 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0) 806 && RANGED_INTEGERP (1, XCDR (value), INT_MAX))
820 break; 807 break;
821 return 0; 808 return 0;
822 809
823 case IMAGE_ASCENT_VALUE: 810 case IMAGE_ASCENT_VALUE:
824 if (SYMBOLP (value) && EQ (value, Qcenter)) 811 if (SYMBOLP (value) && EQ (value, Qcenter))
825 break; 812 break;
826 else if (INTEGERP (value) 813 else if (RANGED_INTEGERP (0, value, 100))
827 && XINT (value) >= 0
828 && XINT (value) <= 100)
829 break; 814 break;
830 return 0; 815 return 0;
831 816
832 case IMAGE_NON_NEGATIVE_INTEGER_VALUE: 817 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
818 /* Unlike the other integer-related cases, this one does not
819 verify that VALUE fits in 'int'. This is because callers
820 want EMACS_INT. */
833 if (!INTEGERP (value) || XINT (value) < 0) 821 if (!INTEGERP (value) || XINT (value) < 0)
834 return 0; 822 return 0;
835 break; 823 break;
@@ -849,7 +837,7 @@ parse_image_spec (Lisp_Object spec, struct image_keyword *keywords,
849 break; 837 break;
850 838
851 case IMAGE_INTEGER_VALUE: 839 case IMAGE_INTEGER_VALUE:
852 if (!INTEGERP (value)) 840 if (! TYPE_RANGED_INTEGERP (int, value))
853 return 0; 841 return 0;
854 break; 842 break;
855 843
@@ -919,7 +907,7 @@ or omitted means use the selected frame. */)
919 if (valid_image_p (spec)) 907 if (valid_image_p (spec))
920 { 908 {
921 struct frame *f = check_x_frame (frame); 909 struct frame *f = check_x_frame (frame);
922 int id = lookup_image (f, spec); 910 ptrdiff_t id = lookup_image (f, spec);
923 struct image *img = IMAGE_FROM_ID (f, id); 911 struct image *img = IMAGE_FROM_ID (f, id);
924 int width = img->width + 2 * img->hmargin; 912 int width = img->width + 2 * img->hmargin;
925 int height = img->height + 2 * img->vmargin; 913 int height = img->height + 2 * img->vmargin;
@@ -949,7 +937,7 @@ or omitted means use the selected frame. */)
949 if (valid_image_p (spec)) 937 if (valid_image_p (spec))
950 { 938 {
951 struct frame *f = check_x_frame (frame); 939 struct frame *f = check_x_frame (frame);
952 int id = lookup_image (f, spec); 940 ptrdiff_t id = lookup_image (f, spec);
953 struct image *img = IMAGE_FROM_ID (f, id); 941 struct image *img = IMAGE_FROM_ID (f, id);
954 if (img->mask) 942 if (img->mask)
955 mask = Qt; 943 mask = Qt;
@@ -972,7 +960,7 @@ or omitted means use the selected frame. */)
972 if (valid_image_p (spec)) 960 if (valid_image_p (spec))
973 { 961 {
974 struct frame *f = check_x_frame (frame); 962 struct frame *f = check_x_frame (frame);
975 int id = lookup_image (f, spec); 963 ptrdiff_t id = lookup_image (f, spec);
976 struct image *img = IMAGE_FROM_ID (f, id); 964 struct image *img = IMAGE_FROM_ID (f, id);
977 ext = img->lisp_data; 965 ext = img->lisp_data;
978 } 966 }
@@ -1125,7 +1113,7 @@ image_ascent (struct image *img, struct face *face, struct glyph_slice *slice)
1125 ascent = height / 2; 1113 ascent = height / 2;
1126 } 1114 }
1127 else 1115 else
1128 ascent = (int) (height * img->ascent / 100.0); 1116 ascent = height * (img->ascent / 100.0);
1129 1117
1130 return ascent; 1118 return ascent;
1131} 1119}
@@ -1371,11 +1359,12 @@ x_alloc_image_color (struct frame *f, struct image *img, Lisp_Object color_name,
1371 { 1359 {
1372 /* This isn't called frequently so we get away with simply 1360 /* This isn't called frequently so we get away with simply
1373 reallocating the color vector to the needed size, here. */ 1361 reallocating the color vector to the needed size, here. */
1374 ++img->ncolors; 1362 ptrdiff_t ncolors = img->ncolors + 1;
1375 img->colors = 1363 img->colors =
1376 (unsigned long *) xrealloc (img->colors, 1364 (unsigned long *) xrealloc (img->colors,
1377 img->ncolors * sizeof *img->colors); 1365 ncolors * sizeof *img->colors);
1378 img->colors[img->ncolors - 1] = color.pixel; 1366 img->colors[ncolors - 1] = color.pixel;
1367 img->ncolors = ncolors;
1379 result = color.pixel; 1368 result = color.pixel;
1380 } 1369 }
1381 else 1370 else
@@ -1403,8 +1392,9 @@ make_image_cache (void)
1403 int size; 1392 int size;
1404 1393
1405 memset (c, 0, sizeof *c); 1394 memset (c, 0, sizeof *c);
1406 c->size = 50; 1395 size = 50;
1407 c->images = (struct image **) xmalloc (c->size * sizeof *c->images); 1396 c->images = (struct image **) xmalloc (size * sizeof *c->images);
1397 c->size = size;
1408 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets; 1398 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
1409 c->buckets = (struct image **) xmalloc (size); 1399 c->buckets = (struct image **) xmalloc (size);
1410 memset (c->buckets, 0, size); 1400 memset (c->buckets, 0, size);
@@ -1470,7 +1460,7 @@ free_image_cache (struct frame *f)
1470 struct image_cache *c = FRAME_IMAGE_CACHE (f); 1460 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1471 if (c) 1461 if (c)
1472 { 1462 {
1473 int i; 1463 ptrdiff_t i;
1474 1464
1475 /* Cache should not be referenced by any frame when freed. */ 1465 /* Cache should not be referenced by any frame when freed. */
1476 xassert (c->refcount == 0); 1466 xassert (c->refcount == 0);
@@ -1500,7 +1490,7 @@ clear_image_cache (struct frame *f, Lisp_Object filter)
1500 1490
1501 if (c) 1491 if (c)
1502 { 1492 {
1503 int i, nfreed = 0; 1493 ptrdiff_t i, nfreed = 0;
1504 1494
1505 /* Block input so that we won't be interrupted by a SIGIO 1495 /* Block input so that we won't be interrupted by a SIGIO
1506 while being in an inconsistent state. */ 1496 while being in an inconsistent state. */
@@ -1524,8 +1514,8 @@ clear_image_cache (struct frame *f, Lisp_Object filter)
1524 { 1514 {
1525 /* Free cache based on timestamp. */ 1515 /* Free cache based on timestamp. */
1526 EMACS_TIME t; 1516 EMACS_TIME t;
1527 time_t old; 1517 double old, delay;
1528 int delay, nimages = 0; 1518 ptrdiff_t nimages = 0;
1529 1519
1530 for (i = 0; i < c->used; ++i) 1520 for (i = 0; i < c->used; ++i)
1531 if (c->images[i]) 1521 if (c->images[i])
@@ -1533,9 +1523,10 @@ clear_image_cache (struct frame *f, Lisp_Object filter)
1533 1523
1534 /* If the number of cached images has grown unusually large, 1524 /* If the number of cached images has grown unusually large,
1535 decrease the cache eviction delay (Bug#6230). */ 1525 decrease the cache eviction delay (Bug#6230). */
1536 delay = XFASTINT (Vimage_cache_eviction_delay); 1526 delay = XINT (Vimage_cache_eviction_delay);
1537 if (nimages > 40) 1527 if (nimages > 40)
1538 delay = max (1, 1600 * delay / (nimages*nimages)); 1528 delay = 1600 * delay / nimages / nimages;
1529 delay = max (delay, 1);
1539 1530
1540 EMACS_GET_TIME (t); 1531 EMACS_GET_TIME (t);
1541 old = EMACS_SECS (t) - delay; 1532 old = EMACS_SECS (t) - delay;
@@ -1711,7 +1702,7 @@ postprocess_image (struct frame *f, struct image *img)
1711/* Return the id of image with Lisp specification SPEC on frame F. 1702/* Return the id of image with Lisp specification SPEC on frame F.
1712 SPEC must be a valid Lisp image specification (see valid_image_p). */ 1703 SPEC must be a valid Lisp image specification (see valid_image_p). */
1713 1704
1714int 1705ptrdiff_t
1715lookup_image (struct frame *f, Lisp_Object spec) 1706lookup_image (struct frame *f, Lisp_Object spec)
1716{ 1707{
1717 struct image *img; 1708 struct image *img;
@@ -1770,15 +1761,12 @@ lookup_image (struct frame *f, Lisp_Object spec)
1770 img->ascent = CENTERED_IMAGE_ASCENT; 1761 img->ascent = CENTERED_IMAGE_ASCENT;
1771 1762
1772 margin = image_spec_value (spec, QCmargin, NULL); 1763 margin = image_spec_value (spec, QCmargin, NULL);
1773 if (INTEGERP (margin) && XINT (margin) >= 0) 1764 if (INTEGERP (margin))
1774 img->vmargin = img->hmargin = XFASTINT (margin); 1765 img->vmargin = img->hmargin = XFASTINT (margin);
1775 else if (CONSP (margin) && INTEGERP (XCAR (margin)) 1766 else if (CONSP (margin))
1776 && INTEGERP (XCDR (margin)))
1777 { 1767 {
1778 if (XINT (XCAR (margin)) > 0) 1768 img->hmargin = XFASTINT (XCAR (margin));
1779 img->hmargin = XFASTINT (XCAR (margin)); 1769 img->vmargin = XFASTINT (XCDR (margin));
1780 if (XINT (XCDR (margin)) > 0)
1781 img->vmargin = XFASTINT (XCDR (margin));
1782 } 1770 }
1783 1771
1784 relief = image_spec_value (spec, QCrelief, NULL); 1772 relief = image_spec_value (spec, QCrelief, NULL);
@@ -1825,7 +1813,7 @@ static void
1825cache_image (struct frame *f, struct image *img) 1813cache_image (struct frame *f, struct image *img)
1826{ 1814{
1827 struct image_cache *c = FRAME_IMAGE_CACHE (f); 1815 struct image_cache *c = FRAME_IMAGE_CACHE (f);
1828 int i; 1816 ptrdiff_t i;
1829 1817
1830 /* Find a free slot in c->images. */ 1818 /* Find a free slot in c->images. */
1831 for (i = 0; i < c->used; ++i) 1819 for (i = 0; i < c->used; ++i)
@@ -1834,13 +1822,7 @@ cache_image (struct frame *f, struct image *img)
1834 1822
1835 /* If no free slot found, maybe enlarge c->images. */ 1823 /* If no free slot found, maybe enlarge c->images. */
1836 if (i == c->used && c->used == c->size) 1824 if (i == c->used && c->used == c->size)
1837 { 1825 c->images = xpalloc (c->images, &c->size, 1, -1, sizeof *c->images);
1838 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *c->images / 2 < c->size)
1839 memory_full (SIZE_MAX);
1840 c->size *= 2;
1841 c->images = (struct image **) xrealloc (c->images,
1842 c->size * sizeof *c->images);
1843 }
1844 1826
1845 /* Add IMG to c->images, and assign IMG an id. */ 1827 /* Add IMG to c->images, and assign IMG an id. */
1846 c->images[i] = img; 1828 c->images[i] = img;
@@ -1879,7 +1861,7 @@ mark_image_cache (struct image_cache *c)
1879{ 1861{
1880 if (c) 1862 if (c)
1881 { 1863 {
1882 int i; 1864 ptrdiff_t i;
1883 for (i = 0; i < c->used; ++i) 1865 for (i = 0; i < c->used; ++i)
1884 if (c->images[i]) 1866 if (c->images[i])
1885 mark_image (c->images[i]); 1867 mark_image (c->images[i]);
@@ -2076,7 +2058,7 @@ x_create_x_image_and_pixmap (struct frame *f, int width, int height, int depth,
2076 DWORD err = GetLastError (); 2058 DWORD err = GetLastError ();
2077 Lisp_Object errcode; 2059 Lisp_Object errcode;
2078 /* All system errors are < 10000, so the following is safe. */ 2060 /* All system errors are < 10000, so the following is safe. */
2079 XSETINT (errcode, (int) err); 2061 XSETINT (errcode, err);
2080 image_error ("Unable to create bitmap, error code %d", errcode, Qnil); 2062 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
2081 x_destroy_x_image (*ximg); 2063 x_destroy_x_image (*ximg);
2082 return 0; 2064 return 0;
@@ -2355,7 +2337,7 @@ xbm_image_p (Lisp_Object object)
2355 else 2337 else
2356 { 2338 {
2357 Lisp_Object data; 2339 Lisp_Object data;
2358 EMACS_INT width, height; 2340 int width, height;
2359 2341
2360 /* Entries for `:width', `:height' and `:data' must be present. */ 2342 /* Entries for `:width', `:height' and `:data' must be present. */
2361 if (!kw[XBM_WIDTH].count 2343 if (!kw[XBM_WIDTH].count
@@ -3587,9 +3569,8 @@ xpm_load (struct frame *f, struct image *img)
3587#endif /* HAVE_NTGUI */ 3569#endif /* HAVE_NTGUI */
3588 3570
3589 /* Remember allocated colors. */ 3571 /* Remember allocated colors. */
3572 img->colors = xnmalloc (attrs.nalloc_pixels, sizeof *img->colors);
3590 img->ncolors = attrs.nalloc_pixels; 3573 img->ncolors = attrs.nalloc_pixels;
3591 img->colors = (unsigned long *) xmalloc (img->ncolors
3592 * sizeof *img->colors);
3593 for (i = 0; i < attrs.nalloc_pixels; ++i) 3574 for (i = 0; i < attrs.nalloc_pixels; ++i)
3594 { 3575 {
3595 img->colors[i] = attrs.alloc_pixels[i]; 3576 img->colors[i] = attrs.alloc_pixels[i];
@@ -3813,8 +3794,8 @@ xpm_get_color_table_h (Lisp_Object color_table,
3813 int chars_len) 3794 int chars_len)
3814{ 3795{
3815 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table); 3796 struct Lisp_Hash_Table *table = XHASH_TABLE (color_table);
3816 int i = hash_lookup (table, make_unibyte_string (chars_start, chars_len), 3797 ptrdiff_t i =
3817 NULL); 3798 hash_lookup (table, make_unibyte_string (chars_start, chars_len), NULL);
3818 3799
3819 return i >= 0 ? HASH_VALUE (table, i) : Qnil; 3800 return i >= 0 ? HASH_VALUE (table, i) : Qnil;
3820} 3801}
@@ -4163,6 +4144,12 @@ static struct ct_color **ct_table;
4163/* Number of entries in the color table. */ 4144/* Number of entries in the color table. */
4164 4145
4165static int ct_colors_allocated; 4146static int ct_colors_allocated;
4147enum
4148{
4149 ct_colors_allocated_max =
4150 min (INT_MAX,
4151 min (PTRDIFF_MAX, SIZE_MAX) / sizeof (unsigned long))
4152};
4166 4153
4167/* Initialize the color table. */ 4154/* Initialize the color table. */
4168 4155
@@ -4249,7 +4236,14 @@ lookup_rgb_color (struct frame *f, int r, int g, int b)
4249 XColor color; 4236 XColor color;
4250 Colormap cmap; 4237 Colormap cmap;
4251 int rc; 4238 int rc;
4239#else
4240 COLORREF color;
4241#endif
4252 4242
4243 if (ct_colors_allocated_max <= ct_colors_allocated)
4244 return FRAME_FOREGROUND_PIXEL (f);
4245
4246#ifdef HAVE_X_WINDOWS
4253 color.red = r; 4247 color.red = r;
4254 color.green = g; 4248 color.green = g;
4255 color.blue = b; 4249 color.blue = b;
@@ -4271,7 +4265,6 @@ lookup_rgb_color (struct frame *f, int r, int g, int b)
4271 return FRAME_FOREGROUND_PIXEL (f); 4265 return FRAME_FOREGROUND_PIXEL (f);
4272 4266
4273#else 4267#else
4274 COLORREF color;
4275#ifdef HAVE_NTGUI 4268#ifdef HAVE_NTGUI
4276 color = PALETTERGB (r, g, b); 4269 color = PALETTERGB (r, g, b);
4277#else 4270#else
@@ -4312,6 +4305,9 @@ lookup_pixel_color (struct frame *f, unsigned long pixel)
4312 Colormap cmap; 4305 Colormap cmap;
4313 int rc; 4306 int rc;
4314 4307
4308 if (ct_colors_allocated_max <= ct_colors_allocated)
4309 return FRAME_FOREGROUND_PIXEL (f);
4310
4315#ifdef HAVE_X_WINDOWS 4311#ifdef HAVE_X_WINDOWS
4316 cmap = FRAME_X_COLORMAP (f); 4312 cmap = FRAME_X_COLORMAP (f);
4317 color.pixel = pixel; 4313 color.pixel = pixel;
@@ -4450,7 +4446,9 @@ x_to_xcolors (struct frame *f, struct image *img, int rgb_p)
4450 HGDIOBJ prev; 4446 HGDIOBJ prev;
4451#endif /* HAVE_NTGUI */ 4447#endif /* HAVE_NTGUI */
4452 4448
4453 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors); 4449 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *colors / img->width < img->height)
4450 memory_full (SIZE_MAX);
4451 colors = (XColor *) xmalloc (sizeof *colors * img->width * img->height);
4454 4452
4455#ifndef HAVE_NTGUI 4453#ifndef HAVE_NTGUI
4456 /* Get the X image IMG->pixmap. */ 4454 /* Get the X image IMG->pixmap. */
@@ -4602,7 +4600,9 @@ x_detect_edges (struct frame *f, struct image *img, int *matrix, int color_adjus
4602 4600
4603#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X)) 4601#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
4604 4602
4605 new = (XColor *) xmalloc (img->width * img->height * sizeof *new); 4603 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *new / img->width < img->height)
4604 memory_full (SIZE_MAX);
4605 new = (XColor *) xmalloc (sizeof *new * img->width * img->height);
4606 4606
4607 for (y = 0; y < img->height; ++y) 4607 for (y = 0; y < img->height; ++y)
4608 { 4608 {
@@ -5880,7 +5880,7 @@ png_load (struct frame *f, struct image *img)
5880 5880
5881 for (x = 0; x < width; ++x) 5881 for (x = 0; x < width; ++x)
5882 { 5882 {
5883 unsigned r, g, b; 5883 int r, g, b;
5884 5884
5885 r = *p++ << 8; 5885 r = *p++ << 8;
5886 g = *p++ << 8; 5886 g = *p++ << 8;
@@ -6745,17 +6745,29 @@ tiff_size_of_memory (thandle_t data)
6745} 6745}
6746 6746
6747 6747
6748static void tiff_handler (const char *, const char *, const char *, va_list)
6749 ATTRIBUTE_FORMAT_PRINTF (3, 0);
6750static void
6751tiff_handler (const char *log_format, const char *title,
6752 const char *format, va_list ap)
6753{
6754 /* doprnt is not suitable here, as TIFF handlers are called from
6755 libtiff and are passed arbitrary printf directives. Instead, use
6756 vsnprintf, taking care to be portable to nonstandard environments
6757 where vsnprintf returns -1 on buffer overflow. Since it's just a
6758 log entry, it's OK to truncate it. */
6759 char buf[4000];
6760 int len = vsnprintf (buf, sizeof buf, format, ap);
6761 add_to_log (log_format, build_string (title),
6762 make_string (buf, max (0, min (len, sizeof buf - 1))));
6763}
6764
6748static void tiff_error_handler (const char *, const char *, va_list) 6765static void tiff_error_handler (const char *, const char *, va_list)
6749 ATTRIBUTE_FORMAT_PRINTF (2, 0); 6766 ATTRIBUTE_FORMAT_PRINTF (2, 0);
6750static void 6767static void
6751tiff_error_handler (const char *title, const char *format, va_list ap) 6768tiff_error_handler (const char *title, const char *format, va_list ap)
6752{ 6769{
6753 char buf[512]; 6770 tiff_handler ("TIFF error: %s %s", title, format, ap);
6754 int len;
6755
6756 len = sprintf (buf, "TIFF error: %s ", title);
6757 vsprintf (buf + len, format, ap);
6758 add_to_log (buf, Qnil, Qnil);
6759} 6771}
6760 6772
6761 6773
@@ -6764,12 +6776,7 @@ static void tiff_warning_handler (const char *, const char *, va_list)
6764static void 6776static void
6765tiff_warning_handler (const char *title, const char *format, va_list ap) 6777tiff_warning_handler (const char *title, const char *format, va_list ap)
6766{ 6778{
6767 char buf[512]; 6779 tiff_handler ("TIFF warning: %s %s", title, format, ap);
6768 int len;
6769
6770 len = sprintf (buf, "TIFF warning: %s ", title);
6771 vsprintf (buf + len, format, ap);
6772 add_to_log (buf, Qnil, Qnil);
6773} 6780}
6774 6781
6775 6782
@@ -6845,8 +6852,9 @@ tiff_load (struct frame *f, struct image *img)
6845 image = image_spec_value (img->spec, QCindex, NULL); 6852 image = image_spec_value (img->spec, QCindex, NULL);
6846 if (INTEGERP (image)) 6853 if (INTEGERP (image))
6847 { 6854 {
6848 int ino = XFASTINT (image); 6855 EMACS_INT ino = XFASTINT (image);
6849 if (!fn_TIFFSetDirectory (tiff, ino)) 6856 if (! (TYPE_MINIMUM (tdir_t) <= ino && ino <= TYPE_MAXIMUM (tdir_t)
6857 && fn_TIFFSetDirectory (tiff, ino)))
6850 { 6858 {
6851 image_error ("Invalid image number `%s' in image `%s'", 6859 image_error ("Invalid image number `%s' in image `%s'",
6852 image, img->spec); 6860 image, img->spec);
@@ -7144,7 +7152,7 @@ gif_load (struct frame *f, struct image *img)
7144 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL); 7152 Lisp_Object specified_file = image_spec_value (img->spec, QCfile, NULL);
7145 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL); 7153 Lisp_Object specified_data = image_spec_value (img->spec, QCdata, NULL);
7146 unsigned long bgcolor = 0; 7154 unsigned long bgcolor = 0;
7147 int idx; 7155 EMACS_INT idx;
7148 7156
7149 if (NILP (specified_data)) 7157 if (NILP (specified_data))
7150 { 7158 {
@@ -7379,7 +7387,7 @@ gif_load (struct frame *f, struct image *img)
7379 img->lisp_data = Qnil; 7387 img->lisp_data = Qnil;
7380 if (gif->SavedImages[idx].ExtensionBlockCount > 0) 7388 if (gif->SavedImages[idx].ExtensionBlockCount > 0)
7381 { 7389 {
7382 unsigned int delay = 0; 7390 int delay = 0;
7383 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks; 7391 ExtensionBlock *ext = gif->SavedImages[idx].ExtensionBlocks;
7384 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++) 7392 for (i = 0; i < gif->SavedImages[idx].ExtensionBlockCount; i++, ext++)
7385 /* Append (... FUNCTION "BYTES") */ 7393 /* Append (... FUNCTION "BYTES") */
@@ -7400,7 +7408,7 @@ gif_load (struct frame *f, struct image *img)
7400 if (delay) 7408 if (delay)
7401 img->lisp_data 7409 img->lisp_data
7402 = Fcons (Qdelay, 7410 = Fcons (Qdelay,
7403 Fcons (make_float (((double) delay) * 0.01), 7411 Fcons (make_float (delay / 100.0),
7404 img->lisp_data)); 7412 img->lisp_data));
7405 } 7413 }
7406 7414
@@ -7576,10 +7584,10 @@ imagemagick_load_image (struct frame *f, struct image *img,
7576 Lisp_Object image; 7584 Lisp_Object image;
7577 Lisp_Object value; 7585 Lisp_Object value;
7578 Lisp_Object crop; 7586 Lisp_Object crop;
7579 long ino; 7587 EMACS_INT ino;
7580 int desired_width, desired_height; 7588 int desired_width, desired_height;
7581 double rotation; 7589 double rotation;
7582 int imagemagick_rendermethod; 7590 EMACS_INT imagemagick_rendermethod;
7583 int pixelwidth; 7591 int pixelwidth;
7584 ImageInfo *image_info; 7592 ImageInfo *image_info;
7585 ExceptionInfo *exception; 7593 ExceptionInfo *exception;
@@ -7606,7 +7614,7 @@ imagemagick_load_image (struct frame *f, struct image *img,
7606 status = MagickPingImageBlob (ping_wand, contents, size); 7614 status = MagickPingImageBlob (ping_wand, contents, size);
7607 } 7615 }
7608 7616
7609 if (ino >= MagickGetNumberImages (ping_wand)) 7617 if (! (0 <= ino && ino < MagickGetNumberImages (ping_wand)))
7610 { 7618 {
7611 image_error ("Invalid image number `%s' in image `%s'", 7619 image_error ("Invalid image number `%s' in image `%s'",
7612 image, img->spec); 7620 image, img->spec);
@@ -7681,28 +7689,28 @@ imagemagick_load_image (struct frame *f, struct image *img,
7681 efficient. */ 7689 efficient. */
7682 crop = image_spec_value (img->spec, QCcrop, NULL); 7690 crop = image_spec_value (img->spec, QCcrop, NULL);
7683 7691
7684 if (CONSP (crop) && INTEGERP (XCAR (crop))) 7692 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7685 { 7693 {
7686 /* After some testing, it seems MagickCropImage is the fastest crop 7694 /* After some testing, it seems MagickCropImage is the fastest crop
7687 function in ImageMagick. This crop function seems to do less copying 7695 function in ImageMagick. This crop function seems to do less copying
7688 than the alternatives, but it still reads the entire image into memory 7696 than the alternatives, but it still reads the entire image into memory
7689 before croping, which is aparently difficult to avoid when using 7697 before cropping, which is apparently difficult to avoid when using
7690 imagemagick. */ 7698 imagemagick. */
7691 int w, h; 7699 size_t crop_width = XINT (XCAR (crop));
7692 w = XFASTINT (XCAR (crop));
7693 crop = XCDR (crop); 7700 crop = XCDR (crop);
7694 if (CONSP (crop) && INTEGERP (XCAR (crop))) 7701 if (CONSP (crop) && TYPE_RANGED_INTEGERP (size_t, XCAR (crop)))
7695 { 7702 {
7696 h = XFASTINT (XCAR (crop)); 7703 size_t crop_height = XINT (XCAR (crop));
7697 crop = XCDR (crop); 7704 crop = XCDR (crop);
7698 if (CONSP (crop) && INTEGERP (XCAR (crop))) 7705 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7699 { 7706 {
7700 x = XFASTINT (XCAR (crop)); 7707 ssize_t crop_x = XINT (XCAR (crop));
7701 crop = XCDR (crop); 7708 crop = XCDR (crop);
7702 if (CONSP (crop) && INTEGERP (XCAR (crop))) 7709 if (CONSP (crop) && TYPE_RANGED_INTEGERP (ssize_t, XCAR (crop)))
7703 { 7710 {
7704 y = XFASTINT (XCAR (crop)); 7711 ssize_t crop_y = XINT (XCAR (crop));
7705 MagickCropImage (image_wand, w, h, x, y); 7712 MagickCropImage (image_wand, crop_width, crop_height,
7713 crop_x, crop_y);
7706 } 7714 }
7707 } 7715 }
7708 } 7716 }
@@ -7748,9 +7756,11 @@ imagemagick_load_image (struct frame *f, struct image *img,
7748 7756
7749 init_color_table (); 7757 init_color_table ();
7750 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type) 7758 imagemagick_rendermethod = (INTEGERP (Vimagemagick_render_type)
7751 ? XFASTINT (Vimagemagick_render_type) : 0); 7759 ? XINT (Vimagemagick_render_type) : 0);
7752 if (imagemagick_rendermethod == 0) 7760 if (imagemagick_rendermethod == 0)
7753 { 7761 {
7762 size_t image_height;
7763
7754 /* Try to create a x pixmap to hold the imagemagick pixmap. */ 7764 /* Try to create a x pixmap to hold the imagemagick pixmap. */
7755 if (!x_create_x_image_and_pixmap (f, width, height, 0, 7765 if (!x_create_x_image_and_pixmap (f, width, height, 0,
7756 &ximg, &img->pixmap)) 7766 &ximg, &img->pixmap))
@@ -7779,7 +7789,8 @@ imagemagick_load_image (struct frame *f, struct image *img,
7779 goto imagemagick_error; 7789 goto imagemagick_error;
7780 } 7790 }
7781 7791
7782 for (y = 0; y < (long) MagickGetImageHeight (image_wand); y++) 7792 image_height = MagickGetImageHeight (image_wand);
7793 for (y = 0; y < image_height; y++)
7783 { 7794 {
7784 pixels = PixelGetNextIteratorRow (iterator, &width); 7795 pixels = PixelGetNextIteratorRow (iterator, &width);
7785 if (pixels == (PixelWand **) NULL) 7796 if (pixels == (PixelWand **) NULL)
@@ -8285,10 +8296,10 @@ svg_load_image (struct frame *f, /* Pointer to emacs frame structure. *
8285 { 8296 {
8286 for (x = 0; x < width; ++x) 8297 for (x = 0; x < width; ++x)
8287 { 8298 {
8288 unsigned red; 8299 int red;
8289 unsigned green; 8300 int green;
8290 unsigned blue; 8301 int blue;
8291 unsigned opacity; 8302 int opacity;
8292 8303
8293 red = *pixels++; 8304 red = *pixels++;
8294 green = *pixels++; 8305 green = *pixels++;
@@ -8469,7 +8480,8 @@ gs_image_p (Lisp_Object object)
8469static int 8480static int
8470gs_load (struct frame *f, struct image *img) 8481gs_load (struct frame *f, struct image *img)
8471{ 8482{
8472 char buffer[100]; 8483 uprintmax_t printnum1, printnum2;
8484 char buffer[sizeof " " + INT_STRLEN_BOUND (printmax_t)];
8473 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width; 8485 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
8474 Lisp_Object frame; 8486 Lisp_Object frame;
8475 double in_width, in_height; 8487 double in_width, in_height;
@@ -8481,16 +8493,19 @@ gs_load (struct frame *f, struct image *img)
8481 info. */ 8493 info. */
8482 pt_width = image_spec_value (img->spec, QCpt_width, NULL); 8494 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
8483 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0; 8495 in_width = INTEGERP (pt_width) ? XFASTINT (pt_width) / 72.0 : 0;
8484 img->width = in_width * FRAME_X_DISPLAY_INFO (f)->resx; 8496 in_width *= FRAME_X_DISPLAY_INFO (f)->resx;
8485 pt_height = image_spec_value (img->spec, QCpt_height, NULL); 8497 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
8486 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0; 8498 in_height = INTEGERP (pt_height) ? XFASTINT (pt_height) / 72.0 : 0;
8487 img->height = in_height * FRAME_X_DISPLAY_INFO (f)->resy; 8499 in_height *= FRAME_X_DISPLAY_INFO (f)->resy;
8488 8500
8489 if (!check_image_size (f, img->width, img->height)) 8501 if (! (in_width <= INT_MAX && in_height <= INT_MAX
8502 && check_image_size (f, in_width, in_height)))
8490 { 8503 {
8491 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil); 8504 image_error ("Invalid image size (see `max-image-size')", Qnil, Qnil);
8492 return 0; 8505 return 0;
8493 } 8506 }
8507 img->width = in_width;
8508 img->height = in_height;
8494 8509
8495 /* Create the pixmap. */ 8510 /* Create the pixmap. */
8496 xassert (img->pixmap == NO_PIXMAP); 8511 xassert (img->pixmap == NO_PIXMAP);
@@ -8515,14 +8530,14 @@ gs_load (struct frame *f, struct image *img)
8515 if successful. We do not record_unwind_protect here because 8530 if successful. We do not record_unwind_protect here because
8516 other places in redisplay like calling window scroll functions 8531 other places in redisplay like calling window scroll functions
8517 don't either. Let the Lisp loader use `unwind-protect' instead. */ 8532 don't either. Let the Lisp loader use `unwind-protect' instead. */
8518 sprintf (buffer, "%lu %lu", 8533 printnum1 = FRAME_X_WINDOW (f);
8519 (unsigned long) FRAME_X_WINDOW (f), 8534 printnum2 = img->pixmap;
8520 (unsigned long) img->pixmap); 8535 sprintf (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8521 window_and_pixmap_id = build_string (buffer); 8536 window_and_pixmap_id = build_string (buffer);
8522 8537
8523 sprintf (buffer, "%lu %lu", 8538 printnum1 = FRAME_FOREGROUND_PIXEL (f);
8524 FRAME_FOREGROUND_PIXEL (f), 8539 printnum2 = FRAME_BACKGROUND_PIXEL (f);
8525 FRAME_BACKGROUND_PIXEL (f)); 8540 sprintf (buffer, "%"pMu" %"pMu, printnum1, printnum2);
8526 pixel_colors = build_string (buffer); 8541 pixel_colors = build_string (buffer);
8527 8542
8528 XSETFRAME (frame, f); 8543 XSETFRAME (frame, f);
@@ -8547,7 +8562,8 @@ void
8547x_kill_gs_process (Pixmap pixmap, struct frame *f) 8562x_kill_gs_process (Pixmap pixmap, struct frame *f)
8548{ 8563{
8549 struct image_cache *c = FRAME_IMAGE_CACHE (f); 8564 struct image_cache *c = FRAME_IMAGE_CACHE (f);
8550 int class, i; 8565 int class;
8566 ptrdiff_t i;
8551 struct image *img; 8567 struct image *img;
8552 8568
8553 /* Find the image containing PIXMAP. */ 8569 /* Find the image containing PIXMAP. */
@@ -8651,7 +8667,7 @@ DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
8651DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "") 8667DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
8652 (Lisp_Object spec) 8668 (Lisp_Object spec)
8653{ 8669{
8654 int id = -1; 8670 ptrdiff_t id = -1;
8655 8671
8656 if (valid_image_p (spec)) 8672 if (valid_image_p (spec))
8657 id = lookup_image (SELECTED_FRAME (), spec); 8673 id = lookup_image (SELECTED_FRAME (), spec);
diff --git a/src/indent.c b/src/indent.c
index 70689311dd5..313315e9081 100644
--- a/src/indent.c
+++ b/src/indent.c
@@ -284,7 +284,7 @@ skip_invisible (EMACS_INT pos, EMACS_INT *next_boundary_p, EMACS_INT to, Lisp_Ob
284 else \ 284 else \
285 { \ 285 { \
286 if (dp != 0 && VECTORP (DISP_CHAR_VECTOR (dp, ch))) \ 286 if (dp != 0 && VECTORP (DISP_CHAR_VECTOR (dp, ch))) \
287 width = ASIZE (DISP_CHAR_VECTOR (dp, ch)); \ 287 width = sanitize_char_width (ASIZE (DISP_CHAR_VECTOR (dp, ch))); \
288 else \ 288 else \
289 width = CHAR_WIDTH (ch); \ 289 width = CHAR_WIDTH (ch); \
290 } \ 290 } \
@@ -318,15 +318,6 @@ invalidate_current_column (void)
318 last_known_column_point = 0; 318 last_known_column_point = 0;
319} 319}
320 320
321/* Return a non-outlandish value for the tab width. */
322
323static int
324sane_tab_width (void)
325{
326 EMACS_INT n = XFASTINT (BVAR (current_buffer, tab_width));
327 return 0 < n && n <= 1000 ? n : 8;
328}
329
330EMACS_INT 321EMACS_INT
331current_column (void) 322current_column (void)
332{ 323{
@@ -335,7 +326,7 @@ current_column (void)
335 register int tab_seen; 326 register int tab_seen;
336 EMACS_INT post_tab; 327 EMACS_INT post_tab;
337 register int c; 328 register int c;
338 int tab_width = sane_tab_width (); 329 int tab_width = SANE_TAB_WIDTH (current_buffer);
339 int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow)); 330 int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow));
340 register struct Lisp_Char_Table *dp = buffer_display_table (); 331 register struct Lisp_Char_Table *dp = buffer_display_table ();
341 332
@@ -515,7 +506,7 @@ check_display_width (EMACS_INT pos, EMACS_INT col, EMACS_INT *endpos)
515static void 506static void
516scan_for_column (EMACS_INT *endpos, EMACS_INT *goalcol, EMACS_INT *prevcol) 507scan_for_column (EMACS_INT *endpos, EMACS_INT *goalcol, EMACS_INT *prevcol)
517{ 508{
518 int tab_width = sane_tab_width (); 509 int tab_width = SANE_TAB_WIDTH (current_buffer);
519 register int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow)); 510 register int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow));
520 register struct Lisp_Char_Table *dp = buffer_display_table (); 511 register struct Lisp_Char_Table *dp = buffer_display_table ();
521 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters)); 512 int multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
@@ -732,7 +723,7 @@ string_display_width (Lisp_Object string, Lisp_Object beg, Lisp_Object end)
732 register int tab_seen; 723 register int tab_seen;
733 int post_tab; 724 int post_tab;
734 register int c; 725 register int c;
735 int tab_width = sane_tab_width (); 726 int tab_width = SANE_TAB_WIDTH (current_buffer);
736 int ctl_arrow = !NILP (current_buffer->ctl_arrow); 727 int ctl_arrow = !NILP (current_buffer->ctl_arrow);
737 register struct Lisp_Char_Table *dp = buffer_display_table (); 728 register struct Lisp_Char_Table *dp = buffer_display_table ();
738 int b, e; 729 int b, e;
@@ -808,7 +799,7 @@ The return value is COLUMN. */)
808{ 799{
809 EMACS_INT mincol; 800 EMACS_INT mincol;
810 register EMACS_INT fromcol; 801 register EMACS_INT fromcol;
811 int tab_width = sane_tab_width (); 802 int tab_width = SANE_TAB_WIDTH (current_buffer);
812 803
813 CHECK_NUMBER (column); 804 CHECK_NUMBER (column);
814 if (NILP (minimum)) 805 if (NILP (minimum))
@@ -867,7 +858,7 @@ static EMACS_INT
867position_indentation (register int pos_byte) 858position_indentation (register int pos_byte)
868{ 859{
869 register EMACS_INT column = 0; 860 register EMACS_INT column = 0;
870 int tab_width = sane_tab_width (); 861 int tab_width = SANE_TAB_WIDTH (current_buffer);
871 register unsigned char *p; 862 register unsigned char *p;
872 register unsigned char *stop; 863 register unsigned char *stop;
873 unsigned char *start; 864 unsigned char *start;
@@ -1116,7 +1107,7 @@ compute_motion (EMACS_INT from, EMACS_INT fromvpos, EMACS_INT fromhpos, int did_
1116 register EMACS_INT pos; 1107 register EMACS_INT pos;
1117 EMACS_INT pos_byte; 1108 EMACS_INT pos_byte;
1118 register int c = 0; 1109 register int c = 0;
1119 int tab_width = sane_tab_width (); 1110 int tab_width = SANE_TAB_WIDTH (current_buffer);
1120 register int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow)); 1111 register int ctl_arrow = !NILP (BVAR (current_buffer, ctl_arrow));
1121 register struct Lisp_Char_Table *dp = window_display_table (win); 1112 register struct Lisp_Char_Table *dp = window_display_table (win);
1122 EMACS_INT selective 1113 EMACS_INT selective
@@ -1432,7 +1423,7 @@ compute_motion (EMACS_INT from, EMACS_INT fromvpos, EMACS_INT fromhpos, int did_
1432 the text character-by-character. */ 1423 the text character-by-character. */
1433 if (current_buffer->width_run_cache && pos >= next_width_run) 1424 if (current_buffer->width_run_cache && pos >= next_width_run)
1434 { 1425 {
1435 EMACS_INT run_end; 1426 ptrdiff_t run_end;
1436 int common_width 1427 int common_width
1437 = region_cache_forward (current_buffer, 1428 = region_cache_forward (current_buffer,
1438 current_buffer->width_run_cache, 1429 current_buffer->width_run_cache,
diff --git a/src/keyboard.c b/src/keyboard.c
index 95f64847a4f..054cd3e9a20 100644
--- a/src/keyboard.c
+++ b/src/keyboard.c
@@ -438,16 +438,16 @@ static void (*keyboard_init_hook) (void);
438static int read_avail_input (int); 438static int read_avail_input (int);
439static void get_input_pending (int *, int); 439static void get_input_pending (int *, int);
440static int readable_events (int); 440static int readable_events (int);
441static Lisp_Object read_char_x_menu_prompt (int, Lisp_Object *, 441static Lisp_Object read_char_x_menu_prompt (ptrdiff_t, Lisp_Object *,
442 Lisp_Object, int *); 442 Lisp_Object, int *);
443static Lisp_Object read_char_minibuf_menu_prompt (int, int, 443static Lisp_Object read_char_minibuf_menu_prompt (int, ptrdiff_t,
444 Lisp_Object *); 444 Lisp_Object *);
445static Lisp_Object make_lispy_event (struct input_event *); 445static Lisp_Object make_lispy_event (struct input_event *);
446#if defined (HAVE_MOUSE) || defined (HAVE_GPM) 446#if defined (HAVE_MOUSE) || defined (HAVE_GPM)
447static Lisp_Object make_lispy_movement (struct frame *, Lisp_Object, 447static Lisp_Object make_lispy_movement (struct frame *, Lisp_Object,
448 enum scroll_bar_part, 448 enum scroll_bar_part,
449 Lisp_Object, Lisp_Object, 449 Lisp_Object, Lisp_Object,
450 unsigned long); 450 Time);
451#endif 451#endif
452static Lisp_Object modify_event_symbol (EMACS_INT, unsigned, Lisp_Object, 452static Lisp_Object modify_event_symbol (EMACS_INT, unsigned, Lisp_Object,
453 Lisp_Object, const char *const *, 453 Lisp_Object, const char *const *,
@@ -1303,7 +1303,7 @@ some_mouse_moved (void)
1303/* This is the actual command reading loop, 1303/* This is the actual command reading loop,
1304 sans error-handling encapsulation. */ 1304 sans error-handling encapsulation. */
1305 1305
1306static int read_key_sequence (Lisp_Object *, size_t, Lisp_Object, 1306static int read_key_sequence (Lisp_Object *, int, Lisp_Object,
1307 int, int, int); 1307 int, int, int);
1308void safe_run_hooks (Lisp_Object); 1308void safe_run_hooks (Lisp_Object);
1309static void adjust_point_for_property (EMACS_INT, int); 1309static void adjust_point_for_property (EMACS_INT, int);
@@ -2270,7 +2270,8 @@ do { if (polling_stopped_here) start_polling (); \
2270 Value is t if we showed a menu and the user rejected it. */ 2270 Value is t if we showed a menu and the user rejected it. */
2271 2271
2272Lisp_Object 2272Lisp_Object
2273read_char (int commandflag, int nmaps, Lisp_Object *maps, Lisp_Object prev_event, 2273read_char (int commandflag, ptrdiff_t nmaps, Lisp_Object *maps,
2274 Lisp_Object prev_event,
2274 int *used_mouse_menu, struct timeval *end_time) 2275 int *used_mouse_menu, struct timeval *end_time)
2275{ 2276{
2276 volatile Lisp_Object c; 2277 volatile Lisp_Object c;
@@ -7421,7 +7422,7 @@ menu_bar_items (Lisp_Object old)
7421{ 7422{
7422 /* The number of keymaps we're scanning right now, and the number of 7423 /* The number of keymaps we're scanning right now, and the number of
7423 keymaps we have allocated space for. */ 7424 keymaps we have allocated space for. */
7424 int nmaps; 7425 ptrdiff_t nmaps;
7425 7426
7426 /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1] 7427 /* maps[0..nmaps-1] are the prefix definitions of KEYBUF[0..t-1]
7427 in the current keymaps, or nil where it is not a prefix. */ 7428 in the current keymaps, or nil where it is not a prefix. */
@@ -7429,7 +7430,7 @@ menu_bar_items (Lisp_Object old)
7429 7430
7430 Lisp_Object def, tail; 7431 Lisp_Object def, tail;
7431 7432
7432 int mapno; 7433 ptrdiff_t mapno;
7433 Lisp_Object oquit; 7434 Lisp_Object oquit;
7434 7435
7435 /* In order to build the menus, we need to call the keymap 7436 /* In order to build the menus, we need to call the keymap
@@ -7474,7 +7475,7 @@ menu_bar_items (Lisp_Object old)
7474 recognized when the menu-bar (or mode-line) is updated, 7475 recognized when the menu-bar (or mode-line) is updated,
7475 which does not normally happen after every command. */ 7476 which does not normally happen after every command. */
7476 Lisp_Object tem; 7477 Lisp_Object tem;
7477 int nminor; 7478 ptrdiff_t nminor;
7478 nminor = current_minor_maps (NULL, &tmaps); 7479 nminor = current_minor_maps (NULL, &tmaps);
7479 maps = (Lisp_Object *) alloca ((nminor + 3) * sizeof (maps[0])); 7480 maps = (Lisp_Object *) alloca ((nminor + 3) * sizeof (maps[0]));
7480 nmaps = 0; 7481 nmaps = 0;
@@ -7978,7 +7979,7 @@ Lisp_Object
7978tool_bar_items (Lisp_Object reuse, int *nitems) 7979tool_bar_items (Lisp_Object reuse, int *nitems)
7979{ 7980{
7980 Lisp_Object *maps; 7981 Lisp_Object *maps;
7981 int nmaps, i; 7982 ptrdiff_t nmaps, i;
7982 Lisp_Object oquit; 7983 Lisp_Object oquit;
7983 Lisp_Object *tmaps; 7984 Lisp_Object *tmaps;
7984 7985
@@ -8018,7 +8019,7 @@ tool_bar_items (Lisp_Object reuse, int *nitems)
8018 recognized when the tool-bar (or mode-line) is updated, 8019 recognized when the tool-bar (or mode-line) is updated,
8019 which does not normally happen after every command. */ 8020 which does not normally happen after every command. */
8020 Lisp_Object tem; 8021 Lisp_Object tem;
8021 int nminor; 8022 ptrdiff_t nminor;
8022 nminor = current_minor_maps (NULL, &tmaps); 8023 nminor = current_minor_maps (NULL, &tmaps);
8023 maps = (Lisp_Object *) alloca ((nminor + 3) * sizeof (maps[0])); 8024 maps = (Lisp_Object *) alloca ((nminor + 3) * sizeof (maps[0]));
8024 nmaps = 0; 8025 nmaps = 0;
@@ -8290,10 +8291,11 @@ parse_tool_bar_item (Lisp_Object key, Lisp_Object item)
8290 Lisp_Object tcapt = PROP (TOOL_BAR_ITEM_CAPTION); 8291 Lisp_Object tcapt = PROP (TOOL_BAR_ITEM_CAPTION);
8291 const char *label = SYMBOLP (tkey) ? SSDATA (SYMBOL_NAME (tkey)) : ""; 8292 const char *label = SYMBOLP (tkey) ? SSDATA (SYMBOL_NAME (tkey)) : "";
8292 const char *capt = STRINGP (tcapt) ? SSDATA (tcapt) : ""; 8293 const char *capt = STRINGP (tcapt) ? SSDATA (tcapt) : "";
8293 EMACS_INT max_lbl = 2 * tool_bar_max_label_size; 8294 ptrdiff_t max_lbl =
8295 2 * max (0, min (tool_bar_max_label_size, STRING_BYTES_BOUND / 2));
8294 char *buf = (char *) xmalloc (max_lbl + 1); 8296 char *buf = (char *) xmalloc (max_lbl + 1);
8295 Lisp_Object new_lbl; 8297 Lisp_Object new_lbl;
8296 size_t caption_len = strlen (capt); 8298 ptrdiff_t caption_len = strlen (capt);
8297 8299
8298 if (caption_len <= max_lbl && capt[0] != '\0') 8300 if (caption_len <= max_lbl && capt[0] != '\0')
8299 { 8301 {
@@ -8306,7 +8308,7 @@ parse_tool_bar_item (Lisp_Object key, Lisp_Object item)
8306 8308
8307 if (strlen (label) <= max_lbl && label[0] != '\0') 8309 if (strlen (label) <= max_lbl && label[0] != '\0')
8308 { 8310 {
8309 int j; 8311 ptrdiff_t j;
8310 if (label != buf) 8312 if (label != buf)
8311 strcpy (buf, label); 8313 strcpy (buf, label);
8312 8314
@@ -8415,10 +8417,10 @@ append_tool_bar_item (void)
8415 and do auto-saving in the inner call of read_char. */ 8417 and do auto-saving in the inner call of read_char. */
8416 8418
8417static Lisp_Object 8419static Lisp_Object
8418read_char_x_menu_prompt (int nmaps, Lisp_Object *maps, Lisp_Object prev_event, 8420read_char_x_menu_prompt (ptrdiff_t nmaps, Lisp_Object *maps,
8419 int *used_mouse_menu) 8421 Lisp_Object prev_event, int *used_mouse_menu)
8420{ 8422{
8421 int mapno; 8423 ptrdiff_t mapno;
8422 8424
8423 if (used_mouse_menu) 8425 if (used_mouse_menu)
8424 *used_mouse_menu = 0; 8426 *used_mouse_menu = 0;
@@ -8446,7 +8448,7 @@ read_char_x_menu_prompt (int nmaps, Lisp_Object *maps, Lisp_Object prev_event,
8446 Lisp_Object *realmaps 8448 Lisp_Object *realmaps
8447 = (Lisp_Object *) alloca (nmaps * sizeof (Lisp_Object)); 8449 = (Lisp_Object *) alloca (nmaps * sizeof (Lisp_Object));
8448 Lisp_Object value; 8450 Lisp_Object value;
8449 int nmaps1 = 0; 8451 ptrdiff_t nmaps1 = 0;
8450 8452
8451 /* Use the maps that are not nil. */ 8453 /* Use the maps that are not nil. */
8452 for (mapno = 0; mapno < nmaps; mapno++) 8454 for (mapno = 0; mapno < nmaps; mapno++)
@@ -8497,17 +8499,18 @@ read_char_x_menu_prompt (int nmaps, Lisp_Object *maps, Lisp_Object prev_event,
8497 We make this bigger when necessary, and never free it. */ 8499 We make this bigger when necessary, and never free it. */
8498static char *read_char_minibuf_menu_text; 8500static char *read_char_minibuf_menu_text;
8499/* Size of that buffer. */ 8501/* Size of that buffer. */
8500static int read_char_minibuf_menu_width; 8502static ptrdiff_t read_char_minibuf_menu_width;
8501 8503
8502static Lisp_Object 8504static Lisp_Object
8503read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps) 8505read_char_minibuf_menu_prompt (int commandflag,
8506 ptrdiff_t nmaps, Lisp_Object *maps)
8504{ 8507{
8505 int mapno; 8508 ptrdiff_t mapno;
8506 register Lisp_Object name; 8509 register Lisp_Object name;
8507 int nlength; 8510 ptrdiff_t nlength;
8508 /* FIXME: Use the minibuffer's frame width. */ 8511 /* FIXME: Use the minibuffer's frame width. */
8509 int width = FRAME_COLS (SELECTED_FRAME ()) - 4; 8512 ptrdiff_t width = FRAME_COLS (SELECTED_FRAME ()) - 4;
8510 int idx = -1; 8513 ptrdiff_t idx = -1;
8511 int nobindings = 1; 8514 int nobindings = 1;
8512 Lisp_Object rest, vector; 8515 Lisp_Object rest, vector;
8513 char *menu; 8516 char *menu;
@@ -8532,16 +8535,13 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8532 8535
8533 /* Make sure we have a big enough buffer for the menu text. */ 8536 /* Make sure we have a big enough buffer for the menu text. */
8534 width = max (width, SBYTES (name)); 8537 width = max (width, SBYTES (name));
8535 if (read_char_minibuf_menu_text == 0) 8538 if (STRING_BYTES_BOUND - 4 < width)
8539 memory_full (SIZE_MAX);
8540 if (width + 4 > read_char_minibuf_menu_width)
8536 { 8541 {
8537 read_char_minibuf_menu_width = width + 4;
8538 read_char_minibuf_menu_text = (char *) xmalloc (width + 4);
8539 }
8540 else if (width + 4 > read_char_minibuf_menu_width)
8541 {
8542 read_char_minibuf_menu_width = width + 4;
8543 read_char_minibuf_menu_text 8542 read_char_minibuf_menu_text
8544 = (char *) xrealloc (read_char_minibuf_menu_text, width + 4); 8543 = (char *) xrealloc (read_char_minibuf_menu_text, width + 4);
8544 read_char_minibuf_menu_width = width + 4;
8545 } 8545 }
8546 menu = read_char_minibuf_menu_text; 8546 menu = read_char_minibuf_menu_text;
8547 8547
@@ -8560,7 +8560,7 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8560 while (1) 8560 while (1)
8561 { 8561 {
8562 int notfirst = 0; 8562 int notfirst = 0;
8563 int i = nlength; 8563 ptrdiff_t i = nlength;
8564 Lisp_Object obj; 8564 Lisp_Object obj;
8565 Lisp_Object orig_defn_macro; 8565 Lisp_Object orig_defn_macro;
8566 8566
@@ -8659,7 +8659,7 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8659 < width 8659 < width
8660 || !notfirst) 8660 || !notfirst)
8661 { 8661 {
8662 int thiswidth; 8662 ptrdiff_t thiswidth;
8663 8663
8664 /* Punctuate between strings. */ 8664 /* Punctuate between strings. */
8665 if (notfirst) 8665 if (notfirst)
@@ -8675,9 +8675,7 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8675 if (! char_matches) 8675 if (! char_matches)
8676 { 8676 {
8677 /* Add as much of string as fits. */ 8677 /* Add as much of string as fits. */
8678 thiswidth = SCHARS (desc); 8678 thiswidth = min (SCHARS (desc), width - i);
8679 if (thiswidth + i > width)
8680 thiswidth = width - i;
8681 memcpy (menu + i, SDATA (desc), thiswidth); 8679 memcpy (menu + i, SDATA (desc), thiswidth);
8682 i += thiswidth; 8680 i += thiswidth;
8683 strcpy (menu + i, " = "); 8681 strcpy (menu + i, " = ");
@@ -8685,9 +8683,7 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8685 } 8683 }
8686 8684
8687 /* Add as much of string as fits. */ 8685 /* Add as much of string as fits. */
8688 thiswidth = SCHARS (s); 8686 thiswidth = min (SCHARS (s), width - i);
8689 if (thiswidth + i > width)
8690 thiswidth = width - i;
8691 memcpy (menu + i, SDATA (s), thiswidth); 8687 memcpy (menu + i, SDATA (s), thiswidth);
8692 i += thiswidth; 8688 i += thiswidth;
8693 menu[i] = 0; 8689 menu[i] = 0;
@@ -8762,10 +8758,10 @@ read_char_minibuf_menu_prompt (int commandflag, int nmaps, Lisp_Object *maps)
8762 NEXT may be the same array as CURRENT. */ 8758 NEXT may be the same array as CURRENT. */
8763 8759
8764static int 8760static int
8765follow_key (Lisp_Object key, int nmaps, Lisp_Object *current, Lisp_Object *defs, 8761follow_key (Lisp_Object key, ptrdiff_t nmaps, Lisp_Object *current,
8766 Lisp_Object *next) 8762 Lisp_Object *defs, Lisp_Object *next)
8767{ 8763{
8768 int i, first_binding; 8764 ptrdiff_t i, first_binding;
8769 8765
8770 first_binding = nmaps; 8766 first_binding = nmaps;
8771 for (i = nmaps - 1; i >= 0; i--) 8767 for (i = nmaps - 1; i >= 0; i--)
@@ -8865,7 +8861,7 @@ access_keymap_keyremap (Lisp_Object map, Lisp_Object key, Lisp_Object prompt,
8865 The return value is non-zero if the remapping actually took place. */ 8861 The return value is non-zero if the remapping actually took place. */
8866 8862
8867static int 8863static int
8868keyremap_step (Lisp_Object *keybuf, size_t bufsize, volatile keyremap *fkey, 8864keyremap_step (Lisp_Object *keybuf, int bufsize, volatile keyremap *fkey,
8869 int input, int doit, int *diff, Lisp_Object prompt) 8865 int input, int doit, int *diff, Lisp_Object prompt)
8870{ 8866{
8871 Lisp_Object next, key; 8867 Lisp_Object next, key;
@@ -8887,7 +8883,7 @@ keyremap_step (Lisp_Object *keybuf, size_t bufsize, volatile keyremap *fkey,
8887 8883
8888 *diff = len - (fkey->end - fkey->start); 8884 *diff = len - (fkey->end - fkey->start);
8889 8885
8890 if (input + *diff >= bufsize) 8886 if (bufsize - input <= *diff)
8891 error ("Key sequence too long"); 8887 error ("Key sequence too long");
8892 8888
8893 /* Shift the keys that follow fkey->end. */ 8889 /* Shift the keys that follow fkey->end. */
@@ -8958,7 +8954,7 @@ keyremap_step (Lisp_Object *keybuf, size_t bufsize, volatile keyremap *fkey,
8958 from the selected window's buffer. */ 8954 from the selected window's buffer. */
8959 8955
8960static int 8956static int
8961read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt, 8957read_key_sequence (Lisp_Object *keybuf, int bufsize, Lisp_Object prompt,
8962 int dont_downcase_last, int can_return_switch_frame, 8958 int dont_downcase_last, int can_return_switch_frame,
8963 int fix_current_buffer) 8959 int fix_current_buffer)
8964{ 8960{
@@ -8975,8 +8971,8 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
8975 8971
8976 /* The number of keymaps we're scanning right now, and the number of 8972 /* The number of keymaps we're scanning right now, and the number of
8977 keymaps we have allocated space for. */ 8973 keymaps we have allocated space for. */
8978 int nmaps; 8974 ptrdiff_t nmaps;
8979 int nmaps_allocated = 0; 8975 ptrdiff_t nmaps_allocated = 0;
8980 8976
8981 /* defs[0..nmaps-1] are the definitions of KEYBUF[0..t-1] in 8977 /* defs[0..nmaps-1] are the definitions of KEYBUF[0..t-1] in
8982 the current keymaps. */ 8978 the current keymaps. */
@@ -9000,7 +8996,7 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
9000 /* The index in submaps[] of the first keymap that has a binding for 8996 /* The index in submaps[] of the first keymap that has a binding for
9001 this key sequence. In other words, the lowest i such that 8997 this key sequence. In other words, the lowest i such that
9002 submaps[i] is non-nil. */ 8998 submaps[i] is non-nil. */
9003 int first_binding; 8999 ptrdiff_t first_binding;
9004 /* Index of the first key that has no binding. 9000 /* Index of the first key that has no binding.
9005 It is useless to try fkey.start larger than that. */ 9001 It is useless to try fkey.start larger than that. */
9006 int first_unbound; 9002 int first_unbound;
@@ -9161,8 +9157,8 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
9161 } 9157 }
9162 else 9158 else
9163 { 9159 {
9164 int nminor; 9160 ptrdiff_t nminor;
9165 int total; 9161 ptrdiff_t total;
9166 Lisp_Object *maps; 9162 Lisp_Object *maps;
9167 9163
9168 nminor = current_minor_maps (0, &maps); 9164 nminor = current_minor_maps (0, &maps);
@@ -9228,7 +9224,8 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
9228 echo_local_start and keys_local_start allow us to throw away 9224 echo_local_start and keys_local_start allow us to throw away
9229 just one key. */ 9225 just one key. */
9230 int echo_local_start IF_LINT (= 0); 9226 int echo_local_start IF_LINT (= 0);
9231 int keys_local_start, local_first_binding; 9227 int keys_local_start;
9228 ptrdiff_t local_first_binding;
9232 9229
9233 eassert (indec.end == t || (indec.end > t && indec.end <= mock_input)); 9230 eassert (indec.end == t || (indec.end > t && indec.end <= mock_input));
9234 eassert (indec.start <= indec.end); 9231 eassert (indec.start <= indec.end);
@@ -9565,7 +9562,7 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
9565 && (NILP (fake_prefixed_keys) 9562 && (NILP (fake_prefixed_keys)
9566 || NILP (Fmemq (key, fake_prefixed_keys)))) 9563 || NILP (Fmemq (key, fake_prefixed_keys))))
9567 { 9564 {
9568 if (t + 1 >= bufsize) 9565 if (bufsize - t <= 1)
9569 error ("Key sequence too long"); 9566 error ("Key sequence too long");
9570 9567
9571 keybuf[t] = posn; 9568 keybuf[t] = posn;
@@ -9646,7 +9643,7 @@ read_key_sequence (Lisp_Object *keybuf, size_t bufsize, Lisp_Object prompt,
9646 insert the dummy prefix event `menu-bar'. */ 9643 insert the dummy prefix event `menu-bar'. */
9647 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar)) 9644 if (EQ (posn, Qmenu_bar) || EQ (posn, Qtool_bar))
9648 { 9645 {
9649 if (t + 1 >= bufsize) 9646 if (bufsize - t <= 1)
9650 error ("Key sequence too long"); 9647 error ("Key sequence too long");
9651 keybuf[t] = posn; 9648 keybuf[t] = posn;
9652 keybuf[t+1] = key; 9649 keybuf[t+1] = key;
diff --git a/src/keyboard.h b/src/keyboard.h
index 69c804c873d..d4339d0529b 100644
--- a/src/keyboard.h
+++ b/src/keyboard.h
@@ -440,7 +440,7 @@ struct input_event;
440 440
441extern Lisp_Object parse_modifiers (Lisp_Object); 441extern Lisp_Object parse_modifiers (Lisp_Object);
442extern Lisp_Object reorder_modifiers (Lisp_Object); 442extern Lisp_Object reorder_modifiers (Lisp_Object);
443extern Lisp_Object read_char (int, int, Lisp_Object *, Lisp_Object, 443extern Lisp_Object read_char (int, ptrdiff_t, Lisp_Object *, Lisp_Object,
444 int *, EMACS_TIME *); 444 int *, EMACS_TIME *);
445extern int parse_solitary_modifier (Lisp_Object symbol); 445extern int parse_solitary_modifier (Lisp_Object symbol);
446 446
diff --git a/src/keymap.c b/src/keymap.c
index 3b0edbf4fb3..32b531daac4 100644
--- a/src/keymap.c
+++ b/src/keymap.c
@@ -1399,7 +1399,7 @@ silly_event_symbol_error (Lisp_Object c)
1399 some systems, static gets macro-defined to be the empty string. 1399 some systems, static gets macro-defined to be the empty string.
1400 Ickypoo. */ 1400 Ickypoo. */
1401static Lisp_Object *cmm_modes = NULL, *cmm_maps = NULL; 1401static Lisp_Object *cmm_modes = NULL, *cmm_maps = NULL;
1402static int cmm_size = 0; 1402static ptrdiff_t cmm_size = 0;
1403 1403
1404/* Store a pointer to an array of the currently active minor modes in 1404/* Store a pointer to an array of the currently active minor modes in
1405 *modeptr, a pointer to an array of the keymaps of the currently 1405 *modeptr, a pointer to an array of the keymaps of the currently
@@ -1419,10 +1419,10 @@ static int cmm_size = 0;
1419 loop. Instead, we'll use realloc/malloc and silently truncate the 1419 loop. Instead, we'll use realloc/malloc and silently truncate the
1420 list, let the key sequence be read, and hope some other piece of 1420 list, let the key sequence be read, and hope some other piece of
1421 code signals the error. */ 1421 code signals the error. */
1422int 1422ptrdiff_t
1423current_minor_maps (Lisp_Object **modeptr, Lisp_Object **mapptr) 1423current_minor_maps (Lisp_Object **modeptr, Lisp_Object **mapptr)
1424{ 1424{
1425 int i = 0; 1425 ptrdiff_t i = 0;
1426 int list_number = 0; 1426 int list_number = 0;
1427 Lisp_Object alist, assoc, var, val; 1427 Lisp_Object alist, assoc, var, val;
1428 Lisp_Object emulation_alists; 1428 Lisp_Object emulation_alists;
@@ -1465,9 +1465,16 @@ current_minor_maps (Lisp_Object **modeptr, Lisp_Object **mapptr)
1465 1465
1466 if (i >= cmm_size) 1466 if (i >= cmm_size)
1467 { 1467 {
1468 int newsize, allocsize; 1468 ptrdiff_t newsize, allocsize;
1469 Lisp_Object *newmodes, *newmaps; 1469 Lisp_Object *newmodes, *newmaps;
1470 1470
1471 /* Check for size calculation overflow. Other code
1472 (e.g., read_key_sequence) adds 3 to the count
1473 later, so subtract 3 from the limit here. */
1474 if (min (PTRDIFF_MAX, SIZE_MAX) / (2 * sizeof *newmodes) - 3
1475 < cmm_size)
1476 break;
1477
1471 newsize = cmm_size == 0 ? 30 : cmm_size * 2; 1478 newsize = cmm_size == 0 ? 30 : cmm_size * 2;
1472 allocsize = newsize * sizeof *newmodes; 1479 allocsize = newsize * sizeof *newmodes;
1473 1480
diff --git a/src/keymap.h b/src/keymap.h
index 2c826b64e1f..ec9d4cadbb1 100644
--- a/src/keymap.h
+++ b/src/keymap.h
@@ -38,7 +38,7 @@ extern Lisp_Object get_keymap (Lisp_Object, int, int);
38EXFUN (Fset_keymap_parent, 2); 38EXFUN (Fset_keymap_parent, 2);
39extern int describe_map_tree (Lisp_Object, int, Lisp_Object, Lisp_Object, 39extern int describe_map_tree (Lisp_Object, int, Lisp_Object, Lisp_Object,
40 const char *, int, int, int, int); 40 const char *, int, int, int, int);
41extern int current_minor_maps (Lisp_Object **, Lisp_Object **); 41extern ptrdiff_t current_minor_maps (Lisp_Object **, Lisp_Object **);
42extern void initial_define_key (Lisp_Object, int, const char *); 42extern void initial_define_key (Lisp_Object, int, const char *);
43extern void initial_define_lispy_key (Lisp_Object, const char *, const char *); 43extern void initial_define_lispy_key (Lisp_Object, const char *, const char *);
44extern void syms_of_keymap (void); 44extern void syms_of_keymap (void);
diff --git a/src/lisp.h b/src/lisp.h
index 14bd429a45e..5ca31132668 100644
--- a/src/lisp.h
+++ b/src/lisp.h
@@ -1708,6 +1708,11 @@ typedef struct {
1708#define NUMBERP(x) (INTEGERP (x) || FLOATP (x)) 1708#define NUMBERP(x) (INTEGERP (x) || FLOATP (x))
1709#define NATNUMP(x) (INTEGERP (x) && XINT (x) >= 0) 1709#define NATNUMP(x) (INTEGERP (x) && XINT (x) >= 0)
1710 1710
1711#define RANGED_INTEGERP(lo, x, hi) \
1712 (INTEGERP (x) && (lo) <= XINT (x) && XINT (x) <= (hi))
1713#define TYPE_RANGED_INTEGERP(type, x) \
1714 RANGED_INTEGERP (TYPE_MINIMUM (type), x, TYPE_MAXIMUM (type))
1715
1711#define INTEGERP(x) (LISP_INT_TAG_P (XTYPE ((x)))) 1716#define INTEGERP(x) (LISP_INT_TAG_P (XTYPE ((x))))
1712#define SYMBOLP(x) (XTYPE ((x)) == Lisp_Symbol) 1717#define SYMBOLP(x) (XTYPE ((x)) == Lisp_Symbol)
1713#define MISCP(x) (XTYPE ((x)) == Lisp_Misc) 1718#define MISCP(x) (XTYPE ((x)) == Lisp_Misc)
@@ -2555,6 +2560,7 @@ extern void syms_of_syntax (void);
2555 2560
2556/* Defined in fns.c */ 2561/* Defined in fns.c */
2557extern Lisp_Object QCrehash_size, QCrehash_threshold; 2562extern Lisp_Object QCrehash_size, QCrehash_threshold;
2563enum { NEXT_ALMOST_PRIME_LIMIT = 11 };
2558extern EMACS_INT next_almost_prime (EMACS_INT); 2564extern EMACS_INT next_almost_prime (EMACS_INT);
2559extern Lisp_Object larger_vector (Lisp_Object, EMACS_INT, Lisp_Object); 2565extern Lisp_Object larger_vector (Lisp_Object, EMACS_INT, Lisp_Object);
2560extern void sweep_weak_hash_tables (void); 2566extern void sweep_weak_hash_tables (void);
@@ -2566,8 +2572,8 @@ EMACS_UINT sxhash (Lisp_Object, int);
2566Lisp_Object make_hash_table (Lisp_Object, Lisp_Object, Lisp_Object, 2572Lisp_Object make_hash_table (Lisp_Object, Lisp_Object, Lisp_Object,
2567 Lisp_Object, Lisp_Object, Lisp_Object, 2573 Lisp_Object, Lisp_Object, Lisp_Object,
2568 Lisp_Object); 2574 Lisp_Object);
2569EMACS_INT hash_lookup (struct Lisp_Hash_Table *, Lisp_Object, EMACS_UINT *); 2575ptrdiff_t hash_lookup (struct Lisp_Hash_Table *, Lisp_Object, EMACS_UINT *);
2570EMACS_INT hash_put (struct Lisp_Hash_Table *, Lisp_Object, Lisp_Object, 2576ptrdiff_t hash_put (struct Lisp_Hash_Table *, Lisp_Object, Lisp_Object,
2571 EMACS_UINT); 2577 EMACS_UINT);
2572void init_weak_hash_tables (void); 2578void init_weak_hash_tables (void);
2573extern void init_fns (void); 2579extern void init_fns (void);
@@ -3573,6 +3579,9 @@ extern int immediate_quit; /* Nonzero means ^G can quit instantly */
3573extern POINTER_TYPE *xmalloc (size_t); 3579extern POINTER_TYPE *xmalloc (size_t);
3574extern POINTER_TYPE *xrealloc (POINTER_TYPE *, size_t); 3580extern POINTER_TYPE *xrealloc (POINTER_TYPE *, size_t);
3575extern void xfree (POINTER_TYPE *); 3581extern void xfree (POINTER_TYPE *);
3582extern void *xnmalloc (ptrdiff_t, ptrdiff_t);
3583extern void *xnrealloc (void *, ptrdiff_t, ptrdiff_t);
3584extern void *xpalloc (void *, ptrdiff_t *, ptrdiff_t, ptrdiff_t, ptrdiff_t);
3576 3585
3577extern char *xstrdup (const char *); 3586extern char *xstrdup (const char *);
3578 3587
@@ -3690,6 +3699,23 @@ extern Lisp_Object safe_alloca_unwind (Lisp_Object);
3690 } \ 3699 } \
3691 } while (0) 3700 } while (0)
3692 3701
3702/* SAFE_NALLOCA sets BUF to a newly allocated array of MULTIPLIER *
3703 NITEMS items, each of the same type as *BUF. MULTIPLIER must
3704 positive. The code is tuned for MULTIPLIER being a constant. */
3705
3706#define SAFE_NALLOCA(buf, multiplier, nitems) \
3707 do { \
3708 if ((nitems) <= MAX_ALLOCA / sizeof *(buf) / (multiplier)) \
3709 (buf) = alloca (sizeof *(buf) * (multiplier) * (nitems)); \
3710 else \
3711 { \
3712 (buf) = xnmalloc (nitems, sizeof *(buf) * (multiplier)); \
3713 sa_must_free = 1; \
3714 record_unwind_protect (safe_alloca_unwind, \
3715 make_save_value (buf, 0)); \
3716 } \
3717 } while (0)
3718
3693/* SAFE_FREE frees xmalloced memory and enables GC as needed. */ 3719/* SAFE_FREE frees xmalloced memory and enables GC as needed. */
3694 3720
3695#define SAFE_FREE() \ 3721#define SAFE_FREE() \
diff --git a/src/lread.c b/src/lread.c
index 6d1a7b102d7..d24da729df6 100644
--- a/src/lread.c
+++ b/src/lread.c
@@ -2637,14 +2637,14 @@ read1 (register Lisp_Object readcharfun, int *pch, int first_in_list)
2637 2637
2638 if (saved_doc_string_size == 0) 2638 if (saved_doc_string_size == 0)
2639 { 2639 {
2640 saved_doc_string = (char *) xmalloc (nskip + extra);
2640 saved_doc_string_size = nskip + extra; 2641 saved_doc_string_size = nskip + extra;
2641 saved_doc_string = (char *) xmalloc (saved_doc_string_size);
2642 } 2642 }
2643 if (nskip > saved_doc_string_size) 2643 if (nskip > saved_doc_string_size)
2644 { 2644 {
2645 saved_doc_string_size = nskip + extra;
2646 saved_doc_string = (char *) xrealloc (saved_doc_string, 2645 saved_doc_string = (char *) xrealloc (saved_doc_string,
2647 saved_doc_string_size); 2646 nskip + extra);
2647 saved_doc_string_size = nskip + extra;
2648 } 2648 }
2649 2649
2650 saved_doc_string_position = file_tell (instream); 2650 saved_doc_string_position = file_tell (instream);
@@ -2907,7 +2907,8 @@ read1 (register Lisp_Object readcharfun, int *pch, int first_in_list)
2907 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size) 2907 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
2908 memory_full (SIZE_MAX); 2908 memory_full (SIZE_MAX);
2909 read_buffer = (char *) xrealloc (read_buffer, 2909 read_buffer = (char *) xrealloc (read_buffer,
2910 read_buffer_size *= 2); 2910 read_buffer_size * 2);
2911 read_buffer_size *= 2;
2911 p = read_buffer + offset; 2912 p = read_buffer + offset;
2912 end = read_buffer + read_buffer_size; 2913 end = read_buffer + read_buffer_size;
2913 } 2914 }
@@ -3050,7 +3051,8 @@ read1 (register Lisp_Object readcharfun, int *pch, int first_in_list)
3050 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size) 3051 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3051 memory_full (SIZE_MAX); 3052 memory_full (SIZE_MAX);
3052 read_buffer = (char *) xrealloc (read_buffer, 3053 read_buffer = (char *) xrealloc (read_buffer,
3053 read_buffer_size *= 2); 3054 read_buffer_size * 2);
3055 read_buffer_size *= 2;
3054 p = read_buffer + offset; 3056 p = read_buffer + offset;
3055 end = read_buffer + read_buffer_size; 3057 end = read_buffer + read_buffer_size;
3056 } 3058 }
@@ -3080,7 +3082,8 @@ read1 (register Lisp_Object readcharfun, int *pch, int first_in_list)
3080 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size) 3082 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < read_buffer_size)
3081 memory_full (SIZE_MAX); 3083 memory_full (SIZE_MAX);
3082 read_buffer = (char *) xrealloc (read_buffer, 3084 read_buffer = (char *) xrealloc (read_buffer,
3083 read_buffer_size *= 2); 3085 read_buffer_size * 2);
3086 read_buffer_size *= 2;
3084 p = read_buffer + offset; 3087 p = read_buffer + offset;
3085 end = read_buffer + read_buffer_size; 3088 end = read_buffer + read_buffer_size;
3086 } 3089 }
@@ -3962,6 +3965,7 @@ void
3962init_obarray (void) 3965init_obarray (void)
3963{ 3966{
3964 Lisp_Object oblength; 3967 Lisp_Object oblength;
3968 ptrdiff_t size = 100 + MAX_MULTIBYTE_LENGTH;
3965 3969
3966 XSETFASTINT (oblength, OBARRAY_SIZE); 3970 XSETFASTINT (oblength, OBARRAY_SIZE);
3967 3971
@@ -3994,8 +3998,8 @@ init_obarray (void)
3994 3998
3995 DEFSYM (Qvariable_documentation, "variable-documentation"); 3999 DEFSYM (Qvariable_documentation, "variable-documentation");
3996 4000
3997 read_buffer_size = 100 + MAX_MULTIBYTE_LENGTH; 4001 read_buffer = (char *) xmalloc (size);
3998 read_buffer = (char *) xmalloc (read_buffer_size); 4002 read_buffer_size = size;
3999} 4003}
4000 4004
4001void 4005void
diff --git a/src/macros.c b/src/macros.c
index 60f30c3fbbe..f6cd3a3ccad 100644
--- a/src/macros.c
+++ b/src/macros.c
@@ -62,9 +62,9 @@ macro before appending to it. */)
62 62
63 if (!current_kboard->kbd_macro_buffer) 63 if (!current_kboard->kbd_macro_buffer)
64 { 64 {
65 current_kboard->kbd_macro_bufsize = 30;
66 current_kboard->kbd_macro_buffer 65 current_kboard->kbd_macro_buffer
67 = (Lisp_Object *)xmalloc (30 * sizeof (Lisp_Object)); 66 = (Lisp_Object *)xmalloc (30 * sizeof (Lisp_Object));
67 current_kboard->kbd_macro_bufsize = 30;
68 } 68 }
69 update_mode_lines++; 69 update_mode_lines++;
70 if (NILP (append)) 70 if (NILP (append))
@@ -202,7 +202,7 @@ store_kbd_macro_char (Lisp_Object c)
202 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *kb->kbd_macro_buffer / 2 202 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *kb->kbd_macro_buffer / 2
203 < kb->kbd_macro_bufsize) 203 < kb->kbd_macro_bufsize)
204 memory_full (SIZE_MAX); 204 memory_full (SIZE_MAX);
205 nbytes = kb->kbd_macro_bufsize * 2 * sizeof *kb->kbd_macro_buffer; 205 nbytes = kb->kbd_macro_bufsize * (2 * sizeof *kb->kbd_macro_buffer);
206 kb->kbd_macro_buffer 206 kb->kbd_macro_buffer
207 = (Lisp_Object *) xrealloc (kb->kbd_macro_buffer, nbytes); 207 = (Lisp_Object *) xrealloc (kb->kbd_macro_buffer, nbytes);
208 kb->kbd_macro_bufsize *= 2; 208 kb->kbd_macro_bufsize *= 2;
diff --git a/src/makefile.w32-in b/src/makefile.w32-in
index 792b66b0e4f..53cb5f857ab 100644
--- a/src/makefile.w32-in
+++ b/src/makefile.w32-in
@@ -469,6 +469,7 @@ $(BLD)/alloc.$(O) : \
469 $(SRC)/syssignal.h \ 469 $(SRC)/syssignal.h \
470 $(SRC)/w32.h \ 470 $(SRC)/w32.h \
471 $(NT_INC)/unistd.h \ 471 $(NT_INC)/unistd.h \
472 $(GNU_LIB)/verify.h \
472 $(BLOCKINPUT_H) \ 473 $(BLOCKINPUT_H) \
473 $(CHARACTER_H) \ 474 $(CHARACTER_H) \
474 $(CONFIG_H) \ 475 $(CONFIG_H) \
diff --git a/src/minibuf.c b/src/minibuf.c
index 7e59cf157b5..eb564a10ec6 100644
--- a/src/minibuf.c
+++ b/src/minibuf.c
@@ -1723,7 +1723,7 @@ the values STRING, PREDICATE and `lambda'. */)
1723 (Lisp_Object string, Lisp_Object collection, Lisp_Object predicate) 1723 (Lisp_Object string, Lisp_Object collection, Lisp_Object predicate)
1724{ 1724{
1725 Lisp_Object regexps, tail, tem = Qnil; 1725 Lisp_Object regexps, tail, tem = Qnil;
1726 EMACS_INT i = 0; 1726 ptrdiff_t i = 0;
1727 1727
1728 CHECK_STRING (string); 1728 CHECK_STRING (string);
1729 1729
diff --git a/src/nsmenu.m b/src/nsmenu.m
index 6bde229ed4d..951282910ac 100644
--- a/src/nsmenu.m
+++ b/src/nsmenu.m
@@ -1014,7 +1014,7 @@ update_frame_tool_bar (FRAME_PTR f)
1014 BOOL enabled_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_ENABLED_P)); 1014 BOOL enabled_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_ENABLED_P));
1015 BOOL selected_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_SELECTED_P)); 1015 BOOL selected_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_SELECTED_P));
1016 int idx; 1016 int idx;
1017 int img_id; 1017 ptrdiff_t img_id;
1018 struct image *img; 1018 struct image *img;
1019 Lisp_Object image; 1019 Lisp_Object image;
1020 Lisp_Object helpObj; 1020 Lisp_Object helpObj;
diff --git a/src/nsterm.h b/src/nsterm.h
index 902f35c96ea..188ec732e82 100644
--- a/src/nsterm.h
+++ b/src/nsterm.h
@@ -416,8 +416,8 @@ struct ns_bitmap_record
416/* this to map between emacs color indices and NSColor objects */ 416/* this to map between emacs color indices and NSColor objects */
417struct ns_color_table 417struct ns_color_table
418{ 418{
419 unsigned int size; 419 ptrdiff_t size;
420 unsigned int avail; 420 ptrdiff_t avail;
421#ifdef __OBJC__ 421#ifdef __OBJC__
422 NSColor **colors; 422 NSColor **colors;
423 NSMutableSet *empty_indices; 423 NSMutableSet *empty_indices;
diff --git a/src/nsterm.m b/src/nsterm.m
index 582e53e202c..4c9574c35ba 100644
--- a/src/nsterm.m
+++ b/src/nsterm.m
@@ -1341,7 +1341,7 @@ unsigned long
1341ns_index_color (NSColor *color, struct frame *f) 1341ns_index_color (NSColor *color, struct frame *f)
1342{ 1342{
1343 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table; 1343 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1344 int idx; 1344 ptrdiff_t idx;
1345 NSNumber *index; 1345 NSNumber *index;
1346 1346
1347 if (!color_table->colors) 1347 if (!color_table->colors)
@@ -1356,7 +1356,7 @@ ns_index_color (NSColor *color, struct frame *f)
1356 1356
1357 /* do we already have this color ? */ 1357 /* do we already have this color ? */
1358 { 1358 {
1359 int i; 1359 ptrdiff_t i;
1360 for (i = 1; i < color_table->avail; i++) 1360 for (i = 1; i < color_table->avail; i++)
1361 { 1361 {
1362 if (color_table->colors[i] && [color_table->colors[i] isEqual: color]) 1362 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
@@ -1371,17 +1371,14 @@ ns_index_color (NSColor *color, struct frame *f)
1371 { 1371 {
1372 index = [color_table->empty_indices anyObject]; 1372 index = [color_table->empty_indices anyObject];
1373 [color_table->empty_indices removeObject: index]; 1373 [color_table->empty_indices removeObject: index];
1374 idx = [index unsignedIntValue]; 1374 idx = [index unsignedLongValue];
1375 } 1375 }
1376 else 1376 else
1377 { 1377 {
1378 if (color_table->avail == color_table->size) 1378 if (color_table->avail == color_table->size)
1379 { 1379 color_table->colors =
1380 color_table->size += NS_COLOR_CAPACITY; 1380 xpalloc (color_table->colors, &color_table->size, 1,
1381 color_table->colors 1381 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1382 = (NSColor **)xrealloc (color_table->colors,
1383 color_table->size * sizeof (NSColor *));
1384 }
1385 idx = color_table->avail++; 1382 idx = color_table->avail++;
1386 } 1383 }
1387 1384
@@ -2321,7 +2318,7 @@ ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2321 if (!img) 2318 if (!img)
2322 { 2319 {
2323 unsigned short *bits = p->bits + p->dh; 2320 unsigned short *bits = p->bits + p->dh;
2324 int len = 8 * p->h/8; 2321 int len = p->h;
2325 int i; 2322 int i;
2326 unsigned char *cbits = xmalloc (len); 2323 unsigned char *cbits = xmalloc (len);
2327 2324
@@ -4867,7 +4864,7 @@ ns_term_shutdown (int sig)
4867 } 4864 }
4868 } 4865 }
4869 4866
4870 4867
4871#if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 4868#if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4872 /* if we get here we should send the key for input manager processing */ 4869 /* if we get here we should send the key for input manager processing */
4873 if (firstTime && [[NSInputManager currentInputManager] 4870 if (firstTime && [[NSInputManager currentInputManager]
diff --git a/src/process.c b/src/process.c
index 977cfb964e2..a8088322147 100644
--- a/src/process.c
+++ b/src/process.c
@@ -3573,52 +3573,27 @@ format; see the description of ADDRESS in `make-network-process'. */)
3573 struct ifconf ifconf; 3573 struct ifconf ifconf;
3574 struct ifreq *ifreq; 3574 struct ifreq *ifreq;
3575 void *buf = NULL; 3575 void *buf = NULL;
3576 int buf_size = 512, s, i; 3576 ptrdiff_t buf_size = 512;
3577 int s, i;
3577 Lisp_Object res; 3578 Lisp_Object res;
3578 3579
3579 s = socket (AF_INET, SOCK_STREAM, 0); 3580 s = socket (AF_INET, SOCK_STREAM, 0);
3580 if (s < 0) 3581 if (s < 0)
3581 return Qnil; 3582 return Qnil;
3582 3583
3583 ifconf.ifc_buf = 0; 3584 do
3584 ifconf.ifc_len = 0;
3585 if (ioctl (s, SIOCGIFCONF, &ifconf) == 0 && ifconf.ifc_len > 0)
3586 { 3585 {
3587 ifconf.ifc_buf = xmalloc (ifconf.ifc_len); 3586 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3588 if (ifconf.ifc_buf == NULL) 3587 ifconf.ifc_buf = buf;
3589 { 3588 ifconf.ifc_len = buf_size;
3590 close (s);
3591 return Qnil;
3592 }
3593 if (ioctl (s, SIOCGIFCONF, &ifconf)) 3589 if (ioctl (s, SIOCGIFCONF, &ifconf))
3594 { 3590 {
3595 close (s); 3591 close (s);
3596 xfree (ifconf.ifc_buf); 3592 xfree (buf);
3597 return Qnil; 3593 return Qnil;
3598 } 3594 }
3599 } 3595 }
3600 else 3596 while (ifconf.ifc_len == buf_size);
3601 do
3602 {
3603 buf_size *= 2;
3604 buf = xrealloc (buf, buf_size);
3605 if (!buf)
3606 {
3607 close (s);
3608 return Qnil;
3609 }
3610
3611 ifconf.ifc_buf = buf;
3612 ifconf.ifc_len = buf_size;
3613 if (ioctl (s, SIOCGIFCONF, &ifconf))
3614 {
3615 close (s);
3616 xfree (buf);
3617 return Qnil;
3618 }
3619
3620 }
3621 while (ifconf.ifc_len == buf_size);
3622 3597
3623 close (s); 3598 close (s);
3624 3599
diff --git a/src/region-cache.c b/src/region-cache.c
index d701f4d71b0..ed7a07a6709 100644
--- a/src/region-cache.c
+++ b/src/region-cache.c
@@ -63,7 +63,7 @@ along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
63 revalidate_region_cache to see how this helps. */ 63 revalidate_region_cache to see how this helps. */
64 64
65struct boundary { 65struct boundary {
66 EMACS_INT pos; 66 ptrdiff_t pos;
67 int value; 67 int value;
68}; 68};
69 69
@@ -73,16 +73,16 @@ struct region_cache {
73 struct boundary *boundaries; 73 struct boundary *boundaries;
74 74
75 /* boundaries[gap_start ... gap_start + gap_len - 1] is the gap. */ 75 /* boundaries[gap_start ... gap_start + gap_len - 1] is the gap. */
76 EMACS_INT gap_start, gap_len; 76 ptrdiff_t gap_start, gap_len;
77 77
78 /* The number of elements allocated to boundaries, not including the 78 /* The number of elements allocated to boundaries, not including the
79 gap. */ 79 gap. */
80 EMACS_INT cache_len; 80 ptrdiff_t cache_len;
81 81
82 /* The areas that haven't changed since the last time we cleaned out 82 /* The areas that haven't changed since the last time we cleaned out
83 invalid entries from the cache. These overlap when the buffer is 83 invalid entries from the cache. These overlap when the buffer is
84 entirely unchanged. */ 84 entirely unchanged. */
85 EMACS_INT beg_unchanged, end_unchanged; 85 ptrdiff_t beg_unchanged, end_unchanged;
86 86
87 /* The first and last positions in the buffer. Because boundaries 87 /* The first and last positions in the buffer. Because boundaries
88 store their positions relative to the start (BEG) and end (Z) of 88 store their positions relative to the start (BEG) and end (Z) of
@@ -92,7 +92,7 @@ struct region_cache {
92 92
93 Yes, buffer_beg is always 1. It's there for symmetry with 93 Yes, buffer_beg is always 1. It's there for symmetry with
94 buffer_end and the BEG and BUF_BEG macros. */ 94 buffer_end and the BEG and BUF_BEG macros. */
95 EMACS_INT buffer_beg, buffer_end; 95 ptrdiff_t buffer_beg, buffer_end;
96}; 96};
97 97
98/* Return the position of boundary i in cache c. */ 98/* Return the position of boundary i in cache c. */
@@ -173,17 +173,17 @@ free_region_cache (struct region_cache *c)
173 This operation should be logarithmic in the number of cache 173 This operation should be logarithmic in the number of cache
174 entries. It would be nice if it took advantage of locality of 174 entries. It would be nice if it took advantage of locality of
175 reference, too, by searching entries near the last entry found. */ 175 reference, too, by searching entries near the last entry found. */
176static EMACS_INT 176static ptrdiff_t
177find_cache_boundary (struct region_cache *c, EMACS_INT pos) 177find_cache_boundary (struct region_cache *c, ptrdiff_t pos)
178{ 178{
179 EMACS_INT low = 0, high = c->cache_len; 179 ptrdiff_t low = 0, high = c->cache_len;
180 180
181 while (low + 1 < high) 181 while (low + 1 < high)
182 { 182 {
183 /* mid is always a valid index, because low < high and ">> 1" 183 /* mid is always a valid index, because low < high and ">> 1"
184 rounds down. */ 184 rounds down. */
185 EMACS_INT mid = (low + high) >> 1; 185 ptrdiff_t mid = (low >> 1) + (high >> 1) + (low & high & 1);
186 EMACS_INT boundary = BOUNDARY_POS (c, mid); 186 ptrdiff_t boundary = BOUNDARY_POS (c, mid);
187 187
188 if (pos < boundary) 188 if (pos < boundary)
189 high = mid; 189 high = mid;
@@ -208,13 +208,13 @@ find_cache_boundary (struct region_cache *c, EMACS_INT pos)
208/* Move the gap of cache C to index POS, and make sure it has space 208/* Move the gap of cache C to index POS, and make sure it has space
209 for at least MIN_SIZE boundaries. */ 209 for at least MIN_SIZE boundaries. */
210static void 210static void
211move_cache_gap (struct region_cache *c, EMACS_INT pos, EMACS_INT min_size) 211move_cache_gap (struct region_cache *c, ptrdiff_t pos, ptrdiff_t min_size)
212{ 212{
213 /* Copy these out of the cache and into registers. */ 213 /* Copy these out of the cache and into registers. */
214 EMACS_INT gap_start = c->gap_start; 214 ptrdiff_t gap_start = c->gap_start;
215 EMACS_INT gap_len = c->gap_len; 215 ptrdiff_t gap_len = c->gap_len;
216 EMACS_INT buffer_beg = c->buffer_beg; 216 ptrdiff_t buffer_beg = c->buffer_beg;
217 EMACS_INT buffer_end = c->buffer_end; 217 ptrdiff_t buffer_end = c->buffer_end;
218 218
219 if (pos < 0 219 if (pos < 0
220 || pos > c->cache_len) 220 || pos > c->cache_len)
@@ -246,17 +246,11 @@ move_cache_gap (struct region_cache *c, EMACS_INT pos, EMACS_INT min_size)
246 when the portion after the gap is smallest. */ 246 when the portion after the gap is smallest. */
247 if (gap_len < min_size) 247 if (gap_len < min_size)
248 { 248 {
249 EMACS_INT i; 249 ptrdiff_t i;
250
251 /* Always make at least NEW_CACHE_GAP elements, as long as we're
252 expanding anyway. */
253 if (min_size < NEW_CACHE_GAP)
254 min_size = NEW_CACHE_GAP;
255 250
256 c->boundaries = 251 c->boundaries =
257 (struct boundary *) xrealloc (c->boundaries, 252 xpalloc (c->boundaries, &c->cache_len, min_size, -1,
258 ((min_size + c->cache_len) 253 sizeof *c->boundaries);
259 * sizeof (*c->boundaries)));
260 254
261 /* Some systems don't provide a version of the copy routine that 255 /* Some systems don't provide a version of the copy routine that
262 can be trusted to shift memory upward into an overlapping 256 can be trusted to shift memory upward into an overlapping
@@ -293,7 +287,7 @@ move_cache_gap (struct region_cache *c, EMACS_INT pos, EMACS_INT min_size)
293/* Insert a new boundary in cache C; it will have cache index I, 287/* Insert a new boundary in cache C; it will have cache index I,
294 and have the specified POS and VALUE. */ 288 and have the specified POS and VALUE. */
295static void 289static void
296insert_cache_boundary (struct region_cache *c, EMACS_INT i, EMACS_INT pos, 290insert_cache_boundary (struct region_cache *c, ptrdiff_t i, ptrdiff_t pos,
297 int value) 291 int value)
298{ 292{
299 /* i must be a valid cache index. */ 293 /* i must be a valid cache index. */
@@ -331,9 +325,9 @@ insert_cache_boundary (struct region_cache *c, EMACS_INT i, EMACS_INT pos,
331 325
332static void 326static void
333delete_cache_boundaries (struct region_cache *c, 327delete_cache_boundaries (struct region_cache *c,
334 EMACS_INT start, EMACS_INT end) 328 ptrdiff_t start, ptrdiff_t end)
335{ 329{
336 EMACS_INT len = end - start; 330 ptrdiff_t len = end - start;
337 331
338 /* Gotta be in range. */ 332 /* Gotta be in range. */
339 if (start < 0 333 if (start < 0
@@ -384,7 +378,7 @@ delete_cache_boundaries (struct region_cache *c,
384/* Set the value in cache C for the region START..END to VALUE. */ 378/* Set the value in cache C for the region START..END to VALUE. */
385static void 379static void
386set_cache_region (struct region_cache *c, 380set_cache_region (struct region_cache *c,
387 EMACS_INT start, EMACS_INT end, int value) 381 ptrdiff_t start, ptrdiff_t end, int value)
388{ 382{
389 if (start > end) 383 if (start > end)
390 abort (); 384 abort ();
@@ -407,8 +401,8 @@ set_cache_region (struct region_cache *c,
407 index of the earliest boundary after the last character in 401 index of the earliest boundary after the last character in
408 start..end. (This tortured terminology is intended to answer 402 start..end. (This tortured terminology is intended to answer
409 all the "< or <=?" sort of questions.) */ 403 all the "< or <=?" sort of questions.) */
410 EMACS_INT start_ix = find_cache_boundary (c, start); 404 ptrdiff_t start_ix = find_cache_boundary (c, start);
411 EMACS_INT end_ix = find_cache_boundary (c, end - 1) + 1; 405 ptrdiff_t end_ix = find_cache_boundary (c, end - 1) + 1;
412 406
413 /* We must remember the value established by the last boundary 407 /* We must remember the value established by the last boundary
414 before end; if that boundary's domain stretches beyond end, 408 before end; if that boundary's domain stretches beyond end,
@@ -486,7 +480,7 @@ set_cache_region (struct region_cache *c,
486 args to pass are the same before and after such an operation.) */ 480 args to pass are the same before and after such an operation.) */
487void 481void
488invalidate_region_cache (struct buffer *buf, struct region_cache *c, 482invalidate_region_cache (struct buffer *buf, struct region_cache *c,
489 EMACS_INT head, EMACS_INT tail) 483 ptrdiff_t head, ptrdiff_t tail)
490{ 484{
491 /* Let chead = c->beg_unchanged, and 485 /* Let chead = c->beg_unchanged, and
492 ctail = c->end_unchanged. 486 ctail = c->end_unchanged.
@@ -624,7 +618,7 @@ revalidate_region_cache (struct buffer *buf, struct region_cache *c)
624 corresponds to the modified region of the buffer. */ 618 corresponds to the modified region of the buffer. */
625 else 619 else
626 { 620 {
627 EMACS_INT modified_ix; 621 ptrdiff_t modified_ix;
628 622
629 /* These positions are correct, relative to both the cache basis 623 /* These positions are correct, relative to both the cache basis
630 and the buffer basis. */ 624 and the buffer basis. */
@@ -693,7 +687,7 @@ revalidate_region_cache (struct buffer *buf, struct region_cache *c)
693 no newlines", in the case of the line cache). */ 687 no newlines", in the case of the line cache). */
694void 688void
695know_region_cache (struct buffer *buf, struct region_cache *c, 689know_region_cache (struct buffer *buf, struct region_cache *c,
696 EMACS_INT start, EMACS_INT end) 690 ptrdiff_t start, ptrdiff_t end)
697{ 691{
698 revalidate_region_cache (buf, c); 692 revalidate_region_cache (buf, c);
699 693
@@ -708,14 +702,14 @@ know_region_cache (struct buffer *buf, struct region_cache *c,
708 position after POS where the knownness changes. */ 702 position after POS where the knownness changes. */
709int 703int
710region_cache_forward (struct buffer *buf, struct region_cache *c, 704region_cache_forward (struct buffer *buf, struct region_cache *c,
711 EMACS_INT pos, EMACS_INT *next) 705 ptrdiff_t pos, ptrdiff_t *next)
712{ 706{
713 revalidate_region_cache (buf, c); 707 revalidate_region_cache (buf, c);
714 708
715 { 709 {
716 EMACS_INT i = find_cache_boundary (c, pos); 710 ptrdiff_t i = find_cache_boundary (c, pos);
717 int i_value = BOUNDARY_VALUE (c, i); 711 int i_value = BOUNDARY_VALUE (c, i);
718 EMACS_INT j; 712 ptrdiff_t j;
719 713
720 /* Beyond the end of the buffer is unknown, by definition. */ 714 /* Beyond the end of the buffer is unknown, by definition. */
721 if (pos >= BUF_Z (buf)) 715 if (pos >= BUF_Z (buf))
@@ -744,7 +738,7 @@ region_cache_forward (struct buffer *buf, struct region_cache *c,
744 the purposes of CACHE. If NEXT is non-zero, set *NEXT to the nearest 738 the purposes of CACHE. If NEXT is non-zero, set *NEXT to the nearest
745 position before POS where the knownness changes. */ 739 position before POS where the knownness changes. */
746int region_cache_backward (struct buffer *buf, struct region_cache *c, 740int region_cache_backward (struct buffer *buf, struct region_cache *c,
747 EMACS_INT pos, EMACS_INT *next) 741 ptrdiff_t pos, ptrdiff_t *next)
748{ 742{
749 revalidate_region_cache (buf, c); 743 revalidate_region_cache (buf, c);
750 744
@@ -757,9 +751,9 @@ int region_cache_backward (struct buffer *buf, struct region_cache *c,
757 } 751 }
758 752
759 { 753 {
760 EMACS_INT i = find_cache_boundary (c, pos - 1); 754 ptrdiff_t i = find_cache_boundary (c, pos - 1);
761 int i_value = BOUNDARY_VALUE (c, i); 755 int i_value = BOUNDARY_VALUE (c, i);
762 EMACS_INT j; 756 ptrdiff_t j;
763 757
764 if (next) 758 if (next)
765 { 759 {
@@ -785,18 +779,18 @@ void pp_cache (struct region_cache *) EXTERNALLY_VISIBLE;
785void 779void
786pp_cache (struct region_cache *c) 780pp_cache (struct region_cache *c)
787{ 781{
788 int i; 782 ptrdiff_t i;
789 EMACS_INT beg_u = c->buffer_beg + c->beg_unchanged; 783 ptrdiff_t beg_u = c->buffer_beg + c->beg_unchanged;
790 EMACS_INT end_u = c->buffer_end - c->end_unchanged; 784 ptrdiff_t end_u = c->buffer_end - c->end_unchanged;
791 785
792 fprintf (stderr, 786 fprintf (stderr,
793 "basis: %"pI"d..%"pI"d modified: %"pI"d..%"pI"d\n", 787 "basis: %"pD"d..%"pD"d modified: %"pD"d..%"pD"d\n",
794 c->buffer_beg, c->buffer_end, 788 c->buffer_beg, c->buffer_end,
795 beg_u, end_u); 789 beg_u, end_u);
796 790
797 for (i = 0; i < c->cache_len; i++) 791 for (i = 0; i < c->cache_len; i++)
798 { 792 {
799 EMACS_INT pos = BOUNDARY_POS (c, i); 793 ptrdiff_t pos = BOUNDARY_POS (c, i);
800 794
801 putc (((pos < beg_u) ? 'v' 795 putc (((pos < beg_u) ? 'v'
802 : (pos == beg_u) ? '-' 796 : (pos == beg_u) ? '-'
@@ -806,6 +800,6 @@ pp_cache (struct region_cache *c)
806 : (pos == end_u) ? '-' 800 : (pos == end_u) ? '-'
807 : ' '), 801 : ' '),
808 stderr); 802 stderr);
809 fprintf (stderr, "%"pI"d : %d\n", pos, BOUNDARY_VALUE (c, i)); 803 fprintf (stderr, "%"pD"d : %d\n", pos, BOUNDARY_VALUE (c, i));
810 } 804 }
811} 805}
diff --git a/src/region-cache.h b/src/region-cache.h
index ea767ed0dc3..8e1be716776 100644
--- a/src/region-cache.h
+++ b/src/region-cache.h
@@ -72,7 +72,7 @@ void free_region_cache (struct region_cache *);
72 no newlines", in the case of the line cache). */ 72 no newlines", in the case of the line cache). */
73extern void know_region_cache (struct buffer *BUF, 73extern void know_region_cache (struct buffer *BUF,
74 struct region_cache *CACHE, 74 struct region_cache *CACHE,
75 EMACS_INT START, EMACS_INT END); 75 ptrdiff_t START, ptrdiff_t END);
76 76
77/* Indicate that a section of BUF has changed, to invalidate CACHE. 77/* Indicate that a section of BUF has changed, to invalidate CACHE.
78 HEAD is the number of chars unchanged at the beginning of the buffer. 78 HEAD is the number of chars unchanged at the beginning of the buffer.
@@ -84,7 +84,7 @@ extern void know_region_cache (struct buffer *BUF,
84 args to pass are the same before and after such an operation.) */ 84 args to pass are the same before and after such an operation.) */
85extern void invalidate_region_cache (struct buffer *BUF, 85extern void invalidate_region_cache (struct buffer *BUF,
86 struct region_cache *CACHE, 86 struct region_cache *CACHE,
87 EMACS_INT HEAD, EMACS_INT TAIL); 87 ptrdiff_t HEAD, ptrdiff_t TAIL);
88 88
89/* The scanning functions. 89/* The scanning functions.
90 90
@@ -100,13 +100,13 @@ extern void invalidate_region_cache (struct buffer *BUF,
100 position after POS where the knownness changes. */ 100 position after POS where the knownness changes. */
101extern int region_cache_forward (struct buffer *BUF, 101extern int region_cache_forward (struct buffer *BUF,
102 struct region_cache *CACHE, 102 struct region_cache *CACHE,
103 EMACS_INT POS, 103 ptrdiff_t POS,
104 EMACS_INT *NEXT); 104 ptrdiff_t *NEXT);
105 105
106/* Return true if the text immediately before POS in BUF is known, for 106/* Return true if the text immediately before POS in BUF is known, for
107 the purposes of CACHE. If NEXT is non-zero, set *NEXT to the nearest 107 the purposes of CACHE. If NEXT is non-zero, set *NEXT to the nearest
108 position before POS where the knownness changes. */ 108 position before POS where the knownness changes. */
109extern int region_cache_backward (struct buffer *BUF, 109extern int region_cache_backward (struct buffer *BUF,
110 struct region_cache *CACHE, 110 struct region_cache *CACHE,
111 EMACS_INT POS, 111 ptrdiff_t POS,
112 EMACS_INT *NEXT); 112 ptrdiff_t *NEXT);
diff --git a/src/scroll.c b/src/scroll.c
index 6291936a541..05f6fdf85f0 100644
--- a/src/scroll.c
+++ b/src/scroll.c
@@ -969,32 +969,14 @@ do_line_insertion_deletion_costs (FRAME_PTR frame,
969 const char *cleanup_string, 969 const char *cleanup_string,
970 int coefficient) 970 int coefficient)
971{ 971{
972 if (FRAME_INSERT_COST (frame) != 0) 972 FRAME_INSERT_COST (frame) =
973 { 973 xnrealloc (FRAME_INSERT_COST (frame), FRAME_LINES (frame), sizeof (int));
974 FRAME_INSERT_COST (frame) = 974 FRAME_DELETEN_COST (frame) =
975 (int *) xrealloc (FRAME_INSERT_COST (frame), 975 xnrealloc (FRAME_DELETEN_COST (frame), FRAME_LINES (frame), sizeof (int));
976 FRAME_LINES (frame) * sizeof (int)); 976 FRAME_INSERTN_COST (frame) =
977 FRAME_DELETEN_COST (frame) = 977 xnrealloc (FRAME_INSERTN_COST (frame), FRAME_LINES (frame), sizeof (int));
978 (int *) xrealloc (FRAME_DELETEN_COST (frame), 978 FRAME_DELETE_COST (frame) =
979 FRAME_LINES (frame) * sizeof (int)); 979 xnrealloc (FRAME_DELETE_COST (frame), FRAME_LINES (frame), sizeof (int));
980 FRAME_INSERTN_COST (frame) =
981 (int *) xrealloc (FRAME_INSERTN_COST (frame),
982 FRAME_LINES (frame) * sizeof (int));
983 FRAME_DELETE_COST (frame) =
984 (int *) xrealloc (FRAME_DELETE_COST (frame),
985 FRAME_LINES (frame) * sizeof (int));
986 }
987 else
988 {
989 FRAME_INSERT_COST (frame) =
990 (int *) xmalloc (FRAME_LINES (frame) * sizeof (int));
991 FRAME_DELETEN_COST (frame) =
992 (int *) xmalloc (FRAME_LINES (frame) * sizeof (int));
993 FRAME_INSERTN_COST (frame) =
994 (int *) xmalloc (FRAME_LINES (frame) * sizeof (int));
995 FRAME_DELETE_COST (frame) =
996 (int *) xmalloc (FRAME_LINES (frame) * sizeof (int));
997 }
998 980
999 ins_del_costs (frame, 981 ins_del_costs (frame,
1000 ins_line_string, multi_ins_string, 982 ins_line_string, multi_ins_string,
diff --git a/src/search.c b/src/search.c
index a56df784cd2..d892792cbaa 100644
--- a/src/search.c
+++ b/src/search.c
@@ -683,7 +683,7 @@ scan_buffer (register int target, EMACS_INT start, EMACS_INT end,
683 to see where we can avoid some scanning. */ 683 to see where we can avoid some scanning. */
684 if (target == '\n' && newline_cache) 684 if (target == '\n' && newline_cache)
685 { 685 {
686 EMACS_INT next_change; 686 ptrdiff_t next_change;
687 immediate_quit = 0; 687 immediate_quit = 0;
688 while (region_cache_forward 688 while (region_cache_forward
689 (current_buffer, newline_cache, start_byte, &next_change)) 689 (current_buffer, newline_cache, start_byte, &next_change))
@@ -755,7 +755,7 @@ scan_buffer (register int target, EMACS_INT start, EMACS_INT end,
755 /* Consult the newline cache, if appropriate. */ 755 /* Consult the newline cache, if appropriate. */
756 if (target == '\n' && newline_cache) 756 if (target == '\n' && newline_cache)
757 { 757 {
758 EMACS_INT next_change; 758 ptrdiff_t next_change;
759 immediate_quit = 0; 759 immediate_quit = 0;
760 while (region_cache_backward 760 while (region_cache_backward
761 (current_buffer, newline_cache, start_byte, &next_change)) 761 (current_buffer, newline_cache, start_byte, &next_change))
@@ -2640,15 +2640,17 @@ since only regular expressions have distinguished subexpressions. */)
2640 perform substitution on the replacement string. */ 2640 perform substitution on the replacement string. */
2641 if (NILP (literal)) 2641 if (NILP (literal))
2642 { 2642 {
2643 EMACS_INT length = SBYTES (newtext); 2643 ptrdiff_t length = SBYTES (newtext);
2644 unsigned char *substed; 2644 unsigned char *substed;
2645 EMACS_INT substed_alloc_size, substed_len; 2645 ptrdiff_t substed_alloc_size, substed_len;
2646 int buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters)); 2646 int buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2647 int str_multibyte = STRING_MULTIBYTE (newtext); 2647 int str_multibyte = STRING_MULTIBYTE (newtext);
2648 int really_changed = 0; 2648 int really_changed = 0;
2649 2649
2650 substed_alloc_size = length * 2 + 100; 2650 substed_alloc_size = ((STRING_BYTES_BOUND - 100) / 2 < length
2651 substed = (unsigned char *) xmalloc (substed_alloc_size + 1); 2651 ? STRING_BYTES_BOUND
2652 : length * 2 + 100);
2653 substed = (unsigned char *) xmalloc (substed_alloc_size);
2652 substed_len = 0; 2654 substed_len = 0;
2653 2655
2654 /* Go thru NEWTEXT, producing the actual text to insert in 2656 /* Go thru NEWTEXT, producing the actual text to insert in
@@ -2659,7 +2661,7 @@ since only regular expressions have distinguished subexpressions. */)
2659 { 2661 {
2660 unsigned char str[MAX_MULTIBYTE_LENGTH]; 2662 unsigned char str[MAX_MULTIBYTE_LENGTH];
2661 const unsigned char *add_stuff = NULL; 2663 const unsigned char *add_stuff = NULL;
2662 EMACS_INT add_len = 0; 2664 ptrdiff_t add_len = 0;
2663 int idx = -1; 2665 int idx = -1;
2664 2666
2665 if (str_multibyte) 2667 if (str_multibyte)
@@ -2723,7 +2725,7 @@ since only regular expressions have distinguished subexpressions. */)
2723 set up ADD_STUFF and ADD_LEN to point to it. */ 2725 set up ADD_STUFF and ADD_LEN to point to it. */
2724 if (idx >= 0) 2726 if (idx >= 0)
2725 { 2727 {
2726 EMACS_INT begbyte = CHAR_TO_BYTE (search_regs.start[idx]); 2728 ptrdiff_t begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2727 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte; 2729 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2728 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx]) 2730 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2729 move_gap (search_regs.start[idx]); 2731 move_gap (search_regs.start[idx]);
@@ -2734,12 +2736,11 @@ since only regular expressions have distinguished subexpressions. */)
2734 is invariably ADD_LEN bytes starting at ADD_STUFF. */ 2736 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2735 2737
2736 /* Make sure SUBSTED is big enough. */ 2738 /* Make sure SUBSTED is big enough. */
2737 if (substed_len + add_len >= substed_alloc_size) 2739 if (substed_alloc_size - substed_len < add_len)
2738 { 2740 substed =
2739 substed_alloc_size = substed_len + add_len + 500; 2741 xpalloc (substed, &substed_alloc_size,
2740 substed = (unsigned char *) xrealloc (substed, 2742 add_len - (substed_alloc_size - substed_len),
2741 substed_alloc_size + 1); 2743 STRING_BYTES_BOUND, 1);
2742 }
2743 2744
2744 /* Now add to the end of SUBSTED. */ 2745 /* Now add to the end of SUBSTED. */
2745 if (add_stuff) 2746 if (add_stuff)
@@ -2973,7 +2974,7 @@ LIST should have been created by calling `match-data' previously.
2973If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */) 2974If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2974 (register Lisp_Object list, Lisp_Object reseat) 2975 (register Lisp_Object list, Lisp_Object reseat)
2975{ 2976{
2976 register int i; 2977 ptrdiff_t i;
2977 register Lisp_Object marker; 2978 register Lisp_Object marker;
2978 2979
2979 if (running_asynch_code) 2980 if (running_asynch_code)
@@ -2987,31 +2988,21 @@ If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2987 2988
2988 /* Allocate registers if they don't already exist. */ 2989 /* Allocate registers if they don't already exist. */
2989 { 2990 {
2990 int length = XFASTINT (Flength (list)) / 2; 2991 ptrdiff_t length = XFASTINT (Flength (list)) / 2;
2991 2992
2992 if (length > search_regs.num_regs) 2993 if (length > search_regs.num_regs)
2993 { 2994 {
2994 if (search_regs.num_regs == 0) 2995 ptrdiff_t num_regs = search_regs.num_regs;
2995 { 2996 search_regs.start =
2996 search_regs.start 2997 xpalloc (search_regs.start, &num_regs, length - num_regs,
2997 = (regoff_t *) xmalloc (length * sizeof (regoff_t)); 2998 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
2998 search_regs.end 2999 search_regs.end =
2999 = (regoff_t *) xmalloc (length * sizeof (regoff_t)); 3000 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
3000 } 3001
3001 else 3002 for (i = search_regs.num_regs; i < num_regs; i++)
3002 {
3003 search_regs.start
3004 = (regoff_t *) xrealloc (search_regs.start,
3005 length * sizeof (regoff_t));
3006 search_regs.end
3007 = (regoff_t *) xrealloc (search_regs.end,
3008 length * sizeof (regoff_t));
3009 }
3010
3011 for (i = search_regs.num_regs; i < length; i++)
3012 search_regs.start[i] = -1; 3003 search_regs.start[i] = -1;
3013 3004
3014 search_regs.num_regs = length; 3005 search_regs.num_regs = num_regs;
3015 } 3006 }
3016 3007
3017 for (i = 0; CONSP (list); i++) 3008 for (i = 0; CONSP (list); i++)
diff --git a/src/sysdep.c b/src/sysdep.c
index 4bd1f54b9e6..57fff94f552 100644
--- a/src/sysdep.c
+++ b/src/sysdep.c
@@ -2640,7 +2640,7 @@ system_process_attributes (Lisp_Object pid)
2640 ssize_t nread; 2640 ssize_t nread;
2641 const char *cmd = NULL; 2641 const char *cmd = NULL;
2642 char *cmdline = NULL; 2642 char *cmdline = NULL;
2643 size_t cmdsize = 0, cmdline_size; 2643 ptrdiff_t cmdsize = 0, cmdline_size;
2644 unsigned char c; 2644 unsigned char c;
2645 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount; 2645 int proc_id, ppid, uid, gid, pgrp, sess, tty, tpgid, thcount;
2646 unsigned long long u_time, s_time, cutime, cstime, start; 2646 unsigned long long u_time, s_time, cutime, cstime, start;
@@ -2822,8 +2822,10 @@ system_process_attributes (Lisp_Object pid)
2822 if (fd >= 0) 2822 if (fd >= 0)
2823 { 2823 {
2824 char ch; 2824 char ch;
2825 for (cmdline_size = 0; emacs_read (fd, &ch, 1) == 1; cmdline_size++) 2825 for (cmdline_size = 0; cmdline_size < STRING_BYTES_BOUND; cmdline_size++)
2826 { 2826 {
2827 if (emacs_read (fd, &ch, 1) != 1)
2828 break;
2827 c = ch; 2829 c = ch;
2828 if (isspace (c) || c == '\\') 2830 if (isspace (c) || c == '\\')
2829 cmdline_size++; /* for later quoting, see below */ 2831 cmdline_size++; /* for later quoting, see below */
@@ -2844,7 +2846,7 @@ system_process_attributes (Lisp_Object pid)
2844 nread = 0; 2846 nread = 0;
2845 } 2847 }
2846 /* We don't want trailing null characters. */ 2848 /* We don't want trailing null characters. */
2847 for (p = cmdline + nread - 1; p > cmdline && !*p; p--) 2849 for (p = cmdline + nread; p > cmdline + 1 && !p[-1]; p--)
2848 nread--; 2850 nread--;
2849 for (p = cmdline; p < cmdline + nread; p++) 2851 for (p = cmdline; p < cmdline + nread; p++)
2850 { 2852 {
diff --git a/src/term.c b/src/term.c
index 22056451cb9..f3bf3a947cb 100644
--- a/src/term.c
+++ b/src/term.c
@@ -136,10 +136,6 @@ enum no_color_bit
136 136
137static int max_frame_cols; 137static int max_frame_cols;
138 138
139/* The largest frame height in any call to calculate_costs. */
140
141static int max_frame_lines;
142
143/* Non-zero if we have dropped our controlling tty and therefore 139/* Non-zero if we have dropped our controlling tty and therefore
144 should not open a frame on stdout. */ 140 should not open a frame on stdout. */
145static int no_controlling_tty; 141static int no_controlling_tty;
@@ -497,8 +493,8 @@ tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
497static unsigned char *encode_terminal_src; 493static unsigned char *encode_terminal_src;
498static unsigned char *encode_terminal_dst; 494static unsigned char *encode_terminal_dst;
499/* Allocated sizes of the above buffers. */ 495/* Allocated sizes of the above buffers. */
500static int encode_terminal_src_size; 496static ptrdiff_t encode_terminal_src_size;
501static int encode_terminal_dst_size; 497static ptrdiff_t encode_terminal_dst_size;
502 498
503/* Encode SRC_LEN glyphs starting at SRC to terminal output codes. 499/* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
504 Set CODING->produced to the byte-length of the resulting byte 500 Set CODING->produced to the byte-length of the resulting byte
@@ -509,8 +505,8 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
509{ 505{
510 struct glyph *src_end = src + src_len; 506 struct glyph *src_end = src + src_len;
511 unsigned char *buf; 507 unsigned char *buf;
512 int nchars, nbytes, required; 508 ptrdiff_t nchars, nbytes, required;
513 register int tlen = GLYPH_TABLE_LENGTH; 509 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
514 register Lisp_Object *tbase = GLYPH_TABLE_BASE; 510 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
515 Lisp_Object charset_list; 511 Lisp_Object charset_list;
516 512
@@ -518,13 +514,13 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
518 multibyte-form. But, it may be enlarged on demand if 514 multibyte-form. But, it may be enlarged on demand if
519 Vglyph_table contains a string or a composite glyph is 515 Vglyph_table contains a string or a composite glyph is
520 encountered. */ 516 encountered. */
521 required = MAX_MULTIBYTE_LENGTH * src_len; 517 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
518 memory_full (SIZE_MAX);
519 required = src_len;
520 required *= MAX_MULTIBYTE_LENGTH;
522 if (encode_terminal_src_size < required) 521 if (encode_terminal_src_size < required)
523 { 522 {
524 if (encode_terminal_src) 523 encode_terminal_src = xrealloc (encode_terminal_src, required);
525 encode_terminal_src = xrealloc (encode_terminal_src, required);
526 else
527 encode_terminal_src = xmalloc (required);
528 encode_terminal_src_size = required; 524 encode_terminal_src_size = required;
529 } 525 }
530 526
@@ -544,19 +540,21 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
544 if (src->u.cmp.automatic) 540 if (src->u.cmp.automatic)
545 { 541 {
546 gstring = composition_gstring_from_id (src->u.cmp.id); 542 gstring = composition_gstring_from_id (src->u.cmp.id);
547 required = src->slice.cmp.to + 1 - src->slice.cmp.from; 543 required = src->slice.cmp.to - src->slice.cmp.from + 1;
548 } 544 }
549 else 545 else
550 { 546 {
551 cmp = composition_table[src->u.cmp.id]; 547 cmp = composition_table[src->u.cmp.id];
552 required = MAX_MULTIBYTE_LENGTH * cmp->glyph_len; 548 required = cmp->glyph_len;
549 required *= MAX_MULTIBYTE_LENGTH;
553 } 550 }
554 551
555 if (encode_terminal_src_size < nbytes + required) 552 if (encode_terminal_src_size - nbytes < required)
556 { 553 {
557 encode_terminal_src_size = nbytes + required; 554 encode_terminal_src =
558 encode_terminal_src = xrealloc (encode_terminal_src, 555 xpalloc (encode_terminal_src, &encode_terminal_src_size,
559 encode_terminal_src_size); 556 required - (encode_terminal_src_size - nbytes),
557 -1, 1);
560 buf = encode_terminal_src + nbytes; 558 buf = encode_terminal_src + nbytes;
561 } 559 }
562 560
@@ -627,11 +625,11 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
627 if (NILP (string)) 625 if (NILP (string))
628 { 626 {
629 nbytes = buf - encode_terminal_src; 627 nbytes = buf - encode_terminal_src;
630 if (encode_terminal_src_size < nbytes + MAX_MULTIBYTE_LENGTH) 628 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
631 { 629 {
632 encode_terminal_src_size = nbytes + MAX_MULTIBYTE_LENGTH; 630 encode_terminal_src =
633 encode_terminal_src = xrealloc (encode_terminal_src, 631 xpalloc (encode_terminal_src, &encode_terminal_src_size,
634 encode_terminal_src_size); 632 MAX_MULTIBYTE_LENGTH, -1, 1);
635 buf = encode_terminal_src + nbytes; 633 buf = encode_terminal_src + nbytes;
636 } 634 }
637 if (CHAR_BYTE8_P (c) 635 if (CHAR_BYTE8_P (c)
@@ -659,11 +657,13 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
659 if (! STRING_MULTIBYTE (string)) 657 if (! STRING_MULTIBYTE (string))
660 string = string_to_multibyte (string); 658 string = string_to_multibyte (string);
661 nbytes = buf - encode_terminal_src; 659 nbytes = buf - encode_terminal_src;
662 if (encode_terminal_src_size < nbytes + SBYTES (string)) 660 if (encode_terminal_src_size - nbytes < SBYTES (string))
663 { 661 {
664 encode_terminal_src_size = nbytes + SBYTES (string); 662 encode_terminal_src =
665 encode_terminal_src = xrealloc (encode_terminal_src, 663 xpalloc (encode_terminal_src, &encode_terminal_src_size,
666 encode_terminal_src_size); 664 (SBYTES (string)
665 - (encode_terminal_src_size - nbytes)),
666 -1, 1);
667 buf = encode_terminal_src + nbytes; 667 buf = encode_terminal_src + nbytes;
668 } 668 }
669 memcpy (buf, SDATA (string), SBYTES (string)); 669 memcpy (buf, SDATA (string), SBYTES (string));
@@ -684,12 +684,9 @@ encode_terminal_code (struct glyph *src, int src_len, struct coding_system *codi
684 coding->source = encode_terminal_src; 684 coding->source = encode_terminal_src;
685 if (encode_terminal_dst_size == 0) 685 if (encode_terminal_dst_size == 0)
686 { 686 {
687 encode_terminal_dst = xrealloc (encode_terminal_dst,
688 encode_terminal_src_size);
687 encode_terminal_dst_size = encode_terminal_src_size; 689 encode_terminal_dst_size = encode_terminal_src_size;
688 if (encode_terminal_dst)
689 encode_terminal_dst = xrealloc (encode_terminal_dst,
690 encode_terminal_dst_size);
691 else
692 encode_terminal_dst = xmalloc (encode_terminal_dst_size);
693 } 690 }
694 coding->destination = encode_terminal_dst; 691 coding->destination = encode_terminal_dst;
695 coding->dst_bytes = encode_terminal_dst_size; 692 coding->dst_bytes = encode_terminal_dst_size;
@@ -1156,21 +1153,17 @@ calculate_costs (struct frame *frame)
1156 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because 1153 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1157 X turns off char_ins_del_ok. */ 1154 X turns off char_ins_del_ok. */
1158 1155
1159 max_frame_lines = max (max_frame_lines, FRAME_LINES (frame));
1160 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame)); 1156 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1157 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1158 < max_frame_cols)
1159 memory_full (SIZE_MAX);
1161 1160
1162 if (char_ins_del_vector != 0) 1161 char_ins_del_vector =
1163 char_ins_del_vector 1162 xrealloc (char_ins_del_vector,
1164 = (int *) xrealloc (char_ins_del_vector, 1163 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1165 (sizeof (int)
1166 + 2 * max_frame_cols * sizeof (int)));
1167 else
1168 char_ins_del_vector
1169 = (int *) xmalloc (sizeof (int)
1170 + 2 * max_frame_cols * sizeof (int));
1171 1164
1172 memset (char_ins_del_vector, 0, 1165 memset (char_ins_del_vector, 0,
1173 (sizeof (int) + 2 * max_frame_cols * sizeof (int))); 1166 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1174 1167
1175 1168
1176 if (f && (!tty->TS_ins_line && !tty->TS_del_line)) 1169 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
diff --git a/src/termcap.c b/src/termcap.c
index 96b9303d62d..6f24817fa72 100644
--- a/src/termcap.c
+++ b/src/termcap.c
@@ -480,7 +480,7 @@ tgetent (char *bp, const char *name)
480 /* If BP is malloc'd by us, make sure it is big enough. */ 480 /* If BP is malloc'd by us, make sure it is big enough. */
481 if (malloc_size) 481 if (malloc_size)
482 { 482 {
483 int offset1 = bp1 - bp, offset2 = tc_search_point - bp; 483 ptrdiff_t offset1 = bp1 - bp, offset2 = tc_search_point - bp;
484 malloc_size = offset1 + buf.size; 484 malloc_size = offset1 + buf.size;
485 bp = termcap_name = (char *) xrealloc (bp, malloc_size); 485 bp = termcap_name = (char *) xrealloc (bp, malloc_size);
486 bp1 = termcap_name + offset1; 486 bp1 = termcap_name + offset1;
@@ -619,7 +619,6 @@ gobble_line (int fd, register struct termcap_buffer *bufp, char *append_end)
619 register char *end; 619 register char *end;
620 register int nread; 620 register int nread;
621 register char *buf = bufp->beg; 621 register char *buf = bufp->beg;
622 register char *tem;
623 622
624 if (!append_end) 623 if (!append_end)
625 append_end = bufp->ptr; 624 append_end = bufp->ptr;
@@ -636,14 +635,14 @@ gobble_line (int fd, register struct termcap_buffer *bufp, char *append_end)
636 { 635 {
637 if (bufp->full == bufp->size) 636 if (bufp->full == bufp->size)
638 { 637 {
639 if ((PTRDIFF_MAX - 1) / 2 < bufp->size) 638 ptrdiff_t ptr_offset = bufp->ptr - buf;
640 memory_full (SIZE_MAX); 639 ptrdiff_t append_end_offset = append_end - buf;
641 bufp->size *= 2;
642 /* Add 1 to size to ensure room for terminating null. */ 640 /* Add 1 to size to ensure room for terminating null. */
643 tem = (char *) xrealloc (buf, bufp->size + 1); 641 ptrdiff_t size = bufp->size + 1;
644 bufp->ptr = (bufp->ptr - buf) + tem; 642 bufp->beg = buf = xpalloc (buf, &size, 1, -1, 1);
645 append_end = (append_end - buf) + tem; 643 bufp->size = size - 1;
646 bufp->beg = buf = tem; 644 bufp->ptr = buf + ptr_offset;
645 append_end = buf + append_end_offset;
647 } 646 }
648 } 647 }
649 else 648 else
diff --git a/src/termhooks.h b/src/termhooks.h
index 1310fba2f0a..a025e2798d9 100644
--- a/src/termhooks.h
+++ b/src/termhooks.h
@@ -291,12 +291,12 @@ enum {
291 /* The next four modifier bits are used also in keyboard events at 291 /* The next four modifier bits are used also in keyboard events at
292 the Lisp level. 292 the Lisp level.
293 293
294 It's probably not the greatest idea to use the 2^23 bit for any 294 It's probably not the greatest idea to use the 2^28 bit for any
295 modifier. It may or may not be the sign bit, depending on 295 modifier. It may or may not be the sign bit, depending on
296 VALBITS, so using it to represent a modifier key means that 296 FIXNUM_BITS, so using it to represent a modifier key means that
297 characters thus modified have different integer equivalents 297 characters thus modified have different integer equivalents
298 depending on the architecture they're running on. Oh, and 298 depending on the architecture they're running on. Oh, and
299 applying XINT to a character whose 2^23 bit is set sign-extends 299 applying XINT to a character whose 2^28 bit is set might sign-extend
300 it, so you get a bunch of bits in the mask you didn't want. 300 it, so you get a bunch of bits in the mask you didn't want.
301 301
302 The CHAR_ macros are defined in lisp.h. */ 302 The CHAR_ macros are defined in lisp.h. */
diff --git a/src/tparam.c b/src/tparam.c
index ed28cd7397f..ac21667d65b 100644
--- a/src/tparam.c
+++ b/src/tparam.c
@@ -79,24 +79,25 @@ tparam1 (const char *string, char *outstring, int len,
79 register const char *p = string; 79 register const char *p = string;
80 register char *op = outstring; 80 register char *op = outstring;
81 char *outend; 81 char *outend;
82 int outlen = 0; 82 char *new = 0;
83 ptrdiff_t outlen = 0;
83 84
84 register int tem; 85 register int tem;
85 int *old_argp = argp; /* can move */ 86 int *old_argp = argp; /* can move */
86 int *fixed_argp = argp; /* never moves */ 87 int *fixed_argp = argp; /* never moves */
87 int explicit_param_p = 0; /* set by %p */ 88 int explicit_param_p = 0; /* set by %p */
88 int doleft = 0; 89 ptrdiff_t doleft = 0;
89 int doup = 0; 90 ptrdiff_t doup = 0;
91 ptrdiff_t append_len = 0;
90 92
91 outend = outstring + len; 93 outend = outstring + len;
92 94
93 while (1) 95 while (1)
94 { 96 {
95 /* If the buffer might be too short, make it bigger. */ 97 /* If the buffer might be too short, make it bigger. */
96 if (op + 5 >= outend) 98 while (outend - op - append_len <= 5)
97 { 99 {
98 register char *new; 100 ptrdiff_t offset = op - outstring;
99 int offset = op - outstring;
100 101
101 if (outlen == 0) 102 if (outlen == 0)
102 { 103 {
@@ -106,8 +107,7 @@ tparam1 (const char *string, char *outstring, int len,
106 } 107 }
107 else 108 else
108 { 109 {
109 outlen *= 2; 110 new = xpalloc (outstring, &outlen, 1, -1, 1);
110 new = (char *) xrealloc (outstring, outlen);
111 } 111 }
112 112
113 op = new + offset; 113 op = new + offset;
@@ -167,11 +167,15 @@ tparam1 (const char *string, char *outstring, int len,
167 and this is one of them, increment it. */ 167 and this is one of them, increment it. */
168 while (tem == 0 || tem == '\n' || tem == '\t') 168 while (tem == 0 || tem == '\n' || tem == '\t')
169 { 169 {
170 ptrdiff_t append_len_incr;
170 tem++; 171 tem++;
171 if (argp == old_argp) 172 if (argp == old_argp)
172 doup++, outend -= strlen (up); 173 doup++, append_len_incr = strlen (up);
173 else 174 else
174 doleft++, outend -= strlen (left); 175 doleft++, append_len_incr = strlen (left);
176 if (INT_ADD_OVERFLOW (append_len, append_len_incr))
177 memory_full (SIZE_MAX);
178 append_len += append_len_incr;
175 } 179 }
176 } 180 }
177 *op++ = tem ? tem : 0200; 181 *op++ = tem ? tem : 0200;
@@ -273,7 +277,7 @@ main (int argc, char **argv)
273 args[0] = atoi (argv[2]); 277 args[0] = atoi (argv[2]);
274 args[1] = atoi (argv[3]); 278 args[1] = atoi (argv[3]);
275 args[2] = atoi (argv[4]); 279 args[2] = atoi (argv[4]);
276 tparam1 (argv[1], buf, "LEFT", "UP", args); 280 tparam1 (argv[1], buf, 50, "LEFT", "UP", args);
277 printf ("%s\n", buf); 281 printf ("%s\n", buf);
278 return 0; 282 return 0;
279} 283}
diff --git a/src/window.c b/src/window.c
index c7a4e1872fc..c8266696b2d 100644
--- a/src/window.c
+++ b/src/window.c
@@ -5074,7 +5074,7 @@ and redisplay normally--don't erase and redraw the frame. */)
5074 && (!EQ (Vrecenter_redisplay, Qtty) 5074 && (!EQ (Vrecenter_redisplay, Qtty)
5075 || !NILP (Ftty_type (selected_frame)))) 5075 || !NILP (Ftty_type (selected_frame))))
5076 { 5076 {
5077 int i; 5077 ptrdiff_t i;
5078 5078
5079 /* Invalidate pixel data calculated for all compositions. */ 5079 /* Invalidate pixel data calculated for all compositions. */
5080 for (i = 0; i < n_compositions; i++) 5080 for (i = 0; i < n_compositions; i++)
diff --git a/src/xdisp.c b/src/xdisp.c
index 580bd59908b..7e06938b3d3 100644
--- a/src/xdisp.c
+++ b/src/xdisp.c
@@ -2483,10 +2483,7 @@ init_iterator (struct it *it, struct window *w,
2483 else if (INTEGERP (w->redisplay_end_trigger)) 2483 else if (INTEGERP (w->redisplay_end_trigger))
2484 it->redisplay_end_trigger_charpos = XINT (w->redisplay_end_trigger); 2484 it->redisplay_end_trigger_charpos = XINT (w->redisplay_end_trigger);
2485 2485
2486 /* Correct bogus values of tab_width. */ 2486 it->tab_width = SANE_TAB_WIDTH (current_buffer);
2487 it->tab_width = XINT (BVAR (current_buffer, tab_width));
2488 if (it->tab_width <= 0 || it->tab_width > 1000)
2489 it->tab_width = 8;
2490 2487
2491 /* Are lines in the display truncated? */ 2488 /* Are lines in the display truncated? */
2492 if (base_face_id != DEFAULT_FACE_ID 2489 if (base_face_id != DEFAULT_FACE_ID
@@ -3151,11 +3148,15 @@ next_overlay_change (EMACS_INT pos)
3151 text property whose value is a string. STRING is data about the 3148 text property whose value is a string. STRING is data about the
3152 string to iterate; if STRING->lstring is nil, we are iterating a 3149 string to iterate; if STRING->lstring is nil, we are iterating a
3153 buffer. FRAME_WINDOW_P is non-zero when we are displaying a window 3150 buffer. FRAME_WINDOW_P is non-zero when we are displaying a window
3154 on a GUI frame. */ 3151 on a GUI frame. DISP_PROP is set to zero if we searched
3152 MAX_DISP_SCAN characters forward without finding any display
3153 strings, non-zero otherwise. It is set to 2 if the display string
3154 uses any kind of `(space ...)' spec that will produce a stretch of
3155 white space in the text area. */
3155EMACS_INT 3156EMACS_INT
3156compute_display_string_pos (struct text_pos *position, 3157compute_display_string_pos (struct text_pos *position,
3157 struct bidi_string_data *string, 3158 struct bidi_string_data *string,
3158 int frame_window_p, int *disp_prop_p) 3159 int frame_window_p, int *disp_prop)
3159{ 3160{
3160 /* OBJECT = nil means current buffer. */ 3161 /* OBJECT = nil means current buffer. */
3161 Lisp_Object object = 3162 Lisp_Object object =
@@ -3168,8 +3169,9 @@ compute_display_string_pos (struct text_pos *position,
3168 EMACS_INT lim = 3169 EMACS_INT lim =
3169 (charpos < eob - MAX_DISP_SCAN) ? charpos + MAX_DISP_SCAN : eob; 3170 (charpos < eob - MAX_DISP_SCAN) ? charpos + MAX_DISP_SCAN : eob;
3170 struct text_pos tpos; 3171 struct text_pos tpos;
3172 int rv = 0;
3171 3173
3172 *disp_prop_p = 1; 3174 *disp_prop = 1;
3173 3175
3174 if (charpos >= eob 3176 if (charpos >= eob
3175 /* We don't support display properties whose values are strings 3177 /* We don't support display properties whose values are strings
@@ -3178,7 +3180,7 @@ compute_display_string_pos (struct text_pos *position,
3178 /* C strings cannot have display properties. */ 3180 /* C strings cannot have display properties. */
3179 || (string->s && !STRINGP (object))) 3181 || (string->s && !STRINGP (object)))
3180 { 3182 {
3181 *disp_prop_p = 0; 3183 *disp_prop = 0;
3182 return eob; 3184 return eob;
3183 } 3185 }
3184 3186
@@ -3195,9 +3197,11 @@ compute_display_string_pos (struct text_pos *position,
3195 || !EQ (Fget_char_property (make_number (charpos - 1), Qdisplay, 3197 || !EQ (Fget_char_property (make_number (charpos - 1), Qdisplay,
3196 object), 3198 object),
3197 spec)) 3199 spec))
3198 && handle_display_spec (NULL, spec, object, Qnil, &tpos, bufpos, 3200 && (rv = handle_display_spec (NULL, spec, object, Qnil, &tpos, bufpos,
3199 frame_window_p)) 3201 frame_window_p)))
3200 { 3202 {
3203 if (rv == 2)
3204 *disp_prop = 2;
3201 return charpos; 3205 return charpos;
3202 } 3206 }
3203 3207
@@ -3209,7 +3213,7 @@ compute_display_string_pos (struct text_pos *position,
3209 CHARPOS (tpos) = XFASTINT (pos); 3213 CHARPOS (tpos) = XFASTINT (pos);
3210 if (CHARPOS (tpos) >= lim) 3214 if (CHARPOS (tpos) >= lim)
3211 { 3215 {
3212 *disp_prop_p = 0; 3216 *disp_prop = 0;
3213 break; 3217 break;
3214 } 3218 }
3215 if (STRINGP (object)) 3219 if (STRINGP (object))
@@ -3220,8 +3224,10 @@ compute_display_string_pos (struct text_pos *position,
3220 if (!STRINGP (object)) 3224 if (!STRINGP (object))
3221 bufpos = CHARPOS (tpos); 3225 bufpos = CHARPOS (tpos);
3222 } while (NILP (spec) 3226 } while (NILP (spec)
3223 || !handle_display_spec (NULL, spec, object, Qnil, &tpos, bufpos, 3227 || !(rv = handle_display_spec (NULL, spec, object, Qnil, &tpos,
3224 frame_window_p)); 3228 bufpos, frame_window_p)));
3229 if (rv == 2)
3230 *disp_prop = 2;
3225 3231
3226 return CHARPOS (tpos); 3232 return CHARPOS (tpos);
3227} 3233}
@@ -4083,7 +4089,9 @@ handle_display_prop (struct it *it)
4083/* Subroutine of handle_display_prop. Returns non-zero if the display 4089/* Subroutine of handle_display_prop. Returns non-zero if the display
4084 specification in SPEC is a replacing specification, i.e. it would 4090 specification in SPEC is a replacing specification, i.e. it would
4085 replace the text covered by `display' property with something else, 4091 replace the text covered by `display' property with something else,
4086 such as an image or a display string. 4092 such as an image or a display string. If SPEC includes any kind or
4093 `(space ...) specification, the value is 2; this is used by
4094 compute_display_string_pos, which see.
4087 4095
4088 See handle_single_display_spec for documentation of arguments. 4096 See handle_single_display_spec for documentation of arguments.
4089 frame_window_p is non-zero if the window being redisplayed is on a 4097 frame_window_p is non-zero if the window being redisplayed is on a
@@ -4100,6 +4108,7 @@ handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4100 EMACS_INT bufpos, int frame_window_p) 4108 EMACS_INT bufpos, int frame_window_p)
4101{ 4109{
4102 int replacing_p = 0; 4110 int replacing_p = 0;
4111 int rv;
4103 4112
4104 if (CONSP (spec) 4113 if (CONSP (spec)
4105 /* Simple specerties. */ 4114 /* Simple specerties. */
@@ -4121,11 +4130,11 @@ handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4121 { 4130 {
4122 for (; CONSP (spec); spec = XCDR (spec)) 4131 for (; CONSP (spec); spec = XCDR (spec))
4123 { 4132 {
4124 if (handle_single_display_spec (it, XCAR (spec), object, overlay, 4133 if ((rv = handle_single_display_spec (it, XCAR (spec), object,
4125 position, bufpos, replacing_p, 4134 overlay, position, bufpos,
4126 frame_window_p)) 4135 replacing_p, frame_window_p)))
4127 { 4136 {
4128 replacing_p = 1; 4137 replacing_p = rv;
4129 /* If some text in a string is replaced, `position' no 4138 /* If some text in a string is replaced, `position' no
4130 longer points to the position of `object'. */ 4139 longer points to the position of `object'. */
4131 if (!it || STRINGP (object)) 4140 if (!it || STRINGP (object))
@@ -4137,11 +4146,11 @@ handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4137 { 4146 {
4138 int i; 4147 int i;
4139 for (i = 0; i < ASIZE (spec); ++i) 4148 for (i = 0; i < ASIZE (spec); ++i)
4140 if (handle_single_display_spec (it, AREF (spec, i), object, overlay, 4149 if ((rv = handle_single_display_spec (it, AREF (spec, i), object,
4141 position, bufpos, replacing_p, 4150 overlay, position, bufpos,
4142 frame_window_p)) 4151 replacing_p, frame_window_p)))
4143 { 4152 {
4144 replacing_p = 1; 4153 replacing_p = rv;
4145 /* If some text in a string is replaced, `position' no 4154 /* If some text in a string is replaced, `position' no
4146 longer points to the position of `object'. */ 4155 longer points to the position of `object'. */
4147 if (!it || STRINGP (object)) 4156 if (!it || STRINGP (object))
@@ -4150,9 +4159,10 @@ handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4150 } 4159 }
4151 else 4160 else
4152 { 4161 {
4153 if (handle_single_display_spec (it, spec, object, overlay, 4162 if ((rv = handle_single_display_spec (it, spec, object, overlay,
4154 position, bufpos, 0, frame_window_p)) 4163 position, bufpos, 0,
4155 replacing_p = 1; 4164 frame_window_p)))
4165 replacing_p = rv;
4156 } 4166 }
4157 4167
4158 return replacing_p; 4168 return replacing_p;
@@ -4532,8 +4542,17 @@ handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4532 4542
4533 if (valid_p && !display_replaced_p) 4543 if (valid_p && !display_replaced_p)
4534 { 4544 {
4545 int retval = 1;
4546
4535 if (!it) 4547 if (!it)
4536 return 1; 4548 {
4549 /* Callers need to know whether the display spec is any kind
4550 of `(space ...)' spec that is about to affect text-area
4551 display. */
4552 if (CONSP (value) && EQ (XCAR (value), Qspace) && NILP (location))
4553 retval = 2;
4554 return retval;
4555 }
4537 4556
4538 /* Save current settings of IT so that we can restore them 4557 /* Save current settings of IT so that we can restore them
4539 when we are finished with the glyph property value. */ 4558 when we are finished with the glyph property value. */
@@ -4591,6 +4610,7 @@ handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4591 it->method = GET_FROM_STRETCH; 4610 it->method = GET_FROM_STRETCH;
4592 it->object = value; 4611 it->object = value;
4593 *position = it->position = start_pos; 4612 *position = it->position = start_pos;
4613 retval = 1 + (it->area == TEXT_AREA);
4594 } 4614 }
4595#ifdef HAVE_XWIDGETS 4615#ifdef HAVE_XWIDGETS
4596 else if (XWIDGETP(value)) 4616 else if (XWIDGETP(value))
@@ -4621,7 +4641,7 @@ handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
4621 } 4641 }
4622#endif /* HAVE_WINDOW_SYSTEM */ 4642#endif /* HAVE_WINDOW_SYSTEM */
4623 4643
4624 return 1; 4644 return retval;
4625 } 4645 }
4626 4646
4627 /* Invalid property or property not supported. Restore 4647 /* Invalid property or property not supported. Restore
@@ -5592,7 +5612,7 @@ forward_to_next_line_start (struct it *it, int *skipped_p,
5592 if (it->bidi_it.disp_pos < limit) 5612 if (it->bidi_it.disp_pos < limit)
5593 { 5613 {
5594 it->bidi_it.disp_pos = limit; 5614 it->bidi_it.disp_pos = limit;
5595 it->bidi_it.disp_prop_p = 0; 5615 it->bidi_it.disp_prop = 0;
5596 } 5616 }
5597 do { 5617 do {
5598 bprev = it->bidi_it; 5618 bprev = it->bidi_it;
@@ -10471,13 +10491,14 @@ static void
10471store_mode_line_noprop_char (char c) 10491store_mode_line_noprop_char (char c)
10472{ 10492{
10473 /* If output position has reached the end of the allocated buffer, 10493 /* If output position has reached the end of the allocated buffer,
10474 double the buffer's size. */ 10494 increase the buffer's size. */
10475 if (mode_line_noprop_ptr == mode_line_noprop_buf_end) 10495 if (mode_line_noprop_ptr == mode_line_noprop_buf_end)
10476 { 10496 {
10477 int len = MODE_LINE_NOPROP_LEN (0); 10497 ptrdiff_t len = MODE_LINE_NOPROP_LEN (0);
10478 int new_size = 2 * len * sizeof *mode_line_noprop_buf; 10498 ptrdiff_t size = len;
10479 mode_line_noprop_buf = (char *) xrealloc (mode_line_noprop_buf, new_size); 10499 mode_line_noprop_buf =
10480 mode_line_noprop_buf_end = mode_line_noprop_buf + new_size; 10500 xpalloc (mode_line_noprop_buf, &size, 1, STRING_BYTES_BOUND, 1);
10501 mode_line_noprop_buf_end = mode_line_noprop_buf + size;
10481 mode_line_noprop_ptr = mode_line_noprop_buf + len; 10502 mode_line_noprop_ptr = mode_line_noprop_buf + len;
10482 } 10503 }
10483 10504
@@ -10539,9 +10560,9 @@ x_consider_frame_title (Lisp_Object frame)
10539 /* Do we have more than one visible frame on this X display? */ 10560 /* Do we have more than one visible frame on this X display? */
10540 Lisp_Object tail; 10561 Lisp_Object tail;
10541 Lisp_Object fmt; 10562 Lisp_Object fmt;
10542 int title_start; 10563 ptrdiff_t title_start;
10543 char *title; 10564 char *title;
10544 int len; 10565 ptrdiff_t len;
10545 struct it it; 10566 struct it it;
10546 int count = SPECPDL_INDEX (); 10567 int count = SPECPDL_INDEX ();
10547 10568
@@ -14631,19 +14652,39 @@ try_cursor_movement (Lisp_Object window, struct text_pos startp, int *scroll_ste
14631 14652
14632 do 14653 do
14633 { 14654 {
14655 int at_zv_p = 0, exact_match_p = 0;
14656
14634 if (MATRIX_ROW_START_CHARPOS (row) <= PT 14657 if (MATRIX_ROW_START_CHARPOS (row) <= PT
14635 && PT <= MATRIX_ROW_END_CHARPOS (row) 14658 && PT <= MATRIX_ROW_END_CHARPOS (row)
14636 && cursor_row_p (row)) 14659 && cursor_row_p (row))
14637 rv |= set_cursor_from_row (w, row, w->current_matrix, 14660 rv |= set_cursor_from_row (w, row, w->current_matrix,
14638 0, 0, 0, 0); 14661 0, 0, 0, 0);
14639 /* As soon as we've found the first suitable row 14662 /* As soon as we've found the exact match for point,
14640 whose ends_at_zv_p flag is set, we are done. */ 14663 or the first suitable row whose ends_at_zv_p flag
14641 if (rv 14664 is set, we are done. */
14642 && MATRIX_ROW (w->current_matrix, w->cursor.vpos)->ends_at_zv_p) 14665 at_zv_p =
14666 MATRIX_ROW (w->current_matrix, w->cursor.vpos)->ends_at_zv_p;
14667 if (!at_zv_p)
14668 {
14669 struct glyph_row *candidate =
14670 MATRIX_ROW (w->current_matrix, w->cursor.vpos);
14671 struct glyph *g =
14672 candidate->glyphs[TEXT_AREA] + w->cursor.hpos;
14673 EMACS_INT endpos = MATRIX_ROW_END_CHARPOS (candidate);
14674
14675 exact_match_p =
14676 (BUFFERP (g->object) && g->charpos == PT)
14677 || (INTEGERP (g->object)
14678 && (g->charpos == PT
14679 || (g->charpos == 0 && endpos - 1 == PT)));
14680 }
14681 if (rv && (at_zv_p || exact_match_p))
14643 { 14682 {
14644 rc = CURSOR_MOVEMENT_SUCCESS; 14683 rc = CURSOR_MOVEMENT_SUCCESS;
14645 break; 14684 break;
14646 } 14685 }
14686 if (MATRIX_ROW_BOTTOM_Y (row) == last_y)
14687 break;
14647 ++row; 14688 ++row;
14648 } 14689 }
14649 while (((MATRIX_ROW_CONTINUATION_LINE_P (row) 14690 while (((MATRIX_ROW_CONTINUATION_LINE_P (row)
@@ -14655,7 +14696,9 @@ try_cursor_movement (Lisp_Object window, struct text_pos startp, int *scroll_ste
14655 loop before all the candidates were examined, signal 14696 loop before all the candidates were examined, signal
14656 to the caller that this method failed. */ 14697 to the caller that this method failed. */
14657 if (rc != CURSOR_MOVEMENT_SUCCESS 14698 if (rc != CURSOR_MOVEMENT_SUCCESS
14658 && (!rv || MATRIX_ROW_CONTINUATION_LINE_P (row))) 14699 && !(rv
14700 && !MATRIX_ROW_CONTINUATION_LINE_P (row)
14701 && !row->continued_p))
14659 rc = CURSOR_MOVEMENT_MUST_SCROLL; 14702 rc = CURSOR_MOVEMENT_MUST_SCROLL;
14660 else if (rv) 14703 else if (rv)
14661 rc = CURSOR_MOVEMENT_SUCCESS; 14704 rc = CURSOR_MOVEMENT_SUCCESS;
@@ -15115,6 +15158,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
15115 || (XFASTINT (w->last_modified) >= MODIFF 15158 || (XFASTINT (w->last_modified) >= MODIFF
15116 && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF))) 15159 && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF)))
15117 { 15160 {
15161 int d1, d2, d3, d4, d5, d6;
15118 15162
15119 /* If first window line is a continuation line, and window start 15163 /* If first window line is a continuation line, and window start
15120 is inside the modified region, but the first change is before 15164 is inside the modified region, but the first change is before
@@ -15136,7 +15180,14 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
15136 compute_window_start_on_continuation_line. (See also 15180 compute_window_start_on_continuation_line. (See also
15137 bug#197). */ 15181 bug#197). */
15138 && XMARKER (w->start)->buffer == current_buffer 15182 && XMARKER (w->start)->buffer == current_buffer
15139 && compute_window_start_on_continuation_line (w)) 15183 && compute_window_start_on_continuation_line (w)
15184 /* It doesn't make sense to force the window start like we
15185 do at label force_start if it is already known that point
15186 will not be visible in the resulting window, because
15187 doing so will move point from its correct position
15188 instead of scrolling the window to bring point into view.
15189 See bug#9324. */
15190 && pos_visible_p (w, PT, &d1, &d2, &d3, &d4, &d5, &d6))
15140 { 15191 {
15141 w->force_start = Qt; 15192 w->force_start = Qt;
15142 SET_TEXT_POS_FROM_MARKER (startp, w->start); 15193 SET_TEXT_POS_FROM_MARKER (startp, w->start);
@@ -21456,7 +21507,7 @@ calc_pixel_width_or_height (double *res, struct it *it, Lisp_Object prop,
21456 if (FRAME_WINDOW_P (it->f) 21507 if (FRAME_WINDOW_P (it->f)
21457 && valid_image_p (prop)) 21508 && valid_image_p (prop))
21458 { 21509 {
21459 int id = lookup_image (it->f, prop); 21510 ptrdiff_t id = lookup_image (it->f, prop);
21460 struct image *img = IMAGE_FROM_ID (it->f, id); 21511 struct image *img = IMAGE_FROM_ID (it->f, id);
21461 21512
21462 return OK_PIXELS (width_p ? img->width : img->height); 21513 return OK_PIXELS (width_p ? img->width : img->height);
@@ -22363,7 +22414,7 @@ compute_overhangs_and_x (struct glyph_string *s, int x, int backward_p)
22363 do { \ 22414 do { \
22364 int face_id = (row)->glyphs[area][START].face_id; \ 22415 int face_id = (row)->glyphs[area][START].face_id; \
22365 struct face *base_face = FACE_FROM_ID (f, face_id); \ 22416 struct face *base_face = FACE_FROM_ID (f, face_id); \
22366 int cmp_id = (row)->glyphs[area][START].u.cmp.id; \ 22417 ptrdiff_t cmp_id = (row)->glyphs[area][START].u.cmp.id; \
22367 struct composition *cmp = composition_table[cmp_id]; \ 22418 struct composition *cmp = composition_table[cmp_id]; \
22368 XChar2b *char2b; \ 22419 XChar2b *char2b; \
22369 struct glyph_string *first_s IF_LINT (= NULL); \ 22420 struct glyph_string *first_s IF_LINT (= NULL); \
diff --git a/src/xfaces.c b/src/xfaces.c
index 52b86638a50..431ca07b8df 100644
--- a/src/xfaces.c
+++ b/src/xfaces.c
@@ -403,7 +403,7 @@ static int next_lface_id;
403/* A vector mapping Lisp face Id's to face names. */ 403/* A vector mapping Lisp face Id's to face names. */
404 404
405static Lisp_Object *lface_id_to_name; 405static Lisp_Object *lface_id_to_name;
406static int lface_id_to_name_size; 406static ptrdiff_t lface_id_to_name_size;
407 407
408/* TTY color-related functions (defined in tty-colors.el). */ 408/* TTY color-related functions (defined in tty-colors.el). */
409 409
@@ -2682,12 +2682,10 @@ Value is a vector of face attributes. */)
2682 The mapping from Lisp face to Lisp face id is given by the 2682 The mapping from Lisp face to Lisp face id is given by the
2683 property `face' of the Lisp face name. */ 2683 property `face' of the Lisp face name. */
2684 if (next_lface_id == lface_id_to_name_size) 2684 if (next_lface_id == lface_id_to_name_size)
2685 { 2685 lface_id_to_name =
2686 int new_size = max (50, 2 * lface_id_to_name_size); 2686 xpalloc (lface_id_to_name, &lface_id_to_name_size, 1,
2687 int sz = new_size * sizeof *lface_id_to_name; 2687 min (INT_MAX, MOST_POSITIVE_FIXNUM),
2688 lface_id_to_name = (Lisp_Object *) xrealloc (lface_id_to_name, sz); 2688 sizeof *lface_id_to_name);
2689 lface_id_to_name_size = new_size;
2690 }
2691 2689
2692 lface_id_to_name[next_lface_id] = face; 2690 lface_id_to_name[next_lface_id] = face;
2693 Fput (face, Qface, make_number (next_lface_id)); 2691 Fput (face, Qface, make_number (next_lface_id));
@@ -4428,15 +4426,8 @@ cache_face (struct face_cache *c, struct face *face, unsigned int hash)
4428 if (i == c->used) 4426 if (i == c->used)
4429 { 4427 {
4430 if (c->used == c->size) 4428 if (c->used == c->size)
4431 { 4429 c->faces_by_id = xpalloc (c->faces_by_id, &c->size, 1, MAX_FACE_ID,
4432 int new_size, sz; 4430 sizeof *c->faces_by_id);
4433 new_size = min (2 * c->size, MAX_FACE_ID);
4434 if (new_size == c->size)
4435 abort (); /* Alternatives? ++kfs */
4436 sz = new_size * sizeof *c->faces_by_id;
4437 c->faces_by_id = (struct face **) xrealloc (c->faces_by_id, sz);
4438 c->size = new_size;
4439 }
4440 c->used++; 4431 c->used++;
4441 } 4432 }
4442 4433
diff --git a/src/xfns.c b/src/xfns.c
index eec19b9d275..9a3d5fcda83 100644
--- a/src/xfns.c
+++ b/src/xfns.c
@@ -145,7 +145,8 @@ static Lisp_Object Qcompound_text, Qcancel_timer;
145Lisp_Object Qfont_param; 145Lisp_Object Qfont_param;
146 146
147#if GLYPH_DEBUG 147#if GLYPH_DEBUG
148static int image_cache_refcount, dpyinfo_refcount; 148static ptrdiff_t image_cache_refcount;
149static int dpyinfo_refcount;
149#endif 150#endif
150 151
151#if defined (USE_GTK) && defined (HAVE_FREETYPE) 152#if defined (USE_GTK) && defined (HAVE_FREETYPE)
@@ -1470,7 +1471,8 @@ x_set_scroll_bar_background (struct frame *f, Lisp_Object value, Lisp_Object old
1470 the result should be `COMPOUND_TEXT'. */ 1471 the result should be `COMPOUND_TEXT'. */
1471 1472
1472static unsigned char * 1473static unsigned char *
1473x_encode_text (Lisp_Object string, Lisp_Object coding_system, int selectionp, int *text_bytes, int *stringp, int *freep) 1474x_encode_text (Lisp_Object string, Lisp_Object coding_system, int selectionp,
1475 ptrdiff_t *text_bytes, int *stringp, int *freep)
1474{ 1476{
1475 int result = string_xstring_p (string); 1477 int result = string_xstring_p (string);
1476 struct coding_system coding; 1478 struct coding_system coding;
@@ -1488,8 +1490,8 @@ x_encode_text (Lisp_Object string, Lisp_Object coding_system, int selectionp, in
1488 coding.mode |= (CODING_MODE_SAFE_ENCODING | CODING_MODE_LAST_BLOCK); 1490 coding.mode |= (CODING_MODE_SAFE_ENCODING | CODING_MODE_LAST_BLOCK);
1489 /* We suppress producing escape sequences for composition. */ 1491 /* We suppress producing escape sequences for composition. */
1490 coding.common_flags &= ~CODING_ANNOTATION_MASK; 1492 coding.common_flags &= ~CODING_ANNOTATION_MASK;
1493 coding.destination = xnmalloc (SCHARS (string), 2);
1491 coding.dst_bytes = SCHARS (string) * 2; 1494 coding.dst_bytes = SCHARS (string) * 2;
1492 coding.destination = (unsigned char *) xmalloc (coding.dst_bytes);
1493 encode_coding_object (&coding, string, 0, 0, 1495 encode_coding_object (&coding, string, 0, 0,
1494 SCHARS (string), SBYTES (string), Qnil); 1496 SCHARS (string), SBYTES (string), Qnil);
1495 *text_bytes = coding.produced; 1497 *text_bytes = coding.produced;
@@ -1511,7 +1513,8 @@ x_set_name_internal (FRAME_PTR f, Lisp_Object name)
1511 BLOCK_INPUT; 1513 BLOCK_INPUT;
1512 { 1514 {
1513 XTextProperty text, icon; 1515 XTextProperty text, icon;
1514 int bytes, stringp; 1516 ptrdiff_t bytes;
1517 int stringp;
1515 int do_free_icon_value = 0, do_free_text_value = 0; 1518 int do_free_icon_value = 0, do_free_text_value = 0;
1516 Lisp_Object coding_system; 1519 Lisp_Object coding_system;
1517 Lisp_Object encoded_name; 1520 Lisp_Object encoded_name;
@@ -1550,6 +1553,8 @@ x_set_name_internal (FRAME_PTR f, Lisp_Object name)
1550 : FRAME_X_DISPLAY_INFO (f)->Xatom_COMPOUND_TEXT); 1553 : FRAME_X_DISPLAY_INFO (f)->Xatom_COMPOUND_TEXT);
1551 text.format = 8; 1554 text.format = 8;
1552 text.nitems = bytes; 1555 text.nitems = bytes;
1556 if (text.nitems != bytes)
1557 error ("Window name too large");
1553 1558
1554 if (!STRINGP (f->icon_name)) 1559 if (!STRINGP (f->icon_name))
1555 { 1560 {
@@ -1565,6 +1570,8 @@ x_set_name_internal (FRAME_PTR f, Lisp_Object name)
1565 : FRAME_X_DISPLAY_INFO (f)->Xatom_COMPOUND_TEXT); 1570 : FRAME_X_DISPLAY_INFO (f)->Xatom_COMPOUND_TEXT);
1566 icon.format = 8; 1571 icon.format = 8;
1567 icon.nitems = bytes; 1572 icon.nitems = bytes;
1573 if (icon.nitems != bytes)
1574 error ("Icon name too large");
1568 1575
1569 encoded_icon_name = ENCODE_UTF_8 (f->icon_name); 1576 encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
1570 } 1577 }
@@ -4193,21 +4200,19 @@ FRAME. Default is to change on the edit X window. */)
4193 4200
4194 if (CONSP (value)) 4201 if (CONSP (value))
4195 { 4202 {
4203 ptrdiff_t elsize;
4204
4196 nelements = x_check_property_data (value); 4205 nelements = x_check_property_data (value);
4197 if (nelements == -1) 4206 if (nelements == -1)
4198 error ("Bad data in VALUE, must be number, string or cons"); 4207 error ("Bad data in VALUE, must be number, string or cons");
4199 4208
4200 if (element_format == 8) 4209 /* The man page for XChangeProperty:
4201 data = (unsigned char *) xmalloc (nelements); 4210 "If the specified format is 32, the property data must be a
4202 else if (element_format == 16) 4211 long array."
4203 data = (unsigned char *) xmalloc (nelements*2); 4212 This applies even if long is more than 32 bits. The X library
4204 else /* format == 32 */ 4213 converts to 32 bits before sending to the X server. */
4205 /* The man page for XChangeProperty: 4214 elsize = element_format == 32 ? sizeof (long) : element_format >> 3;
4206 "If the specified format is 32, the property data must be a 4215 data = xnmalloc (nelements, elsize);
4207 long array."
4208 This applies even if long is more than 64 bits. The X library
4209 converts to 32 bits before sending to the X server. */
4210 data = (unsigned char *) xmalloc (nelements * sizeof(long));
4211 4216
4212 x_fill_property_data (FRAME_X_DISPLAY (f), value, data, element_format); 4217 x_fill_property_data (FRAME_X_DISPLAY (f), value, data, element_format);
4213 } 4218 }
@@ -4215,7 +4220,9 @@ FRAME. Default is to change on the edit X window. */)
4215 { 4220 {
4216 CHECK_STRING (value); 4221 CHECK_STRING (value);
4217 data = SDATA (value); 4222 data = SDATA (value);
4218 nelements = SCHARS (value); 4223 if (INT_MAX < SBYTES (value))
4224 error ("VALUE too long");
4225 nelements = SBYTES (value);
4219 } 4226 }
4220 4227
4221 BLOCK_INPUT; 4228 BLOCK_INPUT;
diff --git a/src/xgselect.c b/src/xgselect.c
index 9ccdd37489f..339ec475117 100644
--- a/src/xgselect.c
+++ b/src/xgselect.c
@@ -29,7 +29,7 @@ along with GNU Emacs. If not, see <http§://www.gnu.org/licenses/>. */
29#include <setjmp.h> 29#include <setjmp.h>
30 30
31static GPollFD *gfds; 31static GPollFD *gfds;
32static int gfds_size; 32static ptrdiff_t gfds_size;
33 33
34int 34int
35xg_select (int max_fds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds, 35xg_select (int max_fds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
@@ -54,10 +54,9 @@ xg_select (int max_fds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
54 do { 54 do {
55 if (n_gfds > gfds_size) 55 if (n_gfds > gfds_size)
56 { 56 {
57 while (n_gfds > gfds_size)
58 gfds_size *= 2;
59 xfree (gfds); 57 xfree (gfds);
60 gfds = xmalloc (sizeof (*gfds) * gfds_size); 58 gfds = xpalloc (0, &gfds_size, n_gfds - gfds_size, INT_MAX,
59 sizeof *gfds);
61 } 60 }
62 61
63 n_gfds = g_main_context_query (context, 62 n_gfds = g_main_context_query (context,
diff --git a/src/xrdb.c b/src/xrdb.c
index 6a16e3260bd..63f06738b98 100644
--- a/src/xrdb.c
+++ b/src/xrdb.c
@@ -426,24 +426,22 @@ get_environ_db (void)
426{ 426{
427 XrmDatabase db; 427 XrmDatabase db;
428 char *p; 428 char *p;
429 char *path = 0, *home = 0; 429 char *path = 0;
430 const char *host;
431 430
432 if ((p = getenv ("XENVIRONMENT")) == NULL) 431 if ((p = getenv ("XENVIRONMENT")) == NULL)
433 { 432 {
434 home = gethomedir (); 433 static char const xdefaults[] = ".Xdefaults-";
435 host = get_system_name (); 434 char *home = gethomedir ();
436 path = (char *) xmalloc (strlen (home) 435 char const *host = get_system_name ();
437 + sizeof (".Xdefaults-") 436 ptrdiff_t pathsize = strlen (home) + sizeof xdefaults + strlen (host);
438 + strlen (host)); 437 path = (char *) xrealloc (home, pathsize);
439 sprintf (path, "%s%s%s", home, ".Xdefaults-", host); 438 strcat (strcat (path, xdefaults), host);
440 p = path; 439 p = path;
441 } 440 }
442 441
443 db = XrmGetFileDatabase (p); 442 db = XrmGetFileDatabase (p);
444 443
445 xfree (path); 444 xfree (path);
446 xfree (home);
447 445
448 return db; 446 return db;
449} 447}
diff --git a/src/xselect.c b/src/xselect.c
index f63977a73de..77bda79007c 100644
--- a/src/xselect.c
+++ b/src/xselect.c
@@ -66,22 +66,15 @@ static Lisp_Object wait_for_property_change_unwind (Lisp_Object);
66static void wait_for_property_change (struct prop_location *); 66static void wait_for_property_change (struct prop_location *);
67static Lisp_Object x_get_foreign_selection (Lisp_Object, Lisp_Object, 67static Lisp_Object x_get_foreign_selection (Lisp_Object, Lisp_Object,
68 Lisp_Object, Lisp_Object); 68 Lisp_Object, Lisp_Object);
69static void x_get_window_property (Display *, Window, Atom,
70 unsigned char **, int *,
71 Atom *, int *, unsigned long *, int);
72static void receive_incremental_selection (Display *, Window, Atom,
73 Lisp_Object, unsigned,
74 unsigned char **, int *,
75 Atom *, int *, unsigned long *);
76static Lisp_Object x_get_window_property_as_lisp_data (Display *, 69static Lisp_Object x_get_window_property_as_lisp_data (Display *,
77 Window, Atom, 70 Window, Atom,
78 Lisp_Object, Atom); 71 Lisp_Object, Atom);
79static Lisp_Object selection_data_to_lisp_data (Display *, 72static Lisp_Object selection_data_to_lisp_data (Display *,
80 const unsigned char *, 73 const unsigned char *,
81 int, Atom, int); 74 ptrdiff_t, Atom, int);
82static void lisp_data_to_selection_data (Display *, Lisp_Object, 75static void lisp_data_to_selection_data (Display *, Lisp_Object,
83 unsigned char **, Atom *, 76 unsigned char **, Atom *,
84 unsigned *, int *, int *); 77 ptrdiff_t *, int *, int *);
85static Lisp_Object clean_local_selection_data (Lisp_Object); 78static Lisp_Object clean_local_selection_data (Lisp_Object);
86 79
87/* Printing traces to stderr. */ 80/* Printing traces to stderr. */
@@ -114,15 +107,39 @@ static Lisp_Object Qcompound_text_with_extensions;
114static Lisp_Object Qforeign_selection; 107static Lisp_Object Qforeign_selection;
115static Lisp_Object Qx_lost_selection_functions, Qx_sent_selection_functions; 108static Lisp_Object Qx_lost_selection_functions, Qx_sent_selection_functions;
116 109
110/* Bytes needed to represent 'long' data. This is as per libX11; it
111 is not necessarily sizeof (long). */
112#define X_LONG_SIZE 4
113
114/* Extreme 'short' and 'long' values suitable for libX11. */
115#define X_SHRT_MAX 0x7fff
116#define X_SHRT_MIN (-1 - X_SHRT_MAX)
117#define X_LONG_MAX 0x7fffffff
118#define X_LONG_MIN (-1 - X_LONG_MAX)
119
117/* If this is a smaller number than the max-request-size of the display, 120/* If this is a smaller number than the max-request-size of the display,
118 emacs will use INCR selection transfer when the selection is larger 121 emacs will use INCR selection transfer when the selection is larger
119 than this. The max-request-size is usually around 64k, so if you want 122 than this. The max-request-size is usually around 64k, so if you want
120 emacs to use incremental selection transfers when the selection is 123 emacs to use incremental selection transfers when the selection is
121 smaller than that, set this. I added this mostly for debugging the 124 smaller than that, set this. I added this mostly for debugging the
122 incremental transfer stuff, but it might improve server performance. */ 125 incremental transfer stuff, but it might improve server performance.
123#define MAX_SELECTION_QUANTUM 0xFFFFFF
124 126
125#define SELECTION_QUANTUM(dpy) ((XMaxRequestSize(dpy) << 2) - 100) 127 This value cannot exceed INT_MAX / max (X_LONG_SIZE, sizeof (long))
128 because it is multiplied by X_LONG_SIZE and by sizeof (long) in
129 subscript calculations. Similarly for PTRDIFF_MAX - 1 or SIZE_MAX
130 - 1 in place of INT_MAX. */
131#define MAX_SELECTION_QUANTUM \
132 ((int) min (0xFFFFFF, (min (INT_MAX, min (PTRDIFF_MAX, SIZE_MAX) - 1) \
133 / max (X_LONG_SIZE, sizeof (long)))))
134
135static int
136selection_quantum (Display *display)
137{
138 long mrs = XMaxRequestSize (display);
139 return (mrs < MAX_SELECTION_QUANTUM / X_LONG_SIZE + 25
140 ? (mrs - 25) * X_LONG_SIZE
141 : MAX_SELECTION_QUANTUM);
142}
126 143
127#define LOCAL_SELECTION(selection_symbol,dpyinfo) \ 144#define LOCAL_SELECTION(selection_symbol,dpyinfo) \
128 assq_no_quit (selection_symbol, dpyinfo->terminal->Vselection_alist) 145 assq_no_quit (selection_symbol, dpyinfo->terminal->Vselection_alist)
@@ -477,7 +494,7 @@ static struct x_display_info *selection_request_dpyinfo;
477struct selection_data 494struct selection_data
478{ 495{
479 unsigned char *data; 496 unsigned char *data;
480 unsigned int size; 497 ptrdiff_t size;
481 int format; 498 int format;
482 Atom type; 499 Atom type;
483 int nofree; 500 int nofree;
@@ -581,14 +598,11 @@ x_reply_selection_request (struct input_event *event, struct x_display_info *dpy
581 XSelectionEvent *reply = &(reply_base.xselection); 598 XSelectionEvent *reply = &(reply_base.xselection);
582 Display *display = SELECTION_EVENT_DISPLAY (event); 599 Display *display = SELECTION_EVENT_DISPLAY (event);
583 Window window = SELECTION_EVENT_REQUESTOR (event); 600 Window window = SELECTION_EVENT_REQUESTOR (event);
584 int bytes_remaining; 601 ptrdiff_t bytes_remaining;
585 int max_bytes = SELECTION_QUANTUM (display); 602 int max_bytes = selection_quantum (display);
586 int count = SPECPDL_INDEX (); 603 int count = SPECPDL_INDEX ();
587 struct selection_data *cs; 604 struct selection_data *cs;
588 605
589 if (max_bytes > MAX_SELECTION_QUANTUM)
590 max_bytes = MAX_SELECTION_QUANTUM;
591
592 reply->type = SelectionNotify; 606 reply->type = SelectionNotify;
593 reply->display = display; 607 reply->display = display;
594 reply->requestor = window; 608 reply->requestor = window;
@@ -616,11 +630,12 @@ x_reply_selection_request (struct input_event *event, struct x_display_info *dpy
616 if (cs->property == None) 630 if (cs->property == None)
617 continue; 631 continue;
618 632
619 bytes_remaining = cs->size * (cs->format / 8); 633 bytes_remaining = cs->size;
634 bytes_remaining *= cs->format >> 3;
620 if (bytes_remaining <= max_bytes) 635 if (bytes_remaining <= max_bytes)
621 { 636 {
622 /* Send all the data at once, with minimal handshaking. */ 637 /* Send all the data at once, with minimal handshaking. */
623 TRACE1 ("Sending all %d bytes", bytes_remaining); 638 TRACE1 ("Sending all %"pD"d bytes", bytes_remaining);
624 XChangeProperty (display, window, cs->property, 639 XChangeProperty (display, window, cs->property,
625 cs->type, cs->format, PropModeReplace, 640 cs->type, cs->format, PropModeReplace,
626 cs->data, cs->size); 641 cs->data, cs->size);
@@ -630,7 +645,7 @@ x_reply_selection_request (struct input_event *event, struct x_display_info *dpy
630 /* Send an INCR tag to initiate incremental transfer. */ 645 /* Send an INCR tag to initiate incremental transfer. */
631 long value[1]; 646 long value[1];
632 647
633 TRACE2 ("Start sending %d bytes incrementally (%s)", 648 TRACE2 ("Start sending %"pD"d bytes incrementally (%s)",
634 bytes_remaining, XGetAtomName (display, cs->property)); 649 bytes_remaining, XGetAtomName (display, cs->property));
635 cs->wait_object 650 cs->wait_object
636 = expect_property_change (display, window, cs->property, 651 = expect_property_change (display, window, cs->property,
@@ -638,7 +653,7 @@ x_reply_selection_request (struct input_event *event, struct x_display_info *dpy
638 653
639 /* XChangeProperty expects an array of long even if long is 654 /* XChangeProperty expects an array of long even if long is
640 more than 32 bits. */ 655 more than 32 bits. */
641 value[0] = bytes_remaining; 656 value[0] = min (bytes_remaining, X_LONG_MAX);
642 XChangeProperty (display, window, cs->property, 657 XChangeProperty (display, window, cs->property,
643 dpyinfo->Xatom_INCR, 32, PropModeReplace, 658 dpyinfo->Xatom_INCR, 32, PropModeReplace,
644 (unsigned char *) value, 1); 659 (unsigned char *) value, 1);
@@ -672,7 +687,8 @@ x_reply_selection_request (struct input_event *event, struct x_display_info *dpy
672 int had_errors = x_had_errors_p (display); 687 int had_errors = x_had_errors_p (display);
673 UNBLOCK_INPUT; 688 UNBLOCK_INPUT;
674 689
675 bytes_remaining = cs->size * format_bytes; 690 bytes_remaining = cs->size;
691 bytes_remaining *= format_bytes;
676 692
677 /* Wait for the requester to ack by deleting the property. 693 /* Wait for the requester to ack by deleting the property.
678 This can run Lisp code (process handlers) or signal. */ 694 This can run Lisp code (process handlers) or signal. */
@@ -810,7 +826,7 @@ x_handle_selection_request (struct input_event *event)
810 non-None property. */ 826 non-None property. */
811 Window requestor = SELECTION_EVENT_REQUESTOR (event); 827 Window requestor = SELECTION_EVENT_REQUESTOR (event);
812 Lisp_Object multprop; 828 Lisp_Object multprop;
813 int j, nselections; 829 ptrdiff_t j, nselections;
814 830
815 if (property == None) goto DONE; 831 if (property == None) goto DONE;
816 multprop 832 multprop
@@ -1269,19 +1285,28 @@ x_get_foreign_selection (Lisp_Object selection_symbol, Lisp_Object target_type,
1269 1285
1270static void 1286static void
1271x_get_window_property (Display *display, Window window, Atom property, 1287x_get_window_property (Display *display, Window window, Atom property,
1272 unsigned char **data_ret, int *bytes_ret, 1288 unsigned char **data_ret, ptrdiff_t *bytes_ret,
1273 Atom *actual_type_ret, int *actual_format_ret, 1289 Atom *actual_type_ret, int *actual_format_ret,
1274 unsigned long *actual_size_ret, int delete_p) 1290 unsigned long *actual_size_ret, int delete_p)
1275{ 1291{
1276 int total_size; 1292 ptrdiff_t total_size;
1277 unsigned long bytes_remaining; 1293 unsigned long bytes_remaining;
1278 int offset = 0; 1294 ptrdiff_t offset = 0;
1295 unsigned char *data = 0;
1279 unsigned char *tmp_data = 0; 1296 unsigned char *tmp_data = 0;
1280 int result; 1297 int result;
1281 int buffer_size = SELECTION_QUANTUM (display); 1298 int buffer_size = selection_quantum (display);
1299
1300 /* Wide enough to avoid overflow in expressions using it. */
1301 ptrdiff_t x_long_size = X_LONG_SIZE;
1282 1302
1283 if (buffer_size > MAX_SELECTION_QUANTUM) 1303 /* Maximum value for TOTAL_SIZE. It cannot exceed PTRDIFF_MAX - 1
1284 buffer_size = MAX_SELECTION_QUANTUM; 1304 and SIZE_MAX - 1, for an extra byte at the end. And it cannot
1305 exceed LONG_MAX * X_LONG_SIZE, for XGetWindowProperty. */
1306 ptrdiff_t total_size_max =
1307 ((min (PTRDIFF_MAX, SIZE_MAX) - 1) / x_long_size < LONG_MAX
1308 ? min (PTRDIFF_MAX, SIZE_MAX) - 1
1309 : LONG_MAX * x_long_size);
1285 1310
1286 BLOCK_INPUT; 1311 BLOCK_INPUT;
1287 1312
@@ -1292,49 +1317,44 @@ x_get_window_property (Display *display, Window window, Atom property,
1292 actual_size_ret, 1317 actual_size_ret,
1293 &bytes_remaining, &tmp_data); 1318 &bytes_remaining, &tmp_data);
1294 if (result != Success) 1319 if (result != Success)
1295 { 1320 goto done;
1296 UNBLOCK_INPUT;
1297 *data_ret = 0;
1298 *bytes_ret = 0;
1299 return;
1300 }
1301 1321
1302 /* This was allocated by Xlib, so use XFree. */ 1322 /* This was allocated by Xlib, so use XFree. */
1303 XFree ((char *) tmp_data); 1323 XFree ((char *) tmp_data);
1304 1324
1305 if (*actual_type_ret == None || *actual_format_ret == 0) 1325 if (*actual_type_ret == None || *actual_format_ret == 0)
1306 { 1326 goto done;
1307 UNBLOCK_INPUT;
1308 return;
1309 }
1310 1327
1311 total_size = bytes_remaining + 1; 1328 if (total_size_max < bytes_remaining)
1312 *data_ret = (unsigned char *) xmalloc (total_size); 1329 goto size_overflow;
1330 total_size = bytes_remaining;
1331 data = malloc (total_size + 1);
1332 if (! data)
1333 goto memory_exhausted;
1313 1334
1314 /* Now read, until we've gotten it all. */ 1335 /* Now read, until we've gotten it all. */
1315 while (bytes_remaining) 1336 while (bytes_remaining)
1316 { 1337 {
1317#ifdef TRACE_SELECTION 1338 ptrdiff_t bytes_gotten;
1318 unsigned long last = bytes_remaining; 1339 int bytes_per_item;
1319#endif
1320 result 1340 result
1321 = XGetWindowProperty (display, window, property, 1341 = XGetWindowProperty (display, window, property,
1322 (long)offset/4, (long)buffer_size/4, 1342 offset / X_LONG_SIZE,
1343 buffer_size / X_LONG_SIZE,
1323 False, 1344 False,
1324 AnyPropertyType, 1345 AnyPropertyType,
1325 actual_type_ret, actual_format_ret, 1346 actual_type_ret, actual_format_ret,
1326 actual_size_ret, &bytes_remaining, &tmp_data); 1347 actual_size_ret, &bytes_remaining, &tmp_data);
1327 1348
1328 TRACE2 ("Read %lu bytes from property %s",
1329 last - bytes_remaining,
1330 XGetAtomName (display, property));
1331
1332 /* If this doesn't return Success at this point, it means that 1349 /* If this doesn't return Success at this point, it means that
1333 some clod deleted the selection while we were in the midst of 1350 some clod deleted the selection while we were in the midst of
1334 reading it. Deal with that, I guess.... */ 1351 reading it. Deal with that, I guess.... */
1335 if (result != Success) 1352 if (result != Success)
1336 break; 1353 break;
1337 1354
1355 bytes_per_item = *actual_format_ret >> 3;
1356 xassert (*actual_size_ret <= buffer_size / bytes_per_item);
1357
1338 /* The man page for XGetWindowProperty says: 1358 /* The man page for XGetWindowProperty says:
1339 "If the returned format is 32, the returned data is represented 1359 "If the returned format is 32, the returned data is represented
1340 as a long array and should be cast to that type to obtain the 1360 as a long array and should be cast to that type to obtain the
@@ -1348,32 +1368,61 @@ x_get_window_property (Display *display, Window window, Atom property,
1348 The bytes and offsets passed to XGetWindowProperty refers to the 1368 The bytes and offsets passed to XGetWindowProperty refers to the
1349 property and those are indeed in 32 bit quantities if format is 32. */ 1369 property and those are indeed in 32 bit quantities if format is 32. */
1350 1370
1371 bytes_gotten = *actual_size_ret;
1372 bytes_gotten *= bytes_per_item;
1373
1374 TRACE2 ("Read %"pD"d bytes from property %s",
1375 bytes_gotten, XGetAtomName (display, property));
1376
1377 if (total_size - offset < bytes_gotten)
1378 {
1379 unsigned char *data1;
1380 ptrdiff_t remaining_lim = total_size_max - offset - bytes_gotten;
1381 if (remaining_lim < 0 || remaining_lim < bytes_remaining)
1382 goto size_overflow;
1383 total_size = offset + bytes_gotten + bytes_remaining;
1384 data1 = realloc (data, total_size + 1);
1385 if (! data1)
1386 goto memory_exhausted;
1387 data = data1;
1388 }
1389
1351 if (32 < BITS_PER_LONG && *actual_format_ret == 32) 1390 if (32 < BITS_PER_LONG && *actual_format_ret == 32)
1352 { 1391 {
1353 unsigned long i; 1392 unsigned long i;
1354 int *idata = (int *) ((*data_ret) + offset); 1393 int *idata = (int *) (data + offset);
1355 long *ldata = (long *) tmp_data; 1394 long *ldata = (long *) tmp_data;
1356 1395
1357 for (i = 0; i < *actual_size_ret; ++i) 1396 for (i = 0; i < *actual_size_ret; ++i)
1358 { 1397 idata[i] = ldata[i];
1359 idata[i]= (int) ldata[i];
1360 offset += 4;
1361 }
1362 } 1398 }
1363 else 1399 else
1364 { 1400 memcpy (data + offset, tmp_data, bytes_gotten);
1365 *actual_size_ret *= *actual_format_ret / 8; 1401
1366 memcpy ((*data_ret) + offset, tmp_data, *actual_size_ret); 1402 offset += bytes_gotten;
1367 offset += *actual_size_ret;
1368 }
1369 1403
1370 /* This was allocated by Xlib, so use XFree. */ 1404 /* This was allocated by Xlib, so use XFree. */
1371 XFree ((char *) tmp_data); 1405 XFree ((char *) tmp_data);
1372 } 1406 }
1373 1407
1374 XFlush (display); 1408 XFlush (display);
1409 data[offset] = '\0';
1410
1411 done:
1375 UNBLOCK_INPUT; 1412 UNBLOCK_INPUT;
1413 *data_ret = data;
1376 *bytes_ret = offset; 1414 *bytes_ret = offset;
1415 return;
1416
1417 size_overflow:
1418 free (data);
1419 UNBLOCK_INPUT;
1420 memory_full (SIZE_MAX);
1421
1422 memory_exhausted:
1423 free (data);
1424 UNBLOCK_INPUT;
1425 memory_full (total_size + 1);
1377} 1426}
1378 1427
1379/* Use xfree, not XFree, to free the data obtained with this function. */ 1428/* Use xfree, not XFree, to free the data obtained with this function. */
@@ -1382,16 +1431,19 @@ static void
1382receive_incremental_selection (Display *display, Window window, Atom property, 1431receive_incremental_selection (Display *display, Window window, Atom property,
1383 Lisp_Object target_type, 1432 Lisp_Object target_type,
1384 unsigned int min_size_bytes, 1433 unsigned int min_size_bytes,
1385 unsigned char **data_ret, int *size_bytes_ret, 1434 unsigned char **data_ret,
1435 ptrdiff_t *size_bytes_ret,
1386 Atom *type_ret, int *format_ret, 1436 Atom *type_ret, int *format_ret,
1387 unsigned long *size_ret) 1437 unsigned long *size_ret)
1388{ 1438{
1389 int offset = 0; 1439 ptrdiff_t offset = 0;
1390 struct prop_location *wait_object; 1440 struct prop_location *wait_object;
1441 if (min (PTRDIFF_MAX, SIZE_MAX) < min_size_bytes)
1442 memory_full (SIZE_MAX);
1443 *data_ret = (unsigned char *) xmalloc (min_size_bytes);
1391 *size_bytes_ret = min_size_bytes; 1444 *size_bytes_ret = min_size_bytes;
1392 *data_ret = (unsigned char *) xmalloc (*size_bytes_ret);
1393 1445
1394 TRACE1 ("Read %d bytes incrementally", min_size_bytes); 1446 TRACE1 ("Read %u bytes incrementally", min_size_bytes);
1395 1447
1396 /* At this point, we have read an INCR property. 1448 /* At this point, we have read an INCR property.
1397 Delete the property to ack it. 1449 Delete the property to ack it.
@@ -1416,7 +1468,7 @@ receive_incremental_selection (Display *display, Window window, Atom property,
1416 while (1) 1468 while (1)
1417 { 1469 {
1418 unsigned char *tmp_data; 1470 unsigned char *tmp_data;
1419 int tmp_size_bytes; 1471 ptrdiff_t tmp_size_bytes;
1420 1472
1421 TRACE0 (" Wait for property change"); 1473 TRACE0 (" Wait for property change");
1422 wait_for_property_change (wait_object); 1474 wait_for_property_change (wait_object);
@@ -1429,7 +1481,7 @@ receive_incremental_selection (Display *display, Window window, Atom property,
1429 &tmp_data, &tmp_size_bytes, 1481 &tmp_data, &tmp_size_bytes,
1430 type_ret, format_ret, size_ret, 1); 1482 type_ret, format_ret, size_ret, 1);
1431 1483
1432 TRACE1 (" Read increment of %d bytes", tmp_size_bytes); 1484 TRACE1 (" Read increment of %"pD"d bytes", tmp_size_bytes);
1433 1485
1434 if (tmp_size_bytes == 0) /* we're done */ 1486 if (tmp_size_bytes == 0) /* we're done */
1435 { 1487 {
@@ -1452,11 +1504,10 @@ receive_incremental_selection (Display *display, Window window, Atom property,
1452 XFlush (display); 1504 XFlush (display);
1453 UNBLOCK_INPUT; 1505 UNBLOCK_INPUT;
1454 1506
1455 if (*size_bytes_ret < offset + tmp_size_bytes) 1507 if (*size_bytes_ret - offset < tmp_size_bytes)
1456 { 1508 *data_ret = xpalloc (*data_ret, size_bytes_ret,
1457 *size_bytes_ret = offset + tmp_size_bytes; 1509 tmp_size_bytes - (*size_bytes_ret - offset),
1458 *data_ret = (unsigned char *) xrealloc (*data_ret, *size_bytes_ret); 1510 -1, 1);
1459 }
1460 1511
1461 memcpy ((*data_ret) + offset, tmp_data, tmp_size_bytes); 1512 memcpy ((*data_ret) + offset, tmp_data, tmp_size_bytes);
1462 offset += tmp_size_bytes; 1513 offset += tmp_size_bytes;
@@ -1482,7 +1533,7 @@ x_get_window_property_as_lisp_data (Display *display, Window window,
1482 int actual_format; 1533 int actual_format;
1483 unsigned long actual_size; 1534 unsigned long actual_size;
1484 unsigned char *data = 0; 1535 unsigned char *data = 0;
1485 int bytes = 0; 1536 ptrdiff_t bytes = 0;
1486 Lisp_Object val; 1537 Lisp_Object val;
1487 struct x_display_info *dpyinfo = x_display_info_for_display (display); 1538 struct x_display_info *dpyinfo = x_display_info_for_display (display);
1488 1539
@@ -1574,7 +1625,7 @@ x_get_window_property_as_lisp_data (Display *display, Window window,
1574 1625
1575static Lisp_Object 1626static Lisp_Object
1576selection_data_to_lisp_data (Display *display, const unsigned char *data, 1627selection_data_to_lisp_data (Display *display, const unsigned char *data,
1577 int size, Atom type, int format) 1628 ptrdiff_t size, Atom type, int format)
1578{ 1629{
1579 struct x_display_info *dpyinfo = x_display_info_for_display (display); 1630 struct x_display_info *dpyinfo = x_display_info_for_display (display);
1580 1631
@@ -1607,7 +1658,7 @@ selection_data_to_lisp_data (Display *display, const unsigned char *data,
1607 /* Treat ATOM_PAIR type similar to list of atoms. */ 1658 /* Treat ATOM_PAIR type similar to list of atoms. */
1608 || type == dpyinfo->Xatom_ATOM_PAIR) 1659 || type == dpyinfo->Xatom_ATOM_PAIR)
1609 { 1660 {
1610 int i; 1661 ptrdiff_t i;
1611 /* On a 64 bit machine sizeof(Atom) == sizeof(long) == 8. 1662 /* On a 64 bit machine sizeof(Atom) == sizeof(long) == 8.
1612 But the callers of these function has made sure the data for 1663 But the callers of these function has made sure the data for
1613 format == 32 is an array of int. Thus, use int instead 1664 format == 32 is an array of int. Thus, use int instead
@@ -1634,28 +1685,29 @@ selection_data_to_lisp_data (Display *display, const unsigned char *data,
1634 else if (format == 32 && size == sizeof (int)) 1685 else if (format == 32 && size == sizeof (int))
1635 return INTEGER_TO_CONS (((unsigned int *) data) [0]); 1686 return INTEGER_TO_CONS (((unsigned int *) data) [0]);
1636 else if (format == 16 && size == sizeof (short)) 1687 else if (format == 16 && size == sizeof (short))
1637 return make_number ((int) (((unsigned short *) data) [0])); 1688 return make_number (((unsigned short *) data) [0]);
1638 1689
1639 /* Convert any other kind of data to a vector of numbers, represented 1690 /* Convert any other kind of data to a vector of numbers, represented
1640 as above (as an integer, or a cons of two 16 bit integers.) 1691 as above (as an integer, or a cons of two 16 bit integers.)
1641 */ 1692 */
1642 else if (format == 16) 1693 else if (format == 16)
1643 { 1694 {
1644 int i; 1695 ptrdiff_t i;
1645 Lisp_Object v; 1696 Lisp_Object v;
1646 v = Fmake_vector (make_number (size / 2), make_number (0)); 1697 v = Fmake_vector (make_number (size / 2), make_number (0));
1647 for (i = 0; i < size / 2; i++) 1698 for (i = 0; i < size / 2; i++)
1648 { 1699 {
1649 int j = (int) ((unsigned short *) data) [i]; 1700 EMACS_INT j = ((unsigned short *) data) [i];
1650 Faset (v, make_number (i), make_number (j)); 1701 Faset (v, make_number (i), make_number (j));
1651 } 1702 }
1652 return v; 1703 return v;
1653 } 1704 }
1654 else 1705 else
1655 { 1706 {
1656 int i; 1707 ptrdiff_t i;
1657 Lisp_Object v = Fmake_vector (make_number (size / 4), make_number (0)); 1708 Lisp_Object v = Fmake_vector (make_number (size / X_LONG_SIZE),
1658 for (i = 0; i < size / 4; i++) 1709 make_number (0));
1710 for (i = 0; i < size / X_LONG_SIZE; i++)
1659 { 1711 {
1660 unsigned int j = ((unsigned int *) data) [i]; 1712 unsigned int j = ((unsigned int *) data) [i];
1661 Faset (v, make_number (i), INTEGER_TO_CONS (j)); 1713 Faset (v, make_number (i), INTEGER_TO_CONS (j));
@@ -1670,7 +1722,7 @@ selection_data_to_lisp_data (Display *display, const unsigned char *data,
1670static void 1722static void
1671lisp_data_to_selection_data (Display *display, Lisp_Object obj, 1723lisp_data_to_selection_data (Display *display, Lisp_Object obj,
1672 unsigned char **data_ret, Atom *type_ret, 1724 unsigned char **data_ret, Atom *type_ret,
1673 unsigned int *size_ret, 1725 ptrdiff_t *size_ret,
1674 int *format_ret, int *nofree_ret) 1726 int *format_ret, int *nofree_ret)
1675{ 1727{
1676 Lisp_Object type = Qnil; 1728 Lisp_Object type = Qnil;
@@ -1707,22 +1759,20 @@ lisp_data_to_selection_data (Display *display, Lisp_Object obj,
1707 } 1759 }
1708 else if (SYMBOLP (obj)) 1760 else if (SYMBOLP (obj))
1709 { 1761 {
1762 *data_ret = (unsigned char *) xmalloc (sizeof (Atom) + 1);
1710 *format_ret = 32; 1763 *format_ret = 32;
1711 *size_ret = 1; 1764 *size_ret = 1;
1712 *data_ret = (unsigned char *) xmalloc (sizeof (Atom) + 1);
1713 (*data_ret) [sizeof (Atom)] = 0; 1765 (*data_ret) [sizeof (Atom)] = 0;
1714 (*(Atom **) data_ret) [0] = symbol_to_x_atom (dpyinfo, obj); 1766 (*(Atom **) data_ret) [0] = symbol_to_x_atom (dpyinfo, obj);
1715 if (NILP (type)) type = QATOM; 1767 if (NILP (type)) type = QATOM;
1716 } 1768 }
1717 else if (INTEGERP (obj) 1769 else if (RANGED_INTEGERP (X_SHRT_MIN, obj, X_SHRT_MAX))
1718 && XINT (obj) < 0xFFFF
1719 && XINT (obj) > -0xFFFF)
1720 { 1770 {
1771 *data_ret = (unsigned char *) xmalloc (sizeof (short) + 1);
1721 *format_ret = 16; 1772 *format_ret = 16;
1722 *size_ret = 1; 1773 *size_ret = 1;
1723 *data_ret = (unsigned char *) xmalloc (sizeof (short) + 1);
1724 (*data_ret) [sizeof (short)] = 0; 1774 (*data_ret) [sizeof (short)] = 0;
1725 (*(short **) data_ret) [0] = (short) XINT (obj); 1775 (*(short **) data_ret) [0] = XINT (obj);
1726 if (NILP (type)) type = QINTEGER; 1776 if (NILP (type)) type = QINTEGER;
1727 } 1777 }
1728 else if (INTEGERP (obj) 1778 else if (INTEGERP (obj)
@@ -1731,11 +1781,11 @@ lisp_data_to_selection_data (Display *display, Lisp_Object obj,
1731 || (CONSP (XCDR (obj)) 1781 || (CONSP (XCDR (obj))
1732 && INTEGERP (XCAR (XCDR (obj))))))) 1782 && INTEGERP (XCAR (XCDR (obj)))))))
1733 { 1783 {
1784 *data_ret = (unsigned char *) xmalloc (sizeof (long) + 1);
1734 *format_ret = 32; 1785 *format_ret = 32;
1735 *size_ret = 1; 1786 *size_ret = 1;
1736 *data_ret = (unsigned char *) xmalloc (sizeof (long) + 1);
1737 (*data_ret) [sizeof (long)] = 0; 1787 (*data_ret) [sizeof (long)] = 0;
1738 (*(unsigned long **) data_ret) [0] = cons_to_unsigned (obj, ULONG_MAX); 1788 (*(long **) data_ret) [0] = cons_to_signed (obj, X_LONG_MIN, X_LONG_MAX);
1739 if (NILP (type)) type = QINTEGER; 1789 if (NILP (type)) type = QINTEGER;
1740 } 1790 }
1741 else if (VECTORP (obj)) 1791 else if (VECTORP (obj))
@@ -1744,50 +1794,55 @@ lisp_data_to_selection_data (Display *display, Lisp_Object obj,
1744 a set of 16 or 32 bit INTEGERs; 1794 a set of 16 or 32 bit INTEGERs;
1745 or a set of ATOM_PAIRs (represented as [[A1 A2] [A3 A4] ...] 1795 or a set of ATOM_PAIRs (represented as [[A1 A2] [A3 A4] ...]
1746 */ 1796 */
1747 int i; 1797 ptrdiff_t i;
1798 ptrdiff_t size = ASIZE (obj);
1748 1799
1749 if (SYMBOLP (XVECTOR (obj)->contents [0])) 1800 if (SYMBOLP (XVECTOR (obj)->contents [0]))
1750 /* This vector is an ATOM set */ 1801 /* This vector is an ATOM set */
1751 { 1802 {
1752 if (NILP (type)) type = QATOM; 1803 if (NILP (type)) type = QATOM;
1753 *size_ret = ASIZE (obj); 1804 for (i = 0; i < size; i++)
1754 *format_ret = 32;
1755 for (i = 0; i < *size_ret; i++)
1756 if (!SYMBOLP (XVECTOR (obj)->contents [i])) 1805 if (!SYMBOLP (XVECTOR (obj)->contents [i]))
1757 signal_error ("All elements of selection vector must have same type", obj); 1806 signal_error ("All elements of selection vector must have same type", obj);
1758 1807
1759 *data_ret = (unsigned char *) xmalloc ((*size_ret) * sizeof (Atom)); 1808 *data_ret = xnmalloc (size, sizeof (Atom));
1760 for (i = 0; i < *size_ret; i++) 1809 *format_ret = 32;
1810 *size_ret = size;
1811 for (i = 0; i < size; i++)
1761 (*(Atom **) data_ret) [i] 1812 (*(Atom **) data_ret) [i]
1762 = symbol_to_x_atom (dpyinfo, XVECTOR (obj)->contents [i]); 1813 = symbol_to_x_atom (dpyinfo, XVECTOR (obj)->contents [i]);
1763 } 1814 }
1764 else 1815 else
1765 /* This vector is an INTEGER set, or something like it */ 1816 /* This vector is an INTEGER set, or something like it */
1766 { 1817 {
1767 int data_size = 2; 1818 int format = 16;
1768 *size_ret = ASIZE (obj); 1819 int data_size = sizeof (short);
1769 if (NILP (type)) type = QINTEGER; 1820 if (NILP (type)) type = QINTEGER;
1770 *format_ret = 16; 1821 for (i = 0; i < size; i++)
1771 for (i = 0; i < *size_ret; i++) 1822 {
1772 if (CONSP (XVECTOR (obj)->contents [i])) 1823 intmax_t v = cons_to_signed (XVECTOR (obj)->contents[i],
1773 *format_ret = 32; 1824 X_LONG_MIN, X_LONG_MAX);
1774 else if (!INTEGERP (XVECTOR (obj)->contents [i])) 1825 if (X_SHRT_MIN <= v && v <= X_SHRT_MAX)
1775 signal_error (/* Qselection_error */ 1826 {
1776 "Elements of selection vector must be integers or conses of integers", 1827 /* Use sizeof (long) even if it is more than 32 bits.
1777 obj); 1828 See comment in x_get_window_property and
1778 1829 x_fill_property_data. */
1779 /* Use sizeof(long) even if it is more than 32 bits. See comment 1830 data_size = sizeof (long);
1780 in x_get_window_property and x_fill_property_data. */ 1831 format = 32;
1781 1832 }
1782 if (*format_ret == 32) data_size = sizeof(long); 1833 }
1783 *data_ret = (unsigned char *) xmalloc (*size_ret * data_size); 1834 *data_ret = xnmalloc (size, data_size);
1784 for (i = 0; i < *size_ret; i++) 1835 *format_ret = format;
1785 if (*format_ret == 32) 1836 *size_ret = size;
1786 (*((unsigned long **) data_ret)) [i] = 1837 for (i = 0; i < size; i++)
1787 cons_to_unsigned (XVECTOR (obj)->contents [i], ULONG_MAX); 1838 {
1788 else 1839 long v = cons_to_signed (XVECTOR (obj)->contents[i],
1789 (*((unsigned short **) data_ret)) [i] = 1840 X_LONG_MIN, X_LONG_MAX);
1790 cons_to_unsigned (XVECTOR (obj)->contents [i], USHRT_MAX); 1841 if (format == 32)
1842 (*((long **) data_ret)) [i] = v;
1843 else
1844 (*((short **) data_ret)) [i] = v;
1845 }
1791 } 1846 }
1792 } 1847 }
1793 else 1848 else
@@ -1817,8 +1872,8 @@ clean_local_selection_data (Lisp_Object obj)
1817 } 1872 }
1818 if (VECTORP (obj)) 1873 if (VECTORP (obj))
1819 { 1874 {
1820 int i; 1875 ptrdiff_t i;
1821 int size = ASIZE (obj); 1876 ptrdiff_t size = ASIZE (obj);
1822 Lisp_Object copy; 1877 Lisp_Object copy;
1823 if (size == 1) 1878 if (size == 1)
1824 return clean_local_selection_data (XVECTOR (obj)->contents [0]); 1879 return clean_local_selection_data (XVECTOR (obj)->contents [0]);
@@ -2213,6 +2268,8 @@ x_check_property_data (Lisp_Object data)
2213 else if (CONSP (o) && 2268 else if (CONSP (o) &&
2214 (! NUMBERP (XCAR (o)) || ! NUMBERP (XCDR (o)))) 2269 (! NUMBERP (XCAR (o)) || ! NUMBERP (XCDR (o))))
2215 return -1; 2270 return -1;
2271 if (size == INT_MAX)
2272 return -1;
2216 size++; 2273 size++;
2217 } 2274 }
2218 2275
@@ -2294,8 +2351,11 @@ Lisp_Object
2294x_property_data_to_lisp (struct frame *f, const unsigned char *data, 2351x_property_data_to_lisp (struct frame *f, const unsigned char *data,
2295 Atom type, int format, long unsigned int size) 2352 Atom type, int format, long unsigned int size)
2296{ 2353{
2354 ptrdiff_t format_bytes = format >> 3;
2355 if (PTRDIFF_MAX / format_bytes < size)
2356 memory_full (SIZE_MAX);
2297 return selection_data_to_lisp_data (FRAME_X_DISPLAY (f), 2357 return selection_data_to_lisp_data (FRAME_X_DISPLAY (f),
2298 data, size*format/8, type, format); 2358 data, size * format_bytes, type, format);
2299} 2359}
2300 2360
2301/* Get the mouse position in frame relative coordinates. */ 2361/* Get the mouse position in frame relative coordinates. */
@@ -2401,15 +2461,9 @@ FRAME is on. If FRAME is nil, the selected frame is used. */)
2401 return Qnil; 2461 return Qnil;
2402 2462
2403 if (dpyinfo->x_dnd_atoms_length == dpyinfo->x_dnd_atoms_size) 2463 if (dpyinfo->x_dnd_atoms_length == dpyinfo->x_dnd_atoms_size)
2404 { 2464 dpyinfo->x_dnd_atoms =
2405 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *dpyinfo->x_dnd_atoms / 2 2465 xpalloc (dpyinfo->x_dnd_atoms, &dpyinfo->x_dnd_atoms_size,
2406 < dpyinfo->x_dnd_atoms_size) 2466 1, -1, sizeof *dpyinfo->x_dnd_atoms);
2407 memory_full (SIZE_MAX);
2408 dpyinfo->x_dnd_atoms_size *= 2;
2409 dpyinfo->x_dnd_atoms = xrealloc (dpyinfo->x_dnd_atoms,
2410 sizeof (*dpyinfo->x_dnd_atoms)
2411 * dpyinfo->x_dnd_atoms_size);
2412 }
2413 2467
2414 dpyinfo->x_dnd_atoms[dpyinfo->x_dnd_atoms_length++] = x_atom; 2468 dpyinfo->x_dnd_atoms[dpyinfo->x_dnd_atoms_length++] = x_atom;
2415 return Qnil; 2469 return Qnil;
@@ -2444,7 +2498,7 @@ x_handle_dnd_message (struct frame *f, XClientMessageEvent *event, struct x_disp
2444 if (32 < BITS_PER_LONG && event->format == 32) 2498 if (32 < BITS_PER_LONG && event->format == 32)
2445 { 2499 {
2446 for (i = 0; i < 5; ++i) /* There are only 5 longs in a ClientMessage. */ 2500 for (i = 0; i < 5; ++i) /* There are only 5 longs in a ClientMessage. */
2447 idata[i] = (int) event->data.l[i]; 2501 idata[i] = event->data.l[i];
2448 data = (unsigned char *) idata; 2502 data = (unsigned char *) idata;
2449 } 2503 }
2450 2504
diff --git a/src/xsmfns.c b/src/xsmfns.c
index cb56ae648d1..55daec73307 100644
--- a/src/xsmfns.c
+++ b/src/xsmfns.c
@@ -223,9 +223,11 @@ smc_save_yourself_CB (SmcConn smcConn,
223 props[props_idx]->name = xstrdup (SmRestartCommand); 223 props[props_idx]->name = xstrdup (SmRestartCommand);
224 props[props_idx]->type = xstrdup (SmLISTofARRAY8); 224 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
225 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */ 225 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
226 if (INT_MAX - 3 < initial_argc)
227 memory_full (SIZE_MAX);
226 i = 3 + initial_argc; 228 i = 3 + initial_argc;
227 props[props_idx]->num_vals = i; 229 props[props_idx]->num_vals = i;
228 vp = (SmPropValue *) xmalloc (i * sizeof(*vp)); 230 vp = xnmalloc (i, sizeof *vp);
229 props[props_idx]->vals = vp; 231 props[props_idx]->vals = vp;
230 props[props_idx]->vals[vp_idx].length = strlen (emacs_program); 232 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
231 props[props_idx]->vals[vp_idx++].value = emacs_program; 233 props[props_idx]->vals[vp_idx++].value = emacs_program;
diff --git a/src/xterm.c b/src/xterm.c
index cefb98a476d..be456a61a6f 100644
--- a/src/xterm.c
+++ b/src/xterm.c
@@ -1662,19 +1662,18 @@ x_color_cells (Display *dpy, int *ncells)
1662 if (dpyinfo->color_cells == NULL) 1662 if (dpyinfo->color_cells == NULL)
1663 { 1663 {
1664 Screen *screen = dpyinfo->screen; 1664 Screen *screen = dpyinfo->screen;
1665 int ncolor_cells = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1665 int i; 1666 int i;
1666 1667
1667 dpyinfo->ncolor_cells 1668 dpyinfo->color_cells = xnmalloc (ncolor_cells,
1668 = XDisplayCells (dpy, XScreenNumberOfScreen (screen)); 1669 sizeof *dpyinfo->color_cells);
1669 dpyinfo->color_cells 1670 dpyinfo->ncolor_cells = ncolor_cells;
1670 = (XColor *) xmalloc (dpyinfo->ncolor_cells
1671 * sizeof *dpyinfo->color_cells);
1672 1671
1673 for (i = 0; i < dpyinfo->ncolor_cells; ++i) 1672 for (i = 0; i < ncolor_cells; ++i)
1674 dpyinfo->color_cells[i].pixel = i; 1673 dpyinfo->color_cells[i].pixel = i;
1675 1674
1676 XQueryColors (dpy, dpyinfo->cmap, 1675 XQueryColors (dpy, dpyinfo->cmap,
1677 dpyinfo->color_cells, dpyinfo->ncolor_cells); 1676 dpyinfo->color_cells, ncolor_cells);
1678 } 1677 }
1679 1678
1680 *ncells = dpyinfo->ncolor_cells; 1679 *ncells = dpyinfo->ncolor_cells;
@@ -4233,7 +4232,7 @@ xt_action_hook (Widget widget, XtPointer client_data, String action_name,
4233 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */ 4232 x_send_scroll_bar_event and x_scroll_bar_to_input_event. */
4234 4233
4235static struct window **scroll_bar_windows; 4234static struct window **scroll_bar_windows;
4236static size_t scroll_bar_windows_size; 4235static ptrdiff_t scroll_bar_windows_size;
4237 4236
4238 4237
4239/* Send a client message with message type Xatom_Scrollbar for a 4238/* Send a client message with message type Xatom_Scrollbar for a
@@ -4248,7 +4247,7 @@ x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4248 XClientMessageEvent *ev = (XClientMessageEvent *) &event; 4247 XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4249 struct window *w = XWINDOW (window); 4248 struct window *w = XWINDOW (window);
4250 struct frame *f = XFRAME (w->frame); 4249 struct frame *f = XFRAME (w->frame);
4251 size_t i; 4250 ptrdiff_t i;
4252 4251
4253 BLOCK_INPUT; 4252 BLOCK_INPUT;
4254 4253
@@ -4269,16 +4268,15 @@ x_send_scroll_bar_event (Lisp_Object window, int part, int portion, int whole)
4269 4268
4270 if (i == scroll_bar_windows_size) 4269 if (i == scroll_bar_windows_size)
4271 { 4270 {
4272 size_t new_size = max (10, 2 * scroll_bar_windows_size); 4271 ptrdiff_t old_nbytes =
4273 size_t nbytes = new_size * sizeof *scroll_bar_windows; 4272 scroll_bar_windows_size * sizeof *scroll_bar_windows;
4274 size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows; 4273 ptrdiff_t nbytes;
4275 4274 enum { XClientMessageEvent_MAX = 0x7fffffff };
4276 if ((size_t) -1 / sizeof *scroll_bar_windows < new_size) 4275 scroll_bar_windows =
4277 memory_full (SIZE_MAX); 4276 xpalloc (scroll_bar_windows, &scroll_bar_windows_size, 1,
4278 scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows, 4277 XClientMessageEvent_MAX, sizeof *scroll_bar_windows);
4279 nbytes); 4278 nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4280 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes); 4279 memset (&scroll_bar_windows[i], 0, nbytes - old_nbytes);
4281 scroll_bar_windows_size = new_size;
4282 } 4280 }
4283 4281
4284 scroll_bar_windows[i] = w; 4282 scroll_bar_windows[i] = w;
@@ -5856,11 +5854,12 @@ handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
5856 } inev; 5854 } inev;
5857 int count = 0; 5855 int count = 0;
5858 int do_help = 0; 5856 int do_help = 0;
5859 int nbytes = 0; 5857 ptrdiff_t nbytes = 0;
5860 struct frame *f = NULL; 5858 struct frame *f = NULL;
5861 struct coding_system coding; 5859 struct coding_system coding;
5862 XEvent event = *eventptr; 5860 XEvent event = *eventptr;
5863 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight; 5861 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
5862 USE_SAFE_ALLOCA;
5864 5863
5865 *finish = X_EVENT_NORMAL; 5864 *finish = X_EVENT_NORMAL;
5866 5865
@@ -6556,7 +6555,7 @@ handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
6556 } 6555 }
6557 6556
6558 { /* Raw bytes, not keysym. */ 6557 { /* Raw bytes, not keysym. */
6559 register int i; 6558 ptrdiff_t i;
6560 int nchars, len; 6559 int nchars, len;
6561 6560
6562 for (i = 0, nchars = 0; i < nbytes; i++) 6561 for (i = 0, nchars = 0; i < nbytes; i++)
@@ -6569,7 +6568,6 @@ handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
6569 if (nchars < nbytes) 6568 if (nchars < nbytes)
6570 { 6569 {
6571 /* Decode the input data. */ 6570 /* Decode the input data. */
6572 int require;
6573 6571
6574 /* The input should be decoded with `coding_system' 6572 /* The input should be decoded with `coding_system'
6575 which depends on which X*LookupString function 6573 which depends on which X*LookupString function
@@ -6582,9 +6580,9 @@ handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
6582 gives us composition information. */ 6580 gives us composition information. */
6583 coding.common_flags &= ~CODING_ANNOTATION_MASK; 6581 coding.common_flags &= ~CODING_ANNOTATION_MASK;
6584 6582
6585 require = MAX_MULTIBYTE_LENGTH * nbytes; 6583 SAFE_NALLOCA (coding.destination, MAX_MULTIBYTE_LENGTH,
6586 coding.destination = alloca (require); 6584 nbytes);
6587 coding.dst_bytes = require; 6585 coding.dst_bytes = MAX_MULTIBYTE_LENGTH * nbytes;
6588 coding.mode |= CODING_MODE_LAST_BLOCK; 6586 coding.mode |= CODING_MODE_LAST_BLOCK;
6589 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil); 6587 decode_coding_c_string (&coding, copy_bufptr, nbytes, Qnil);
6590 nbytes = coding.produced; 6588 nbytes = coding.produced;
@@ -7043,6 +7041,7 @@ handle_one_xevent (struct x_display_info *dpyinfo, XEvent *eventptr,
7043 count++; 7041 count++;
7044 } 7042 }
7045 7043
7044 SAFE_FREE ();
7046 *eventptr = event; 7045 *eventptr = event;
7047 return count; 7046 return count;
7048} 7047}
@@ -9872,6 +9871,7 @@ x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
9872 struct x_display_info *dpyinfo; 9871 struct x_display_info *dpyinfo;
9873 XrmDatabase xrdb; 9872 XrmDatabase xrdb;
9874 Mouse_HLInfo *hlinfo; 9873 Mouse_HLInfo *hlinfo;
9874 ptrdiff_t lim;
9875 9875
9876 BLOCK_INPUT; 9876 BLOCK_INPUT;
9877 9877
@@ -10094,12 +10094,15 @@ x_term_init (Lisp_Object display_name, char *xrm_option, char *resource_name)
10094 XSetAfterFunction (x_current_display, x_trace_wire); 10094 XSetAfterFunction (x_current_display, x_trace_wire);
10095#endif /* ! 0 */ 10095#endif /* ! 0 */
10096 10096
10097 lim = min (PTRDIFF_MAX, SIZE_MAX) - sizeof "@";
10098 if (lim - SBYTES (Vinvocation_name) < SBYTES (Vsystem_name))
10099 memory_full (SIZE_MAX);
10097 dpyinfo->x_id_name 10100 dpyinfo->x_id_name
10098 = (char *) xmalloc (SBYTES (Vinvocation_name) 10101 = (char *) xmalloc (SBYTES (Vinvocation_name)
10099 + SBYTES (Vsystem_name) 10102 + SBYTES (Vsystem_name)
10100 + 2); 10103 + 2);
10101 sprintf (dpyinfo->x_id_name, "%s@%s", 10104 strcat (strcat (strcpy (dpyinfo->x_id_name, SSDATA (Vinvocation_name)), "@"),
10102 SSDATA (Vinvocation_name), SSDATA (Vsystem_name)); 10105 SSDATA (Vsystem_name));
10103 10106
10104 /* Figure out which modifier bits mean what. */ 10107 /* Figure out which modifier bits mean what. */
10105 x_find_modifier_meanings (dpyinfo); 10108 x_find_modifier_meanings (dpyinfo);