aboutsummaryrefslogtreecommitdiff
path: root/libjava/classpath/java/awt/TextComponent.java
blob: 31ea3f5de5bc03551080f0e5a62de7206b8d6172 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/* TextComponent.java -- Widgets for entering text
   Copyright (C) 1999, 2002, 2003, 2006, Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.awt;

import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.peer.TextComponentPeer;
import java.io.Serializable;
import java.text.BreakIterator;
import java.util.EventListener;

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import javax.accessibility.AccessibleText;
import javax.swing.text.AttributeSet;

/**
 * This class provides common functionality for widgets than
 * contain text.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 */
public class TextComponent extends Component
  implements Serializable, Accessible
{

  private static final long serialVersionUID = -2214773872412987419L;

  /**
   * @serial Indicates whether or not this component is editable.
   * This is package-private to avoid an accessor method.
   */
  boolean editable;

  /**
   * @serial The starting position of the selected text region.
   * This is package-private to avoid an accessor method.
   */
  int selectionStart;

  /**
   * @serial The ending position of the selected text region.
   * This is package-private to avoid an accessor method.
   */
  int selectionEnd;

  /**
   * @serial The text in the component
   * This is package-private to avoid an accessor method.
   */
  String text;

  /**
   * A list of listeners that will receive events from this object.
   */
  protected transient TextListener textListener;

  protected class AccessibleAWTTextComponent
    extends AccessibleAWTComponent
    implements AccessibleText, TextListener
  {
    private static final long serialVersionUID = 3631432373506317811L;

    // Constructor
    // Adds a listener for tracking caret changes
    public AccessibleAWTTextComponent()
    {
      TextComponent.this.addTextListener(this);
    }

    public AccessibleRole getAccessibleRole()
    {
      return AccessibleRole.TEXT;
    }

    public AccessibleStateSet getAccessibleStateSet()
    {
      // TODO: Docs say PropertyChangeEvent will fire if this state changes.
      // That means that the event has to fire when editable changes.
      AccessibleStateSet ss = super.getAccessibleStateSet();
      if (editable)
        ss.add(AccessibleState.EDITABLE);
      return ss;
    }

    public AccessibleText getAccessibleText()
    {
      return this;
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getIndexAtPoint(java.awt.Point)
     */
    public int getIndexAtPoint(Point point)
    {
      return TextComponent.this.getIndexAtPoint(point);
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getCharacterBounds(int)
     */
    public Rectangle getCharacterBounds(int index)
    {
      return TextComponent.this.getCharacterBounds(index);
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getCharCount()
     */
    public int getCharCount()
    {
      return text.length();
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getCaretPosition()
     */
    public int getCaretPosition()
    {
      return TextComponent.this.getCaretPosition();
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getAtIndex(int, int)
     */
    public String getAtIndex(int part, int index)
    {
      if (index < 0 || index >= text.length())
        return null;
      BreakIterator it = null;
      switch (part)
      {
        case CHARACTER:
          return text.substring(index, index + 1);
        case WORD:
          it = BreakIterator.getWordInstance();
          break;
        case SENTENCE:
          it = BreakIterator.getSentenceInstance();
          break;
        default:
          return null;
      }
          it.setText(text);
          int start = index;
          if (!it.isBoundary(index))
            start = it.preceding(index);
          int end = it.following(index);
          if (end == -1)
            return text.substring(index);
          else
            return text.substring(index, end);
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getAfterIndex(int, int)
     */
    public String getAfterIndex(int part, int index) {
      if (index < 0 || index >= text.length())
        return null;
      BreakIterator it = null;
      switch (part)
      {
        case CHARACTER:
          return text.substring(index, index + 1);
        case WORD:
          it = BreakIterator.getWordInstance();
          break;
        case SENTENCE:
          it = BreakIterator.getSentenceInstance();
          break;
        default:
          return null;
      }
          it.setText(text);
          int start = index;
          if (!it.isBoundary(index))
            start = it.following(index);
          // Make sure there was a complete unit.  I.e. if index is in the middle
          // of a word, return null if there is no word after the that one.
          if (start == -1)
            return null;
          int end = it.following(start);
          if (end == -1)
            return text.substring(index);
          else
            return text.substring(index, end);
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getBeforeIndex(int, int)
     */
    public String getBeforeIndex(int part, int index)
    {
      if (index < 1 || index >= text.length())
        return null;
      BreakIterator it = null;
      switch (part)
      {
        case CHARACTER:
          return text.substring(index - 1, index);
        case WORD:
          it = BreakIterator.getWordInstance();
          break;
        case SENTENCE:
          it = BreakIterator.getSentenceInstance();
          break;
        default:
          return null;
      }
          it.setText(text);
          int end = index;
          if (!it.isBoundary(index))
            end = it.preceding(index);
          // Make sure there was a complete unit.  I.e. if index is in the middle
          // of a word, return null if there is no word before that one.
          if (end == -1)
            return null;
          int start = it.preceding(end);
          if (start == -1)
            return text.substring(0, end);
          else
            return text.substring(start, end);
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getCharacterAttribute(int)
     */
    public AttributeSet getCharacterAttribute(int index)
    {
      // FIXME: I suspect this really gets filled in by subclasses.
      return null;
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getSelectionStart()
     */
    public int getSelectionStart() {
      // TODO Auto-generated method stub
      return selectionStart;
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getSelectionEnd()
     */
    public int getSelectionEnd()
    {
      return selectionEnd;
    }

    /* (non-Javadoc)
     * @see javax.accessibility.AccessibleText#getSelectedText()
     */
    public String getSelectedText()
    {
      if (selectionEnd - selectionStart > 0)
        return text.substring(selectionStart, selectionEnd);
      else
        return null;
    }

    /* (non-Javadoc)
     * @see java.awt.event.TextListener#textValueChanged(java.awt.event.TextEvent)
     */
    public void textValueChanged(TextEvent event)
    {
      // TODO Auto-generated method stub

    }

  }


  TextComponent(String text)
  {
    if (text == null)
      this.text = "";
    else
      this.text = text;

    this.editable = true;
  }


  /**
   * Returns the text in this component
   *
   * @return The text in this component.
   */
  public synchronized String getText()
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      text = tcp.getText();

    return(text);
  }

  /**
   * Sets the text in this component to the specified string.
   *
   * @param text The new text for this component.
   */
  public synchronized void setText(String text)
  {
    if (text == null)
      text = "";

    this.text = text;

    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      tcp.setText(text);
    setCaretPosition(0);
  }

  /**
   * Returns a string that contains the text that is currently selected.
   *
   * @return The currently selected text region.
   */
  public synchronized String getSelectedText()
  {
    String alltext = getText();
    int start = getSelectionStart();
    int end = getSelectionEnd();

    return(alltext.substring(start, end));
  }

  /**
   * Returns the starting position of the selected text region.
   * If the text is not selected then caret position is returned.
   *
   * @return The starting position of the selected text region.
   */
  public synchronized int getSelectionStart()
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      selectionStart = tcp.getSelectionStart();

    return(selectionStart);
  }

  /**
   * Sets the starting position of the selected region to the
   * specified value.  If the specified value is out of range, then it
   * will be silently changed to the nearest legal value.
   *
   * @param selectionStart The new start position for selected text.
   */
  public synchronized void setSelectionStart(int selectionStart)
  {
    select(selectionStart,
           (getSelectionEnd() < selectionStart)
                              ? selectionStart : getSelectionEnd());
  }

  /**
   * Returns the ending position of the selected text region.
   * If the text is not selected, then caret position is returned
   *
   * @return The ending position of the selected text region.
   */
  public synchronized int getSelectionEnd()
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      selectionEnd = tcp.getSelectionEnd();

    return(selectionEnd);
  }

  /**
   * Sets the ending position of the selected region to the
   * specified value.  If the specified value is out of range, then it
   * will be silently changed to the nearest legal value.
   *
   * @param selectionEnd The new start position for selected text.
   */
  public synchronized void setSelectionEnd(int selectionEnd)
  {
    select(getSelectionStart(), selectionEnd);
  }

  /**
   * This method sets the selected text range to the text between the
   * specified start and end positions.  Illegal values for these
   * positions are silently fixed.
   *
   * @param selectionStart The new start position for the selected text.
   * @param selectionEnd The new end position for the selected text.
   */
  public synchronized void select(int selectionStart, int selectionEnd)
  {
    if (selectionStart < 0)
      selectionStart = 0;

    if (selectionStart > getText().length())
      selectionStart = text.length();

    if (selectionEnd > text.length())
      selectionEnd = text.length();

    if (selectionStart > selectionEnd)
      selectionStart = selectionEnd;

    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;

    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      tcp.select(selectionStart, selectionEnd);
  }

  /**
   * Selects all of the text in the component.
   */
  public synchronized void selectAll()
  {
    select(0, getText().length());
  }

  /**
   * Returns the current caret position in the text.
   *
   * @return The caret position in the text.
   */
  public synchronized int getCaretPosition()
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      return(tcp.getCaretPosition());
    else
      return(0);
  }

  /**
   * Sets the caret position to the specified value.
   *
   * @param caretPosition The new caret position.
   *
   * @exception IllegalArgumentException If the value supplied for position
   * is less than zero.
   *
   * @since 1.1
   */
  public synchronized void setCaretPosition(int caretPosition)
  {
    if (caretPosition < 0)
      throw new IllegalArgumentException();

    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      tcp.setCaretPosition(caretPosition);
  }

  /**
   * Tests whether or not this component's text can be edited.
   *
   * @return <code>true</code> if the text can be edited, <code>false</code>
   * otherwise.
   */
  public boolean isEditable()
  {
    return(editable);
  }

  /**
   * Sets whether or not this component's text can be edited.
   *
   * @param editable <code>true</code> to enable editing of the text,
   * <code>false</code> to disable it.
   */
  public synchronized void setEditable(boolean editable)
  {
    this.editable = editable;

    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      tcp.setEditable(editable);
  }

  /**
   * Notifies the component that it should destroy its native peer.
   */
  public void removeNotify()
  {
    super.removeNotify();
  }

  /**
   * Adds a new listener to the list of text listeners for this
   * component.
   *
   * @param listener The listener to be added.
   */
  public synchronized void addTextListener(TextListener listener)
  {
    textListener = AWTEventMulticaster.add(textListener, listener);

    enableEvents(AWTEvent.TEXT_EVENT_MASK);
  }

  /**
   * Removes the specified listener from the list of listeners
   * for this component.
   *
   * @param listener The listener to remove.
   */
  public synchronized void removeTextListener(TextListener listener)
  {
    textListener = AWTEventMulticaster.remove(textListener, listener);
  }

  /**
   * Processes the specified event for this component.  Text events are
   * processed by calling the <code>processTextEvent()</code> method.
   * All other events are passed to the superclass method.
   *
   * @param event The event to process.
   */
  protected void processEvent(AWTEvent event)
  {
    if (event instanceof TextEvent)
      processTextEvent((TextEvent)event);
    else
      super.processEvent(event);
  }

  /**
   * Processes the specified text event by dispatching it to any listeners
   * that are registered.  Note that this method will only be called
   * if text event's are enabled.  This will be true if there are any
   * registered listeners, or if the event has been specifically
   * enabled using <code>enableEvents()</code>.
   *
   * @param event The text event to process.
   */
  protected void processTextEvent(TextEvent event)
  {
    if (textListener != null)
      textListener.textValueChanged(event);
  }

  void dispatchEventImpl(AWTEvent e)
  {
    if (e.id <= TextEvent.TEXT_LAST
        && e.id >= TextEvent.TEXT_FIRST
        && (textListener != null
            || (eventMask & AWTEvent.TEXT_EVENT_MASK) != 0))
      processEvent(e);
    else
      super.dispatchEventImpl(e);
  }

  /**
   * Returns a debugging string.
   *
   * @return A debugging string.
   */
  protected String paramString()
  {
    return(getClass().getName() + "(text=" + getText() + ")");
  }

  /**
   * Returns an array of all the objects currently registered as FooListeners
   * upon this <code>TextComponent</code>. FooListeners are registered using
   * the addFooListener method.
   *
   * @exception ClassCastException If listenerType doesn't specify a class or
   * interface that implements java.util.EventListener.
   */
  public <T extends EventListener> T[] getListeners(Class<T> listenerType)
  {
    if (listenerType == TextListener.class)
      return AWTEventMulticaster.getListeners(textListener, listenerType);

    return super.getListeners(listenerType);
  }

  /**
   * Returns all text listeners registered to this object.
   */
  public TextListener[] getTextListeners()
  {
    return (TextListener[]) getListeners(TextListener.class);
  }

  /**
   * Gets the AccessibleContext associated with this <code>TextComponent</code>.
   * The context is created, if necessary.
   *
   * @return the associated context
   */
  public AccessibleContext getAccessibleContext()
  {
    /* Create the context if this is the first request */
    if (accessibleContext == null)
      accessibleContext = new AccessibleAWTTextComponent();
    return accessibleContext;
  }


  // Provide AccessibleAWTTextComponent access to several peer functions that
  // aren't publicly exposed.  This is package-private to avoid an accessor
  // method.
  synchronized int getIndexAtPoint(Point p)
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      return tcp.getIndexAtPoint(p.x, p.y);
    return -1;
  }

  synchronized Rectangle getCharacterBounds(int i)
  {
    TextComponentPeer tcp = (TextComponentPeer) getPeer();
    if (tcp != null)
      return tcp.getCharacterBounds(i);
    return null;
  }

  /**
   * All old mouse events for this component should
   * be ignored.
   *
   * @return true to ignore all old mouse events.
   */
  static boolean ignoreOldMouseEvents()
  {
    return true;
  }

} // class TextComponent
='#n1570'>1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
/* Generic BFD library interface and support routines.
   Copyright (C) 1990-2015 Free Software Foundation, Inc.
   Written by Cygnus Support.

   This file is part of BFD, the Binary File Descriptor library.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
   MA 02110-1301, USA.  */

/*
INODE
typedef bfd, Error reporting, BFD front end, BFD front end

SECTION
	<<typedef bfd>>

	A BFD has type <<bfd>>; objects of this type are the
	cornerstone of any application using BFD. Using BFD
	consists of making references though the BFD and to data in the BFD.

	Here is the structure that defines the type <<bfd>>.  It
	contains the major data about the file and pointers
	to the rest of the data.

CODE_FRAGMENT
.
.enum bfd_direction
.  {
.    no_direction = 0,
.    read_direction = 1,
.    write_direction = 2,
.    both_direction = 3
.  };
.
.enum bfd_plugin_format
.  {
.    bfd_plugin_uknown = 0,
.    bfd_plugin_yes = 1,
.    bfd_plugin_no = 2
.  };
.
.struct bfd_build_id
.  {
.    bfd_size_type size;
.    bfd_byte data[1];
.  };
.
.struct bfd
.{
.  {* The filename the application opened the BFD with.  *}
.  const char *filename;
.
.  {* A pointer to the target jump table.  *}
.  const struct bfd_target *xvec;
.
.  {* The IOSTREAM, and corresponding IO vector that provide access
.     to the file backing the BFD.  *}
.  void *iostream;
.  const struct bfd_iovec *iovec;
.
.  {* The caching routines use these to maintain a
.     least-recently-used list of BFDs.  *}
.  struct bfd *lru_prev, *lru_next;
.
.  {* When a file is closed by the caching routines, BFD retains
.     state information on the file here...  *}
.  ufile_ptr where;
.
.  {* File modified time, if mtime_set is TRUE.  *}
.  long mtime;
.
.  {* A unique identifier of the BFD  *}
.  unsigned int id;
.
.  {* The format which belongs to the BFD. (object, core, etc.)  *}
.  ENUM_BITFIELD (bfd_format) format : 3;
.
.  {* The direction with which the BFD was opened.  *}
.  ENUM_BITFIELD (bfd_direction) direction : 2;
.
.  {* Format_specific flags.  *}
.  flagword flags : 18;
.
.  {* Values that may appear in the flags field of a BFD.  These also
.     appear in the object_flags field of the bfd_target structure, where
.     they indicate the set of flags used by that backend (not all flags
.     are meaningful for all object file formats) (FIXME: at the moment,
.     the object_flags values have mostly just been copied from backend
.     to another, and are not necessarily correct).  *}
.
.#define BFD_NO_FLAGS	0x00
.
.  {* BFD contains relocation entries.  *}
.#define HAS_RELOC   	0x01
.
.  {* BFD is directly executable.  *}
.#define EXEC_P      	0x02
.
.  {* BFD has line number information (basically used for F_LNNO in a
.     COFF header).  *}
.#define HAS_LINENO  	0x04
.
.  {* BFD has debugging information.  *}
.#define HAS_DEBUG   	0x08
.
.  {* BFD has symbols.  *}
.#define HAS_SYMS    	0x10
.
.  {* BFD has local symbols (basically used for F_LSYMS in a COFF
.     header).  *}
.#define HAS_LOCALS  	0x20
.
.  {* BFD is a dynamic object.  *}
.#define DYNAMIC     	0x40
.
.  {* Text section is write protected (if D_PAGED is not set, this is
.     like an a.out NMAGIC file) (the linker sets this by default, but
.     clears it for -r or -N).  *}
.#define WP_TEXT     	0x80
.
.  {* BFD is dynamically paged (this is like an a.out ZMAGIC file) (the
.     linker sets this by default, but clears it for -r or -n or -N).  *}
.#define D_PAGED     	0x100
.
.  {* BFD is relaxable (this means that bfd_relax_section may be able to
.     do something) (sometimes bfd_relax_section can do something even if
.     this is not set).  *}
.#define BFD_IS_RELAXABLE 0x200
.
.  {* This may be set before writing out a BFD to request using a
.     traditional format.  For example, this is used to request that when
.     writing out an a.out object the symbols not be hashed to eliminate
.     duplicates.  *}
.#define BFD_TRADITIONAL_FORMAT 0x400
.
.  {* This flag indicates that the BFD contents are actually cached
.     in memory.  If this is set, iostream points to a bfd_in_memory
.     struct.  *}
.#define BFD_IN_MEMORY 0x800
.
.  {* This BFD has been created by the linker and doesn't correspond
.     to any input file.  *}
.#define BFD_LINKER_CREATED 0x1000
.
.  {* This may be set before writing out a BFD to request that it
.     be written using values for UIDs, GIDs, timestamps, etc. that
.     will be consistent from run to run.  *}
.#define BFD_DETERMINISTIC_OUTPUT 0x2000
.
.  {* Compress sections in this BFD.  *}
.#define BFD_COMPRESS 0x4000
.
.  {* Decompress sections in this BFD.  *}
.#define BFD_DECOMPRESS 0x8000
.
.  {* BFD is a dummy, for plugins.  *}
.#define BFD_PLUGIN 0x10000
.
.  {* Compress sections in this BFD with SHF_COMPRESSED from gABI.  *}
.#define BFD_COMPRESS_GABI 0x20000
.
.  {* Flags bits to be saved in bfd_preserve_save.  *}
.#define BFD_FLAGS_SAVED \
.  (BFD_IN_MEMORY | BFD_COMPRESS | BFD_DECOMPRESS | BFD_PLUGIN \
.   | BFD_COMPRESS_GABI)
.
.  {* Flags bits which are for BFD use only.  *}
.#define BFD_FLAGS_FOR_BFD_USE_MASK \
.  (BFD_IN_MEMORY | BFD_COMPRESS | BFD_DECOMPRESS | BFD_LINKER_CREATED \
.   | BFD_PLUGIN | BFD_TRADITIONAL_FORMAT | BFD_DETERMINISTIC_OUTPUT \
.   | BFD_COMPRESS_GABI)
.
.  {* Is the file descriptor being cached?  That is, can it be closed as
.     needed, and re-opened when accessed later?  *}
.  unsigned int cacheable : 1;
.
.  {* Marks whether there was a default target specified when the
.     BFD was opened. This is used to select which matching algorithm
.     to use to choose the back end.  *}
.  unsigned int target_defaulted : 1;
.
.  {* ... and here: (``once'' means at least once).  *}
.  unsigned int opened_once : 1;
.
.  {* Set if we have a locally maintained mtime value, rather than
.     getting it from the file each time.  *}
.  unsigned int mtime_set : 1;
.
.  {* Flag set if symbols from this BFD should not be exported.  *}
.  unsigned int no_export : 1;
.
.  {* Remember when output has begun, to stop strange things
.     from happening.  *}
.  unsigned int output_has_begun : 1;
.
.  {* Have archive map.  *}
.  unsigned int has_armap : 1;
.
.  {* Set if this is a thin archive.  *}
.  unsigned int is_thin_archive : 1;
.
.  {* Set if only required symbols should be added in the link hash table for
.     this object.  Used by VMS linkers.  *}
.  unsigned int selective_search : 1;
.
.  {* Set if this is the linker output BFD.  *}
.  unsigned int is_linker_output : 1;
.
.  {* Set if this is the linker input BFD.  *}
.  unsigned int is_linker_input : 1;
.
.  {* If this is an input for a compiler plug-in library.  *}
.  ENUM_BITFIELD (bfd_plugin_format) plugin_format : 2;
.
.  {* Set if this is a plugin output file.  *}
.  unsigned int lto_output : 1;
.
.  {* Set to dummy BFD created when claimed by a compiler plug-in
.     library.  *}
.  bfd *plugin_dummy_bfd;
.
.  {* Currently my_archive is tested before adding origin to
.     anything. I believe that this can become always an add of
.     origin, with origin set to 0 for non archive files.  *}
.  ufile_ptr origin;
.
.  {* The origin in the archive of the proxy entry.  This will
.     normally be the same as origin, except for thin archives,
.     when it will contain the current offset of the proxy in the
.     thin archive rather than the offset of the bfd in its actual
.     container.  *}
.  ufile_ptr proxy_origin;
.
.  {* A hash table for section names.  *}
.  struct bfd_hash_table section_htab;
.
.  {* Pointer to linked list of sections.  *}
.  struct bfd_section *sections;
.
.  {* The last section on the section list.  *}
.  struct bfd_section *section_last;
.
.  {* The number of sections.  *}
.  unsigned int section_count;
.
.  {* A field used by _bfd_generic_link_add_archive_symbols.  This will
.     be used only for archive elements.  *}
.  int archive_pass;
.
.  {* Stuff only useful for object files:
.     The start address.  *}
.  bfd_vma start_address;
.
.  {* Symbol table for output BFD (with symcount entries).
.     Also used by the linker to cache input BFD symbols.  *}
.  struct bfd_symbol  **outsymbols;
.
.  {* Used for input and output.  *}
.  unsigned int symcount;
.
.  {* Used for slurped dynamic symbol tables.  *}
.  unsigned int dynsymcount;
.
.  {* Pointer to structure which contains architecture information.  *}
.  const struct bfd_arch_info *arch_info;
.
.  {* Stuff only useful for archives.  *}
.  void *arelt_data;
.  struct bfd *my_archive;      {* The containing archive BFD.  *}
.  struct bfd *archive_next;    {* The next BFD in the archive.  *}
.  struct bfd *archive_head;    {* The first BFD in the archive.  *}
.  struct bfd *nested_archives; {* List of nested archive in a flattened
.                                  thin archive.  *}
.
.  union {
.    {* For input BFDs, a chain of BFDs involved in a link.  *}
.    struct bfd *next;
.    {* For output BFD, the linker hash table.  *}
.    struct bfd_link_hash_table *hash;
.  } link;
.
.  {* Used by the back end to hold private data.  *}
.  union
.    {
.      struct aout_data_struct *aout_data;
.      struct artdata *aout_ar_data;
.      struct _oasys_data *oasys_obj_data;
.      struct _oasys_ar_data *oasys_ar_data;
.      struct coff_tdata *coff_obj_data;
.      struct pe_tdata *pe_obj_data;
.      struct xcoff_tdata *xcoff_obj_data;
.      struct ecoff_tdata *ecoff_obj_data;
.      struct ieee_data_struct *ieee_data;
.      struct ieee_ar_data_struct *ieee_ar_data;
.      struct srec_data_struct *srec_data;
.      struct verilog_data_struct *verilog_data;
.      struct ihex_data_struct *ihex_data;
.      struct tekhex_data_struct *tekhex_data;
.      struct elf_obj_tdata *elf_obj_data;
.      struct nlm_obj_tdata *nlm_obj_data;
.      struct bout_data_struct *bout_data;
.      struct mmo_data_struct *mmo_data;
.      struct sun_core_struct *sun_core_data;
.      struct sco5_core_struct *sco5_core_data;
.      struct trad_core_struct *trad_core_data;
.      struct som_data_struct *som_data;
.      struct hpux_core_struct *hpux_core_data;
.      struct hppabsd_core_struct *hppabsd_core_data;
.      struct sgi_core_struct *sgi_core_data;
.      struct lynx_core_struct *lynx_core_data;
.      struct osf_core_struct *osf_core_data;
.      struct cisco_core_struct *cisco_core_data;
.      struct versados_data_struct *versados_data;
.      struct netbsd_core_struct *netbsd_core_data;
.      struct mach_o_data_struct *mach_o_data;
.      struct mach_o_fat_data_struct *mach_o_fat_data;
.      struct plugin_data_struct *plugin_data;
.      struct bfd_pef_data_struct *pef_data;
.      struct bfd_pef_xlib_data_struct *pef_xlib_data;
.      struct bfd_sym_data_struct *sym_data;
.      void *any;
.    }
.  tdata;
.
.  {* Used by the application to hold private data.  *}
.  void *usrdata;
.
.  {* Where all the allocated stuff under this BFD goes.  This is a
.     struct objalloc *, but we use void * to avoid requiring the inclusion
.     of objalloc.h.  *}
.  void *memory;
.
.  {* For input BFDs, the build ID, if the object has one. *}
.  const struct bfd_build_id *build_id;
.};
.
.{* See note beside bfd_set_section_userdata.  *}
.static inline bfd_boolean
.bfd_set_cacheable (bfd * abfd, bfd_boolean val)
.{
.  abfd->cacheable = val;
.  return TRUE;
.}
.
*/

#include "sysdep.h"
#include <stdarg.h>
#include "bfd.h"
#include "bfdver.h"
#include "libiberty.h"
#include "demangle.h"
#include "safe-ctype.h"
#include "bfdlink.h"
#include "libbfd.h"
#include "coff/internal.h"
#include "coff/sym.h"
#include "libcoff.h"
#include "libecoff.h"
#undef obj_symbols
#include "elf-bfd.h"

#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif


/* provide storage for subsystem, stack and heap data which may have been
   passed in on the command line.  Ld puts this data into a bfd_link_info
   struct which ultimately gets passed in to the bfd.  When it arrives, copy
   it to the following struct so that the data will be available in coffcode.h
   where it is needed.  The typedef's used are defined in bfd.h */

/*
INODE
Error reporting, Miscellaneous, typedef bfd, BFD front end

SECTION
	Error reporting

	Most BFD functions return nonzero on success (check their
	individual documentation for precise semantics).  On an error,
	they call <<bfd_set_error>> to set an error condition that callers
	can check by calling <<bfd_get_error>>.
        If that returns <<bfd_error_system_call>>, then check
	<<errno>>.

	The easiest way to report a BFD error to the user is to
	use <<bfd_perror>>.

SUBSECTION
	Type <<bfd_error_type>>

	The values returned by <<bfd_get_error>> are defined by the
	enumerated type <<bfd_error_type>>.

CODE_FRAGMENT
.
.typedef enum bfd_error
.{
.  bfd_error_no_error = 0,
.  bfd_error_system_call,
.  bfd_error_invalid_target,
.  bfd_error_wrong_format,
.  bfd_error_wrong_object_format,
.  bfd_error_invalid_operation,
.  bfd_error_no_memory,
.  bfd_error_no_symbols,
.  bfd_error_no_armap,
.  bfd_error_no_more_archived_files,
.  bfd_error_malformed_archive,
.  bfd_error_missing_dso,
.  bfd_error_file_not_recognized,
.  bfd_error_file_ambiguously_recognized,
.  bfd_error_no_contents,
.  bfd_error_nonrepresentable_section,
.  bfd_error_no_debug_section,
.  bfd_error_bad_value,
.  bfd_error_file_truncated,
.  bfd_error_file_too_big,
.  bfd_error_on_input,
.  bfd_error_invalid_error_code
.}
.bfd_error_type;
.
*/

static bfd_error_type bfd_error = bfd_error_no_error;
static bfd *input_bfd = NULL;
static bfd_error_type input_error = bfd_error_no_error;

const char *const bfd_errmsgs[] =
{
  N_("No error"),
  N_("System call error"),
  N_("Invalid bfd target"),
  N_("File in wrong format"),
  N_("Archive object file in wrong format"),
  N_("Invalid operation"),
  N_("Memory exhausted"),
  N_("No symbols"),
  N_("Archive has no index; run ranlib to add one"),
  N_("No more archived files"),
  N_("Malformed archive"),
  N_("DSO missing from command line"),
  N_("File format not recognized"),
  N_("File format is ambiguous"),
  N_("Section has no contents"),
  N_("Nonrepresentable section on output"),
  N_("Symbol needs debug section which does not exist"),
  N_("Bad value"),
  N_("File truncated"),
  N_("File too big"),
  N_("Error reading %s: %s"),
  N_("#<Invalid error code>")
};

/*
FUNCTION
	bfd_get_error

SYNOPSIS
	bfd_error_type bfd_get_error (void);

DESCRIPTION
	Return the current BFD error condition.
*/

bfd_error_type
bfd_get_error (void)
{
  return bfd_error;
}

/*
FUNCTION
	bfd_set_error

SYNOPSIS
	void bfd_set_error (bfd_error_type error_tag, ...);

DESCRIPTION
	Set the BFD error condition to be @var{error_tag}.
	If @var{error_tag} is bfd_error_on_input, then this function
	takes two more parameters, the input bfd where the error
	occurred, and the bfd_error_type error.
*/

void
bfd_set_error (bfd_error_type error_tag, ...)
{
  bfd_error = error_tag;
  if (error_tag == bfd_error_on_input)
    {
      /* This is an error that occurred during bfd_close when
	 writing an archive, but on one of the input files.  */
      va_list ap;

      va_start (ap, error_tag);
      input_bfd = va_arg (ap, bfd *);
      input_error = (bfd_error_type) va_arg (ap, int);
      if (input_error >= bfd_error_on_input)
	abort ();
      va_end (ap);
    }
}

/*
FUNCTION
	bfd_errmsg

SYNOPSIS
	const char *bfd_errmsg (bfd_error_type error_tag);

DESCRIPTION
	Return a string describing the error @var{error_tag}, or
	the system error if @var{error_tag} is <<bfd_error_system_call>>.
*/

const char *
bfd_errmsg (bfd_error_type error_tag)
{
#ifndef errno
  extern int errno;
#endif
  if (error_tag == bfd_error_on_input)
    {
      char *buf;
      const char *msg = bfd_errmsg (input_error);

      if (asprintf (&buf, _(bfd_errmsgs [error_tag]), input_bfd->filename, msg)
	  != -1)
	return buf;

      /* Ick, what to do on out of memory?  */
      return msg;
    }

  if (error_tag == bfd_error_system_call)
    return xstrerror (errno);

  if (error_tag > bfd_error_invalid_error_code)
    error_tag = bfd_error_invalid_error_code;	/* sanity check */

  return _(bfd_errmsgs [error_tag]);
}

/*
FUNCTION
	bfd_perror

SYNOPSIS
	void bfd_perror (const char *message);

DESCRIPTION
	Print to the standard error stream a string describing the
	last BFD error that occurred, or the last system error if
	the last BFD error was a system call failure.  If @var{message}
	is non-NULL and non-empty, the error string printed is preceded
	by @var{message}, a colon, and a space.  It is followed by a newline.
*/

void
bfd_perror (const char *message)
{
  fflush (stdout);
  if (message == NULL || *message == '\0')
    fprintf (stderr, "%s\n", bfd_errmsg (bfd_get_error ()));
  else
    fprintf (stderr, "%s: %s\n", message, bfd_errmsg (bfd_get_error ()));
  fflush (stderr);
}

/*
SUBSECTION
	BFD error handler

	Some BFD functions want to print messages describing the
	problem.  They call a BFD error handler function.  This
	function may be overridden by the program.

	The BFD error handler acts like printf.

CODE_FRAGMENT
.
.typedef void (*bfd_error_handler_type) (const char *, ...);
.
*/

/* The program name used when printing BFD error messages.  */

static const char *_bfd_error_program_name;

/* This is the default routine to handle BFD error messages.
   Like fprintf (stderr, ...), but also handles some extra format specifiers.

   %A section name from section.  For group components, print group name too.
   %B file name from bfd.  For archive components, prints archive too.

   Note - because these two extra format specifiers require special handling
   they are scanned for and processed in this function, before calling
   vfprintf.  This means that the *arguments* for these format specifiers
   must be the first ones in the variable argument list, regardless of where
   the specifiers appear in the format string.  Thus for example calling
   this function with a format string of:

      "blah %s blah %A blah %d blah %B"

   would involve passing the arguments as:

      "blah %s blah %A blah %d blah %B",
        asection_for_the_%A,
	bfd_for_the_%B,
	string_for_the_%s,
	integer_for_the_%d);
 */

void
_bfd_default_error_handler (const char *fmt, ...)
{
  va_list ap;
  char *bufp;
  const char *new_fmt, *p;
  size_t avail = 1000;
  char buf[1000];

  /* PR 4992: Don't interrupt output being sent to stdout.  */
  fflush (stdout);

  if (_bfd_error_program_name != NULL)
    fprintf (stderr, "%s: ", _bfd_error_program_name);
  else
    fprintf (stderr, "BFD: ");

  va_start (ap, fmt);
  new_fmt = fmt;
  bufp = buf;

  /* Reserve enough space for the existing format string.  */
  avail -= strlen (fmt) + 1;
  if (avail > 1000)
    _exit (EXIT_FAILURE);

  p = fmt;
  while (1)
    {
      char *q;
      size_t len, extra, trim;

      p = strchr (p, '%');
      if (p == NULL || p[1] == '\0')
	{
	  if (new_fmt == buf)
	    {
	      len = strlen (fmt);
	      memcpy (bufp, fmt, len + 1);
	    }
	  break;
	}

      if (p[1] == 'A' || p[1] == 'B')
	{
	  len = p - fmt;
	  memcpy (bufp, fmt, len);
	  bufp += len;
	  fmt = p + 2;
	  new_fmt = buf;

	  /* If we run out of space, tough, you lose your ridiculously
	     long file or section name.  It's not safe to try to alloc
	     memory here;  We might be printing an out of memory message.  */
	  if (avail == 0)
	    {
	      *bufp++ = '*';
	      *bufp++ = '*';
	      *bufp = '\0';
	    }
	  else
	    {
	      if (p[1] == 'B')
		{
		  bfd *abfd = va_arg (ap, bfd *);

		  if (abfd == NULL)
		    /* Invoking %B with a null bfd pointer is an internal error.  */
		    abort ();
		  else if (abfd->my_archive)
		    snprintf (bufp, avail, "%s(%s)",
			      abfd->my_archive->filename, abfd->filename);
		  else
		    snprintf (bufp, avail, "%s", abfd->filename);
		}
	      else
		{
		  asection *sec = va_arg (ap, asection *);
		  bfd *abfd;
		  const char *group = NULL;
		  struct coff_comdat_info *ci;

		  if (sec == NULL)
		    /* Invoking %A with a null section pointer is an internal error.  */
		    abort ();
		  abfd = sec->owner;
		  if (abfd != NULL
		      && bfd_get_flavour (abfd) == bfd_target_elf_flavour
		      && elf_next_in_group (sec) != NULL
		      && (sec->flags & SEC_GROUP) == 0)
		    group = elf_group_name (sec);
		  else if (abfd != NULL
			   && bfd_get_flavour (abfd) == bfd_target_coff_flavour
			   && (ci = bfd_coff_get_comdat_section (sec->owner,
								 sec)) != NULL)
		    group = ci->name;
		  if (group != NULL)
		    snprintf (bufp, avail, "%s[%s]", sec->name, group);
		  else
		    snprintf (bufp, avail, "%s", sec->name);
		}
	      len = strlen (bufp);
	      avail = avail - len + 2;

	      /* We need to replace any '%' we printed by "%%".
		 First count how many.  */
	      q = bufp;
	      bufp += len;
	      extra = 0;
	      while ((q = strchr (q, '%')) != NULL)
		{
		  ++q;
		  ++extra;
		}

	      /* If there isn't room, trim off the end of the string.  */
	      q = bufp;
	      bufp += extra;
	      if (extra > avail)
		{
		  trim = extra - avail;
		  bufp -= trim;
		  do
		    {
		      if (*--q == '%')
			--extra;
		    }
		  while (--trim != 0);
		  *q = '\0';
		  avail = extra;
		}
	      avail -= extra;

	      /* Now double all '%' chars, shuffling the string as we go.  */
	      while (extra != 0)
		{
		  while ((q[extra] = *q) != '%')
		    --q;
		  q[--extra] = '%';
		  --q;
		}
	    }
	}
      p = p + 2;
    }

  vfprintf (stderr, new_fmt, ap);
  va_end (ap);

  /* On AIX, putc is implemented as a macro that triggers a -Wunused-value
     warning, so use the fputc function to avoid it.  */
  fputc ('\n', stderr);
  fflush (stderr);
}

/* This is a function pointer to the routine which should handle BFD
   error messages.  It is called when a BFD routine encounters an
   error for which it wants to print a message.  Going through a
   function pointer permits a program linked against BFD to intercept
   the messages and deal with them itself.  */

bfd_error_handler_type _bfd_error_handler = _bfd_default_error_handler;

/*
FUNCTION
	bfd_set_error_handler

SYNOPSIS
	bfd_error_handler_type bfd_set_error_handler (bfd_error_handler_type);

DESCRIPTION
	Set the BFD error handler function.  Returns the previous
	function.
*/

bfd_error_handler_type
bfd_set_error_handler (bfd_error_handler_type pnew)
{
  bfd_error_handler_type pold;

  pold = _bfd_error_handler;
  _bfd_error_handler = pnew;
  return pold;
}

/*
FUNCTION
	bfd_set_error_program_name

SYNOPSIS
	void bfd_set_error_program_name (const char *);

DESCRIPTION
	Set the program name to use when printing a BFD error.  This
	is printed before the error message followed by a colon and
	space.  The string must not be changed after it is passed to
	this function.
*/

void
bfd_set_error_program_name (const char *name)
{
  _bfd_error_program_name = name;
}

/*
FUNCTION
	bfd_get_error_handler

SYNOPSIS
	bfd_error_handler_type bfd_get_error_handler (void);

DESCRIPTION
	Return the BFD error handler function.
*/

bfd_error_handler_type
bfd_get_error_handler (void)
{
  return _bfd_error_handler;
}

/*
SUBSECTION
	BFD assert handler

	If BFD finds an internal inconsistency, the bfd assert
	handler is called with information on the BFD version, BFD
	source file and line.  If this happens, most programs linked
	against BFD are expected to want to exit with an error, or mark
	the current BFD operation as failed, so it is recommended to
	override the default handler, which just calls
	_bfd_error_handler and continues.

CODE_FRAGMENT
.
.typedef void (*bfd_assert_handler_type) (const char *bfd_formatmsg,
.                                         const char *bfd_version,
.                                         const char *bfd_file,
.                                         int bfd_line);
.
*/

/* Note the use of bfd_ prefix on the parameter names above: we want to
   show which one is the message and which is the version by naming the
   parameters, but avoid polluting the program-using-bfd namespace as
   the typedef is visible in the exported headers that the program
   includes.  Below, it's just for consistency.  */

static void
_bfd_default_assert_handler (const char *bfd_formatmsg,
			     const char *bfd_version,
			     const char *bfd_file,
			     int bfd_line)

{
  (*_bfd_error_handler) (bfd_formatmsg, bfd_version, bfd_file, bfd_line);
}

/* Similar to _bfd_error_handler, a program can decide to exit on an
   internal BFD error.  We use a non-variadic type to simplify passing
   on parameters to other functions, e.g. _bfd_error_handler.  */

bfd_assert_handler_type _bfd_assert_handler = _bfd_default_assert_handler;

/*
FUNCTION
	bfd_set_assert_handler

SYNOPSIS
	bfd_assert_handler_type bfd_set_assert_handler (bfd_assert_handler_type);

DESCRIPTION
	Set the BFD assert handler function.  Returns the previous
	function.
*/

bfd_assert_handler_type
bfd_set_assert_handler (bfd_assert_handler_type pnew)
{
  bfd_assert_handler_type pold;

  pold = _bfd_assert_handler;
  _bfd_assert_handler = pnew;
  return pold;
}

/*
FUNCTION
	bfd_get_assert_handler

SYNOPSIS
	bfd_assert_handler_type bfd_get_assert_handler (void);

DESCRIPTION
	Return the BFD assert handler function.
*/

bfd_assert_handler_type
bfd_get_assert_handler (void)
{
  return _bfd_assert_handler;
}

/*
INODE
Miscellaneous, Memory Usage, Error reporting, BFD front end

SECTION
	Miscellaneous

SUBSECTION
	Miscellaneous functions
*/

/*
FUNCTION
	bfd_get_reloc_upper_bound

SYNOPSIS
	long bfd_get_reloc_upper_bound (bfd *abfd, asection *sect);

DESCRIPTION
	Return the number of bytes required to store the
	relocation information associated with section @var{sect}
	attached to bfd @var{abfd}.  If an error occurs, return -1.

*/

long
bfd_get_reloc_upper_bound (bfd *abfd, sec_ptr asect)
{
  if (abfd->format != bfd_object)
    {
      bfd_set_error (bfd_error_invalid_operation);
      return -1;
    }

  return BFD_SEND (abfd, _get_reloc_upper_bound, (abfd, asect));
}

/*
FUNCTION
	bfd_canonicalize_reloc

SYNOPSIS
	long bfd_canonicalize_reloc
	  (bfd *abfd, asection *sec, arelent **loc, asymbol **syms);

DESCRIPTION
	Call the back end associated with the open BFD
	@var{abfd} and translate the external form of the relocation
	information attached to @var{sec} into the internal canonical
	form.  Place the table into memory at @var{loc}, which has
	been preallocated, usually by a call to
	<<bfd_get_reloc_upper_bound>>.  Returns the number of relocs, or
	-1 on error.

	The @var{syms} table is also needed for horrible internal magic
	reasons.

*/
long
bfd_canonicalize_reloc (bfd *abfd,
			sec_ptr asect,
			arelent **location,
			asymbol **symbols)
{
  if (abfd->format != bfd_object)
    {
      bfd_set_error (bfd_error_invalid_operation);
      return -1;
    }

  return BFD_SEND (abfd, _bfd_canonicalize_reloc,
		   (abfd, asect, location, symbols));
}

/*
FUNCTION
	bfd_set_reloc

SYNOPSIS
	void bfd_set_reloc
	  (bfd *abfd, asection *sec, arelent **rel, unsigned int count);

DESCRIPTION
	Set the relocation pointer and count within
	section @var{sec} to the values @var{rel} and @var{count}.
	The argument @var{abfd} is ignored.

*/

void
bfd_set_reloc (bfd *ignore_abfd ATTRIBUTE_UNUSED,
	       sec_ptr asect,
	       arelent **location,
	       unsigned int count)
{
  asect->orelocation = location;
  asect->reloc_count = count;
}

/*
FUNCTION
	bfd_set_file_flags

SYNOPSIS
	bfd_boolean bfd_set_file_flags (bfd *abfd, flagword flags);

DESCRIPTION
	Set the flag word in the BFD @var{abfd} to the value @var{flags}.

	Possible errors are:
	o <<bfd_error_wrong_format>> - The target bfd was not of object format.
	o <<bfd_error_invalid_operation>> - The target bfd was open for reading.
	o <<bfd_error_invalid_operation>> -
	The flag word contained a bit which was not applicable to the
	type of file.  E.g., an attempt was made to set the <<D_PAGED>> bit
	on a BFD format which does not support demand paging.

*/

bfd_boolean
bfd_set_file_flags (bfd *abfd, flagword flags)
{
  if (abfd->format != bfd_object)
    {
      bfd_set_error (bfd_error_wrong_format);
      return FALSE;
    }

  if (bfd_read_p (abfd))
    {
      bfd_set_error (bfd_error_invalid_operation);
      return FALSE;
    }

  bfd_get_file_flags (abfd) = flags;
  if ((flags & bfd_applicable_file_flags (abfd)) != flags)
    {
      bfd_set_error (bfd_error_invalid_operation);
      return FALSE;
    }

  return TRUE;
}

void
bfd_assert (const char *file, int line)
{
  (*_bfd_assert_handler) (_("BFD %s assertion fail %s:%d"),
			  BFD_VERSION_STRING, file, line);
}

/* A more or less friendly abort message.  In libbfd.h abort is
   defined to call this function.  */

void
_bfd_abort (const char *file, int line, const char *fn)
{
  if (fn != NULL)
    (*_bfd_error_handler)
      (_("BFD %s internal error, aborting at %s line %d in %s\n"),
       BFD_VERSION_STRING, file, line, fn);
  else
    (*_bfd_error_handler)
      (_("BFD %s internal error, aborting at %s line %d\n"),
       BFD_VERSION_STRING, file, line);
  (*_bfd_error_handler) (_("Please report this bug.\n"));
  _exit (EXIT_FAILURE);
}

/*
FUNCTION
	bfd_get_arch_size

SYNOPSIS
 	int bfd_get_arch_size (bfd *abfd);

DESCRIPTION
	Returns the normalized architecture address size, in bits, as
	determined by the object file's format.  By normalized, we mean
	either 32 or 64.  For ELF, this information is included in the
	header.  Use bfd_arch_bits_per_address for number of bits in
	the architecture address.

RETURNS
	Returns the arch size in bits if known, <<-1>> otherwise.
*/

int
bfd_get_arch_size (bfd *abfd)
{
  if (abfd->xvec->flavour == bfd_target_elf_flavour)
    return get_elf_backend_data (abfd)->s->arch_size;

  return bfd_arch_bits_per_address (abfd) > 32 ? 64 : 32;
}

/*
FUNCTION
	bfd_get_sign_extend_vma

SYNOPSIS
 	int bfd_get_sign_extend_vma (bfd *abfd);

DESCRIPTION
	Indicates if the target architecture "naturally" sign extends
	an address.  Some architectures implicitly sign extend address
	values when they are converted to types larger than the size
	of an address.  For instance, bfd_get_start_address() will
	return an address sign extended to fill a bfd_vma when this is
	the case.

RETURNS
	Returns <<1>> if the target architecture is known to sign
	extend addresses, <<0>> if the target architecture is known to
	not sign extend addresses, and <<-1>> otherwise.
*/

int
bfd_get_sign_extend_vma (bfd *abfd)
{
  char *name;

  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
    return get_elf_backend_data (abfd)->sign_extend_vma;

  name = bfd_get_target (abfd);

  /* Return a proper value for DJGPP & PE COFF.
     This function is required for DWARF2 support, but there is
     no place to store this information in the COFF back end.
     Should enough other COFF targets add support for DWARF2,
     a place will have to be found.  Until then, this hack will do.  */
  if (CONST_STRNEQ (name, "coff-go32")
      || strcmp (name, "pe-i386") == 0
      || strcmp (name, "pei-i386") == 0
      || strcmp (name, "pe-x86-64") == 0
      || strcmp (name, "pei-x86-64") == 0
      || strcmp (name, "pe-arm-wince-little") == 0
      || strcmp (name, "pei-arm-wince-little") == 0
      || strcmp (name, "aixcoff-rs6000") == 0)