code
stringlengths
4
1.01M
language
stringclasses
2 values
package gui; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import logic.DB.MongoUserManager; import logic.model.Statistics; import logic.model.User; import javax.swing.JLabel; import java.awt.Font; import java.awt.Toolkit; public class ListPlayers extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JScrollPane spUsers; private JTable tabUsers; private MongoUserManager mongo = new MongoUserManager(); private List<User> users; private JButton btnClose; private JLabel lbListUsers; /** * Launch the application. */ /*public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ListPlayers frame = new ListPlayers(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }*/ /** * Create the frame. */ public ListPlayers() { setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Raquel\\Desktop\\ASWProject\\Trivial_i1b\\Game\\src\\main\\resources\\Images\\icono.png")); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 532, 340); contentPane = new JPanel(); contentPane.setBackground(new Color(0,0,139)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); contentPane.add(getSpUsers()); contentPane.add(getBtnClose()); contentPane.setBackground(InitialWindow.pnFondo.getBackground()); JButton btnSeeStatistics = new JButton("See statistics"); btnSeeStatistics.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { users = mongo.getAllUsers(); StatisticsWindow statistics = new StatisticsWindow(); statistics.setVisible(true); statistics.txPlayer.setText((String) tabUsers.getValueAt(tabUsers.getSelectedRow(), 0)); int row = tabUsers.getSelectedRow(); int newRow = 0; for (User u : users){ if (u.getEmail().equals(tabUsers.getValueAt(row, 1))){ Statistics s = u.getStatistics(); statistics.tabStatistics.setValueAt(s.getQuestionsMatched(), newRow, 0); statistics.tabStatistics.setValueAt(s.getQuestionsAnswered(), newRow, 1); statistics.tabStatistics.setValueAt(s.getTimesPlayed(), newRow, 2); newRow++; } } } }); btnSeeStatistics.setBounds(357, 42, 123, 23); contentPane.add(btnSeeStatistics); contentPane.add(getLbListUsers()); } private JScrollPane getSpUsers() { if (spUsers == null) { spUsers = new JScrollPane(); spUsers.setBounds(42, 103, 306, 128); spUsers.setViewportView(getTabUsers()); spUsers.setBackground(InitialWindow.pnFondo.getBackground()); } return spUsers; } private JTable getTabUsers() { if (tabUsers == null) { tabUsers = new JTable(); tabUsers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tabUsers.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "Username", "Email" } )); } DefaultTableModel model = (DefaultTableModel)tabUsers.getModel(); listUsers(model); return tabUsers; } private JButton getBtnClose() { if (btnClose == null) { btnClose = new JButton("Close"); btnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); btnClose.setBounds(378, 230, 76, 23); } return btnClose; } private void listUsers(DefaultTableModel model) { users = mongo.getAllUsers(); Object[] row = new Object[2]; for (int i = 0; i < users.size(); i++) { row[0] = users.get(i).getUsername(); row[1] = users.get(i).getEmail(); model.addRow(row); } } private JLabel getLbListUsers() { if (lbListUsers == null) { lbListUsers = new JLabel("List of users:"); lbListUsers.setFont(new Font("Arial", Font.PLAIN, 25)); lbListUsers.setBounds(142, 32, 195, 32); } return lbListUsers; } }
Java
package sabstracta; /** * Represents an or operation in the syntax tree. * */ public class Or extends ExpresionBinariaLogica { public Or(Expresion _izq, Expresion _dch) { super(_izq, _dch); } /** * Returns the instruction code. */ @Override protected String getInst() { return "or"; } }
Java
<?php /** * @package JFBConnect * @copyright (c) 2009-2015 by SourceCoast - All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL * @version Release v7.1.1 * @build-date 2016/11/18 */ defined('JPATH_PLATFORM') or die; jimport('joomla.form.helper'); class JFormFieldProviderloginbutton extends JFormField { protected function getInput() { $html = array(); $provider = $this->element['provider'] ? (string)$this->element['provider'] : null; $style = $this->element['style'] ? (string)$this->element['style'] . '"' : ''; // Initialize some field attributes. $class = !empty($this->class) ? ' class="radio ' . $this->class . '"' : ' class="radio"'; $required = $this->required ? ' required aria-required="true"' : ''; $autofocus = $this->autofocus ? ' autofocus' : ''; $disabled = $this->disabled ? ' disabled' : ''; $readonly = $this->readonly; $style = 'style="float:left;' . $style . '"'; $html[] = '<div style="clear: both"> </div>'; // Start the radio field output. $html[] = '<fieldset id="' . $this->id . '"' . $class . $required . $autofocus . $disabled . $style . ' >'; // Get the field options. $options = $this->getOptions(); $p = JFBCFactory::provider($provider); // Build the radio field output. $html[] = '<label class="providername">' . $p->name . '</label>'; foreach ($options as $i => $option) { // Initialize some option attributes. $checked = ((string)$option->value == (string)$this->value) ? ' checked="checked"' : ''; $class = !empty($option->class) ? ' class="' . $option->class . '"' : ''; $disabled = !empty($option->disable) || ($readonly && !$checked); $disabled = $disabled ? ' disabled' : ''; $html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="' . htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8') . '"' . $checked . $class . $required . $disabled . ' />'; $html[] = '<label for="' . $this->id . $i . '"' . $class . ' >' . '<img src="' . JUri::root() . 'media/sourcecoast/images/provider/' . $provider . '/' . $option->value . '" />' . #. JText::alt($option->text, preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)) . '</label>' '</label>' . $required = ''; } // End the radio field output. $html[] = '</fieldset>'; $html[] = '<div style="clear: both"> </div>'; return implode($html); } protected function getOptions() { // Scan the /media/sourcecoast/images/provider directory for this provider's buttons // Merge in any custom images from ?? $provider = $this->element['provider'] ? (string)$this->element['provider'] : null; $options = array(); $buttons = $this->getButtons('/media/sourcecoast/images/provider/' . $provider); if ($buttons) { foreach ($buttons as $button) { $options[] = JHtml::_('select.option', $button, $button, 'value', 'text', false); } } reset($options); return $options; } private function getButtons($folder) { $folder = JPATH_SITE . $folder; $buttons = array(); if (JFolder::exists($folder)) { $buttons = JFolder::files($folder, '^' . '.*(\.png|\.jpg|\.gif)$'); } return $buttons; } }
Java
\documentclass{report} \usepackage{hyperref} % WARNING: THIS SHOULD BE MODIFIED DEPENDING ON THE LETTER/A4 SIZE \oddsidemargin 0cm \evensidemargin 0cm \marginparsep 0cm \marginparwidth 0cm \parindent 0cm \textwidth 16.5cm \ifpdf \usepackage[pdftex]{graphicx} \else \usepackage[dvips]{graphicx} \fi \begin{document} % special variable used for calculating some widths. \newlength{\tmplength} \chapter{Unit ok{\_}interface{\_}implicit} \section{Overview} \begin{description} \item[\texttt{\begin{ttfamily}IMyInterface\end{ttfamily} Interface}] \item[\texttt{\begin{ttfamily}TMyRecord\end{ttfamily} Record}] \item[\texttt{\begin{ttfamily}TMyPackedRecord\end{ttfamily} Packed Record}] \item[\texttt{\begin{ttfamily}TMyClass\end{ttfamily} Class}] \end{description} \section{Classes, Interfaces, Objects and Records} \subsection*{IMyInterface Interface} \subsubsection*{\large{\textbf{Hierarchy}}\normalsize\hspace{1ex}\hfill} IMyInterface {$>$} IInterface %%%%Description \subsubsection*{\large{\textbf{Methods}}\normalsize\hspace{1ex}\hfill} \paragraph*{PublicMethod}\hspace*{\fill} \begin{list}{}{ \settowidth{\tmplength}{\textbf{Description}} \setlength{\itemindent}{0cm} \setlength{\listparindent}{0cm} \setlength{\leftmargin}{\evensidemargin} \addtolength{\leftmargin}{\tmplength} \settowidth{\labelsep}{X} \addtolength{\leftmargin}{\labelsep} \setlength{\labelwidth}{\tmplength} } \begin{flushleft} \item[\textbf{Declaration}\hfill] \begin{ttfamily} public procedure PublicMethod;\end{ttfamily} \end{flushleft} \end{list} \subsection*{TMyRecord Record} %%%%Description \subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill} \paragraph*{PublicField}\hspace*{\fill} \begin{list}{}{ \settowidth{\tmplength}{\textbf{Description}} \setlength{\itemindent}{0cm} \setlength{\listparindent}{0cm} \setlength{\leftmargin}{\evensidemargin} \addtolength{\leftmargin}{\tmplength} \settowidth{\labelsep}{X} \addtolength{\leftmargin}{\labelsep} \setlength{\labelwidth}{\tmplength} } \begin{flushleft} \item[\textbf{Declaration}\hfill] \begin{ttfamily} public PublicField: Integer;\end{ttfamily} \end{flushleft} \end{list} \subsection*{TMyPackedRecord Packed Record} %%%%Description \subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill} \paragraph*{PublicField}\hspace*{\fill} \begin{list}{}{ \settowidth{\tmplength}{\textbf{Description}} \setlength{\itemindent}{0cm} \setlength{\listparindent}{0cm} \setlength{\leftmargin}{\evensidemargin} \addtolength{\leftmargin}{\tmplength} \settowidth{\labelsep}{X} \addtolength{\leftmargin}{\labelsep} \setlength{\labelwidth}{\tmplength} } \begin{flushleft} \item[\textbf{Declaration}\hfill] \begin{ttfamily} public PublicField: Integer;\end{ttfamily} \end{flushleft} \end{list} \subsection*{TMyClass Class} \subsubsection*{\large{\textbf{Hierarchy}}\normalsize\hspace{1ex}\hfill} TMyClass {$>$} TObject %%%%Description \subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill} \paragraph*{PublicField}\hspace*{\fill} \begin{list}{}{ \settowidth{\tmplength}{\textbf{Description}} \setlength{\itemindent}{0cm} \setlength{\listparindent}{0cm} \setlength{\leftmargin}{\evensidemargin} \addtolength{\leftmargin}{\tmplength} \settowidth{\labelsep}{X} \addtolength{\leftmargin}{\labelsep} \setlength{\labelwidth}{\tmplength} } \begin{flushleft} \item[\textbf{Declaration}\hfill] \begin{ttfamily} public PublicField: Integer;\end{ttfamily} \end{flushleft} \end{list} \end{document}
Java
package org.oguz.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class XMLServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String userName = request.getParameter("username"); String fullName = request.getParameter("fullname"); String profession = request.getParameter("profession"); // HttpSession session =request.getSession(); ServletContext context = request.getServletContext(); if (userName != "" && userName != null) { // session.setAttribute("savedUser",userName); context.setAttribute("savedUser", userName); out.println("<p>Hello context parameter " + (String)context.getAttribute("savedUser") + " from GET method</p>"); } else { out.println("<p>Hello default user " + this.getServletConfig().getInitParameter("username") + " from GET method</p>"); } if (fullName != "" && fullName != null) { // session.setAttribute("savedFull", fullName); context.setAttribute("savedFull", fullName); out.println("<p> your full name is: " + (String)context.getAttribute("savedFull") + "</p>"); } else { out.println("<p>Hello default fullname " + this.getServletConfig().getInitParameter("fullname") + " from GET method</p>"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String userName = request.getParameter("username"); String fullName = request.getParameter("fullname"); String profession = request.getParameter("profession"); // String location = request.getParameter("location"); String[] location = request.getParameterValues("location"); out.println("<p>Hello " + userName + " from POST method in XMLSERVLET response</p>"); out.println("<p> your full name is: " + fullName + "</p>"); out.println("<p>your profession is: " + profession + "</p>"); for (int i = 0; i < location.length; i++) { out.println("<p>your location is: " + location[i].toUpperCase() + "</p>"); } } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en"> <head> <meta name="description" content="Dubstep indie music"> <meta name="keywords" content="dubstep, superman, indie, hollywood, maryland, soundtrack, a boy named su, a boy named sue, heart"> <meta name="author" content="Mike Su"> <script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <title>A Boy Named Su &hearts; the SoundCloud</title> <link type="text/css" media="screen" rel="stylesheet" href="../../slabText/css/slabtext.css"> <link rel="stylesheet" href="../css/sc-player-artwork.css" type="text/css"> <link rel="stylesheet" href="../../css/style.css" type="text/css"> <style> @font-face { font-family: 'LeagueGothicRegular'; src: url('../../fonts/League_Gothic-webfont.eot'); src: url('../../fonts/League_Gothic-webfont.eot?#iefix') format('embedded-opentype'), url('../../fonts/League_Gothic-webfont.woff') format('woff'), url('../../fonts/League_Gothic-webfont.ttf') format('truetype'), url('../../fonts/League_Gothic-webfont.svg#LeagueGothicRegular') format('svg'); font-weight: normal; font-style: normal; } html, body { background:#000; color:#444; } body { font: 16px/1.8 "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; width:80%; padding:20px 0; max-width:960px; margin:0 auto; } hr { border: 0; height: 1px; background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0)); } .col-1 { width:47.5%; margin:0 2.5% 0 0; float:left; } .col-2 { width:47.5%; margin:0 0 0 2.5%; float:left; } .col-1 p, .col-2 p { color:#888; font-size:80%; text-align:center; } a { color:#111; } h1 a { text-decoration:none; } p { margin:0 0 1.5em 0; line-height:1.5em; } dt { font-family:monospace; } pre { line-height:1.2; } footer { border-top:3px double #aaa; padding-top:1em; } footer section { border-bottom:3px double #aaa; padding-bottom:1em; margin-bottom:1em; } sup a { text-decoration:none; } #h4 { clear:both; } .amp { font-family:Baskerville,'Goudy Old Style',Palatino,'Book Antiqua',serif; font-style:italic; font-weight:lighter; } /* Set font-sizes for the headings to be given the slabText treatment */ h1 { text-align:left; font-family:'LeagueGothicRegular', "Impact", Charcoal, Arial Black, Gadget, Sans serif; text-transform: uppercase; line-height:1; color:#222; font-size:300%; /* Remember to set the correct font weight if using fontface */ font-weight:normal; } /* Smaller font-size for the side-by-side demo */ .col-1 h1, .col-2 h1 { font-size: 32px; } h2 { font-size: 25px; } /* Adjust the line-height for all headlines that have been given the slabtext treatment. Use a unitless line-height to stop sillyness */ .slabtexted h1 { line-height:.9; } /* Target specific lines in the preset Studio One demo */ .slabtexted #studio-one span:nth-child(2) { line-height:.8; } .slabtexted #studio-one span:nth-child(3) { line-height:1.1; } /* Fun with media queries - resize your browser to view changes. */ @media screen and (max-width: 960px) { body { padding:10px 0; min-width:20em; } .col-1, .col-2 { float:none; margin:0; width:100%; } h1 { font-size:36px; } h2 { font-size:22px; } } @media screen and (max-width: 460px) { h1 { font-size:26px; } h2 { font-size:18px; } } </style> <div class="menu"> <div id="logo"><a href="/">&hearts;</a></div> </div> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="menu"> <div id="logo"><a href="../../">&hearts;</a></div> <a href="../../album">/Album</a> <a href="http://t.qkme.me/3st1se.jpg">ArchNemesis!</a> <a href="http://listen.boynamedsumusic.com/">BandCamp</a> <a href="../../covers">/Covers</a> <a href="../../lekryptonite">/LeKryptonite</a> <a href="../../lightshow/14hearts/155bpm"><span class="red155">/Lightshow/14&hearts;</span></a> <a href="http://sudocoda.com">RillyThickGlasses</a> <a href="../../soundcloud/heart" class="active">/SoundCloud/&hearts;</a> <a href="../../album/heart/exit-music-for-a-hollywood-movie"><h1 style="padding:3px;">Exit</h1></a> </div> <div class="social"> <div class="footer-social"><a href="http://facebook.com/boynamedsumusic‎" target="_blank"><img src="../../images/footer_facebook.png" alt=""></a></div> <div class="footer-social"><a href="http://twitter.com/boynamedsumusic" target="_blank"><img src="../../images/footer_twitter.png" alt=""></a></div> <div class="footer-social"><a href="http://plus.google.com/u/3/109615451595602898651/" target="_blank"><img src="../../images/footer_google.png" alt=""></a></div> </div> <div class="fb-like" data-href="http://boynamedsumusic.com/soundcloud/heart" data-send="true" data-width="450" data-show-faces="true" data-font="lucida grande" data-colorscheme="dark"></div> <a href="https://twitter.com/share" class="twitter-share-button" data-via="boynamedsumusic">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <h1>I &hearts; the SoundCloud. It was twue WubWubWub at first listen!</h1> <div class="post"> <div class="sc-player"> <a href="http://soundcloud.com/aboynamedsu/sets/heart" class="sc-player">Heart</a> </div> </div> <script type="text/javascript"> $(function(){ var menu = $('.menu'), a = menu.find('a'); a.wrapInner($('<span />')); a.each(function(){ var t = $(this), span = t.find('span'); for (i=0;i<2;i++){ span.clone().appendTo(t); } }); a.hover(function(){ var t = $(this), s = t.siblings('a'); t.toggleClass('shadow'); s.toggleClass('blur'); }); $(a[0]).delay(500).queue(function(n) { $(this).mouseenter(); n(); }); $(a[0]).delay(500).queue(function(n) { $(this).mouseleave(); n(); }); }); </script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script type="text/javascript" src="../js/soundcloud.player.api.js"></script> <script type="text/javascript" src="../js/sc-player.js"></script> </body> </html>
Java
// ********************************************************************** // // Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** #ifndef ICEGRID_ADMINSESSIONI_H #define ICEGRID_ADMINSESSIONI_H #include <IceGrid/SessionI.h> #include <IceGrid/Topics.h> #include <IceGrid/ReapThread.h> #include <IceGrid/Internal.h> namespace IceGrid { class RegistryI; typedef IceUtil::Handle<RegistryI> RegistryIPtr; class FileIteratorI; typedef IceUtil::Handle<FileIteratorI> FileIteratorIPtr; class AdminSessionI : public BaseSessionI, public AdminSession { public: AdminSessionI(const std::string&, const DatabasePtr&, int, const RegistryIPtr&); virtual ~AdminSessionI(); Ice::ObjectPrx _register(const SessionServantManagerPtr&, const Ice::ConnectionPtr&); virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); } virtual AdminPrx getAdmin(const Ice::Current&) const; virtual Ice::ObjectPrx getAdminCallbackTemplate(const Ice::Current&) const; virtual void setObservers(const RegistryObserverPrx&, const NodeObserverPrx&, const ApplicationObserverPrx&, const AdapterObserverPrx&, const ObjectObserverPrx&, const Ice::Current&); virtual void setObserversByIdentity(const Ice::Identity&, const Ice::Identity&, const Ice::Identity&, const Ice::Identity&, const Ice::Identity&, const Ice::Current&); virtual int startUpdate(const Ice::Current&); virtual void finishUpdate(const Ice::Current&); virtual std::string getReplicaName(const Ice::Current&) const; virtual FileIteratorPrx openServerLog(const std::string&, const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openServerStdOut(const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openServerStdErr(const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openNodeStdOut(const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openNodeStdErr(const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openRegistryStdOut(const std::string&, int, const Ice::Current&); virtual FileIteratorPrx openRegistryStdErr(const std::string&, int, const Ice::Current&); virtual void destroy(const Ice::Current&); void removeFileIterator(const Ice::Identity&, const Ice::Current&); private: void setupObserverSubscription(TopicName, const Ice::ObjectPrx&, bool = false); Ice::ObjectPrx addForwarder(const Ice::Identity&, const Ice::Current&); Ice::ObjectPrx addForwarder(const Ice::ObjectPrx&); FileIteratorPrx addFileIterator(const FileReaderPrx&, const std::string&, int, const Ice::Current&); virtual void destroyImpl(bool); const int _timeout; const std::string _replicaName; AdminPrx _admin; std::map<TopicName, std::pair<Ice::ObjectPrx, bool> > _observers; RegistryIPtr _registry; Ice::ObjectPrx _adminCallbackTemplate; }; typedef IceUtil::Handle<AdminSessionI> AdminSessionIPtr; class AdminSessionFactory : public virtual IceUtil::Shared { public: AdminSessionFactory(const SessionServantManagerPtr&, const DatabasePtr&, const ReapThreadPtr&, const RegistryIPtr&); Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&); AdminSessionIPtr createSessionServant(const std::string&); const TraceLevelsPtr& getTraceLevels() const; private: const SessionServantManagerPtr _servantManager; const DatabasePtr _database; const int _timeout; const ReapThreadPtr _reaper; const RegistryIPtr _registry; const bool _filters; }; typedef IceUtil::Handle<AdminSessionFactory> AdminSessionFactoryPtr; class AdminSessionManagerI : public virtual Glacier2::SessionManager { public: AdminSessionManagerI(const AdminSessionFactoryPtr&); virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); private: const AdminSessionFactoryPtr _factory; }; class AdminSSLSessionManagerI : public virtual Glacier2::SSLSessionManager { public: AdminSSLSessionManagerI(const AdminSessionFactoryPtr&); virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&, const Ice::Current&); private: const AdminSessionFactoryPtr _factory; }; class FileIteratorI : public FileIterator { public: FileIteratorI(const AdminSessionIPtr&, const FileReaderPrx&, const std::string&, Ice::Long, int); virtual bool read(int, Ice::StringSeq&, const Ice::Current&); virtual void destroy(const Ice::Current&); private: const AdminSessionIPtr _session; const FileReaderPrx _reader; const std::string _filename; Ice::Long _offset; const int _messageSizeMax; }; }; #endif
Java
--- layout: default --- &nbsp<div class="container blog-container"><h3 class="less-space-top">The Sinfonia Solutions Blog</h3><div class="jumbotron people"><p><em>{{ page.date | date_to_string }}</em></p><h1>{{page.title}}</h1></div><div class="row"><div class="col-sm-8 post-content">{{ content }}</div><div class="col-sm-4"><h3>Recent Posts</h3>{% for post in site.posts limit:8 %}<div class="top-thick-border"><p>{{post.date | date_to_long_string}}</p><h4 class="less-space-top">{{ post.title }}</h4><p>{{ post.description }}</p><a href="{{ post.url }}">Read More</a><div class="spacer-s"></div></div>{% endfor %}</div></div></div>
Java
package fr.npellegrin.xebia.mower.parser.model; /** * Parsed position. */ public class PositionDefinition { private int x; private int y; private OrientationDefinition orientation; public int getX() { return x; } public void setX(final int x) { this.x = x; } public int getY() { return y; } public void setY(final int y) { this.y = y; } public OrientationDefinition getOrientation() { return orientation; } public void setOrientation(final OrientationDefinition orientation) { this.orientation = orientation; } }
Java
#============================================================= -*-Perl-*- # # Pod::POM::Constants # # DESCRIPTION # Constants used by Pod::POM. # # AUTHOR # Andy Wardley <abw@kfs.org> # Andrew Ford <a.ford@ford-mason.co.uk> # # COPYRIGHT # Copyright (C) 2000, 2001 Andy Wardley. All Rights Reserved. # Copyright (C) 2009 Andrew Ford. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # REVISION # $Id: Constants.pm 89 2013-05-30 07:41:52Z ford $ # #======================================================================== package Pod::POM::Constants; $Pod::POM::Constants::VERSION = '2.00'; require 5.006; use strict; use warnings; use parent qw( Exporter ); our @SEQUENCE = qw( CMD LPAREN RPAREN FILE LINE CONTENT ); our @STATUS = qw( IGNORE REDUCE REJECT ); our @EXPORT_OK = ( @SEQUENCE, @STATUS ); our %EXPORT_TAGS = ( status => [ @STATUS ], seq => [ @SEQUENCE ], all => [ @STATUS, @SEQUENCE ], ); # sequence items use constant CMD => 0; use constant LPAREN => 1; use constant RPAREN => 2; use constant FILE => 3; use constant LINE => 4; use constant CONTENT => 5; # node add return values use constant IGNORE => 0; use constant REDUCE => 1; use constant REJECT => 2; 1; =head1 NAME Pod::POM::Constants =head1 DESCRIPTION Constants used by Pod::POM. =head1 AUTHOR Andy Wardley E<lt>abw@kfs.orgE<gt> Andrew Ford E<lt>a.ford@ford-mason.co.ukE<gt> =head1 COPYRIGHT AND LICENSE Copyright (C) 2000, 2001 Andy Wardley. All Rights Reserved. Copyright (C) 2009 Andrew Ford. All Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
Java
#!/usr/bin/env python3 import sys import numpy as np from spc import SPC import matplotlib.pyplot as plt def plot(files, fac=1.0): for f in files: if f.split('.')[-1] == 'xy': td = np.loadtxt(f) plt.plot(td[:, 0], np.log(1. / td[:, 1]) * fac, label=f) elif f.split('.')[-1] == 'spc': td = SPC(f) plt.plot(td.xdata, np.log(1. / np.array(td.ydata)), label=f) plt.legend() plt.show() if __name__ == '__main__': files = sys.argv[2:] fac = float(sys.argv[1]) plot(files, fac)
Java
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\CanonVRD; use PHPExiftool\Driver\AbstractTag; class LandscapeRawContrast extends AbstractTag { protected $Id = 33; protected $Name = 'LandscapeRawContrast'; protected $FullName = 'CanonVRD::Ver2'; protected $GroupName = 'CanonVRD'; protected $g0 = 'CanonVRD'; protected $g1 = 'CanonVRD'; protected $g2 = 'Image'; protected $Type = 'int16s'; protected $Writable = true; protected $Description = 'Landscape Raw Contrast'; }
Java
/**************************************************************************** ** ** This file is part of the Qtopia Opensource Edition Package. ** ** Copyright (C) 2008 Trolltech ASA. ** ** Contact: Qt Extended Information (info@qtextended.org) ** ** This file may be used under the terms of the GNU General Public License ** versions 2.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. ** ** Please review the following information to ensure GNU General Public ** Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html. ** ** ****************************************************************************/ #include <qtopia/private/qmimetypedata_p.h> #include <qtopia/private/drmcontent_p.h> #include <QApplication> #include <QtDebug> Q_GLOBAL_STATIC_WITH_ARGS(QIcon,unknownDocumentIcon,(QLatin1String(":image/qpe/UnknownDocument"))); Q_GLOBAL_STATIC_WITH_ARGS(QIcon,validDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon( *unknownDocumentIcon(), qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ), qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ), true ))); Q_GLOBAL_STATIC_WITH_ARGS(QIcon,invalidDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon( *unknownDocumentIcon(), qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ), qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ), false ))); class QMimeTypeDataPrivate : public QSharedData { public: struct AppData { QContent application; QString iconFile; QIcon icon; QIcon validDrmIcon; QIcon invalidDrmIcon; QDrmRights::Permission permission; bool iconLoaded; bool validDrmIconLoaded; bool invalidDrmIconLoaded; }; QMimeTypeDataPrivate() { } ~QMimeTypeDataPrivate() { qDeleteAll( applicationData.values() ); } QString id; QContentList applications; QContent defaultApplication; QMap< QContentId, AppData * > applicationData; void loadIcon( AppData *data ) const; void loadValidDrmIcon( AppData *data ) const; void loadInvalidDrmIcon( AppData *data ) const; }; void QMimeTypeDataPrivate::loadIcon( AppData *data ) const { if( !data->iconFile.isEmpty() ) data->icon = QIcon( QLatin1String( ":icon/" ) + data->iconFile ); data->iconLoaded = true; } void QMimeTypeDataPrivate::loadValidDrmIcon( AppData *data ) const { if( !data->icon.isNull() ) data->validDrmIcon = DrmContentPrivate::createIcon( data->icon, qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ), qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ), true ); data->validDrmIconLoaded = true; } void QMimeTypeDataPrivate::loadInvalidDrmIcon( AppData *data ) const { if( !data->icon.isNull() ) data->invalidDrmIcon = DrmContentPrivate::createIcon( data->icon, qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ), qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ), false ); data->invalidDrmIconLoaded = true; } Q_GLOBAL_STATIC_WITH_ARGS(QSharedDataPointer<QMimeTypeDataPrivate>,nullQMimeTypeDataPrivate,(new QMimeTypeDataPrivate)); QMimeTypeData::QMimeTypeData() { d = *nullQMimeTypeDataPrivate(); } QMimeTypeData::QMimeTypeData( const QString &id ) { if( !id.isEmpty() ) { d = new QMimeTypeDataPrivate; d->id = id; } else d = *nullQMimeTypeDataPrivate(); } QMimeTypeData::QMimeTypeData( const QMimeTypeData &other ) : d( other.d ) { } QMimeTypeData::~QMimeTypeData() { } QMimeTypeData &QMimeTypeData::operator =( const QMimeTypeData &other ) { d = other.d; return *this; } bool QMimeTypeData::operator ==( const QMimeTypeData &other ) { return d->id == other.d->id; } QString QMimeTypeData::id() const { return d->id; } QContentList QMimeTypeData::applications() const { return d->applications; } QContent QMimeTypeData::defaultApplication() const { return d->defaultApplication; } QIcon QMimeTypeData::icon( const QContent &application ) const { if( d->applicationData.contains( application.id() ) ) { const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() ); if( !data->iconLoaded ) d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) ); return !data->icon.isNull() ? data->icon : data->application.icon(); } else return *unknownDocumentIcon(); } QIcon QMimeTypeData::validDrmIcon( const QContent &application ) const { if( d->applicationData.contains( application.id() ) ) { const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() ); if( !data->iconLoaded ) d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) ); if( !data->validDrmIconLoaded ) d->loadValidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) ); return !data->validDrmIcon.isNull() ? data->validDrmIcon : data->application.icon(); } else return *validDrmUnknownDocumentIcon(); } QIcon QMimeTypeData::invalidDrmIcon( const QContent &application ) const { if( d->applicationData.contains( application.id() ) ) { const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() ); if( !data->iconLoaded ) d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) ); if( !data->invalidDrmIconLoaded ) d->loadInvalidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) ); return !data->invalidDrmIcon.isNull() ? data->invalidDrmIcon : data->application.icon(); } else return *invalidDrmUnknownDocumentIcon(); } QDrmRights::Permission QMimeTypeData::permission( const QContent &application ) const { if( d->applicationData.contains( application.id() ) ) { const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() ); return data->permission; } else return QDrmRights::Unrestricted; } void QMimeTypeData::addApplication( const QContent &application, const QString &iconFile, QDrmRights::Permission permission ) { if( application.id() != QContent::InvalidId && !d->applicationData.contains( application.id() ) ) { QMimeTypeDataPrivate::AppData *data = new QMimeTypeDataPrivate::AppData; data->application = application; data->iconFile = iconFile; data->permission = permission; data->iconLoaded = false; data->validDrmIconLoaded = false; data->invalidDrmIconLoaded = false; d->applicationData.insert( application.id(), data ); d->applications.append( application ); if(d->defaultApplication.id() == QContent::InvalidId) setDefaultApplication(application); } } void QMimeTypeData::removeApplication( const QContent &application ) { if(d->applicationData.contains( application.id() )) { delete d->applicationData.take(application.id()); d->applications.removeAll(application); } } void QMimeTypeData::setDefaultApplication( const QContent &application ) { if(application.id() != QContent::InvalidId) d->defaultApplication = application; } template <typename Stream> void QMimeTypeData::serialize(Stream &stream) const { stream << d->id; stream << d->defaultApplication.id(); stream << d->applicationData.count(); QList< QContentId > keys = d->applicationData.keys(); foreach( QContentId contentId, keys ) { QMimeTypeDataPrivate::AppData *data = d->applicationData.value( contentId ); stream << contentId; stream << data->iconFile; stream << data->permission; } } template <typename Stream> void QMimeTypeData::deserialize(Stream &stream) { qDeleteAll( d->applicationData.values() ); d->applicationData.clear(); stream >> d->id; { QContentId contentId; stream >> contentId; d->defaultApplication = QContent( contentId ); } int count; stream >> count; for( int i = 0; i < count; i++ ) { QContentId contentId; QString iconFile; QDrmRights::Permission permission; stream >> contentId; stream >> iconFile; stream >> permission; addApplication( QContent( contentId ), iconFile, permission ); } } Q_IMPLEMENT_USER_METATYPE(QMimeTypeData);
Java
/* frame_data.c * Routines for packet disassembly * * $Id$ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * * 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 2 * 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. */ #include "config.h" #include <glib.h> #include <wiretap/wtap.h> #include <epan/frame_data.h> #include <epan/packet.h> #include <epan/emem.h> #include <epan/timestamp.h> /* Protocol-specific data attached to a frame_data structure - protocol index and opaque pointer. */ typedef struct _frame_proto_data { int proto; void *proto_data; } frame_proto_data; /* XXX - I declared this static, because it only seems to be used by * p_get_proto_data and p_add_proto_data */ static gint p_compare(gconstpointer a, gconstpointer b) { const frame_proto_data *ap = (const frame_proto_data *)a; const frame_proto_data *bp = (const frame_proto_data *)b; if (ap -> proto > bp -> proto) return 1; else if (ap -> proto == bp -> proto) return 0; else return -1; } void p_add_proto_data(frame_data *fd, int proto, void *proto_data) { frame_proto_data *p1 = se_alloc(sizeof(frame_proto_data)); p1->proto = proto; p1->proto_data = proto_data; /* Add it to the GSLIST */ fd -> pfd = g_slist_insert_sorted(fd -> pfd, (gpointer *)p1, p_compare); } void * p_get_proto_data(frame_data *fd, int proto) { frame_proto_data temp, *p1; GSList *item; temp.proto = proto; temp.proto_data = NULL; item = g_slist_find_custom(fd->pfd, (gpointer *)&temp, p_compare); if (item) { p1 = (frame_proto_data *)item->data; return p1->proto_data; } return NULL; } void p_remove_proto_data(frame_data *fd, int proto) { frame_proto_data temp; GSList *item; temp.proto = proto; temp.proto_data = NULL; item = g_slist_find_custom(fd->pfd, (gpointer *)&temp, p_compare); if (item) { fd->pfd = g_slist_remove(fd->pfd, item->data); } } #define COMPARE_FRAME_NUM() ((fdata1->num < fdata2->num) ? -1 : \ (fdata1->num > fdata2->num) ? 1 : \ 0) #define COMPARE_NUM(f) ((fdata1->f < fdata2->f) ? -1 : \ (fdata1->f > fdata2->f) ? 1 : \ COMPARE_FRAME_NUM()) /* Compare time stamps. A packet whose time is a reference time is considered to have a lower time stamp than any frame with a non-reference time; if both packets' times are reference times, we compare the times of the packets. */ #define COMPARE_TS_REAL(time1, time2) \ ((fdata1->flags.ref_time && !fdata2->flags.ref_time) ? -1 : \ (!fdata1->flags.ref_time && fdata2->flags.ref_time) ? 1 : \ ((time1).secs < (time2).secs) ? -1 : \ ((time1).secs > (time2).secs) ? 1 : \ ((time1).nsecs < (time2).nsecs) ? -1 :\ ((time1).nsecs > (time2).nsecs) ? 1 : \ COMPARE_FRAME_NUM()) #define COMPARE_TS(ts) COMPARE_TS_REAL(fdata1->ts, fdata2->ts) void frame_delta_abs_time(const frame_data *fdata, const frame_data *prev, nstime_t *delta) { if (prev) { nstime_delta(delta, &fdata->abs_ts, &prev->abs_ts); } else { /* If we don't have the time stamp of the previous packet, it's because we have no displayed/captured packets prior to this. Set the delta time to zero. */ nstime_set_zero(delta); } } static gint frame_data_time_delta_compare(const frame_data *fdata1, const frame_data *fdata2) { nstime_t del_cap_ts1, del_cap_ts2; frame_delta_abs_time(fdata1, fdata1->prev_cap, &del_cap_ts1); frame_delta_abs_time(fdata2, fdata2->prev_cap, &del_cap_ts2); return COMPARE_TS_REAL(del_cap_ts1, del_cap_ts2); } static gint frame_data_time_delta_dis_compare(const frame_data *fdata1, const frame_data *fdata2) { nstime_t del_dis_ts1, del_dis_ts2; frame_delta_abs_time(fdata1, fdata1->prev_dis, &del_dis_ts1); frame_delta_abs_time(fdata2, fdata2->prev_dis, &del_dis_ts2); return COMPARE_TS_REAL(del_dis_ts1, del_dis_ts2); } gint frame_data_compare(const frame_data *fdata1, const frame_data *fdata2, int field) { switch (field) { case COL_NUMBER: return COMPARE_FRAME_NUM(); case COL_CLS_TIME: switch (timestamp_get_type()) { case TS_ABSOLUTE: case TS_ABSOLUTE_WITH_DATE: case TS_UTC: case TS_UTC_WITH_DATE: case TS_EPOCH: return COMPARE_TS(abs_ts); case TS_RELATIVE: return COMPARE_TS(rel_ts); case TS_DELTA: return frame_data_time_delta_compare(fdata1, fdata2); case TS_DELTA_DIS: return frame_data_time_delta_dis_compare(fdata1, fdata2); case TS_NOT_SET: return 0; } return 0; case COL_ABS_TIME: case COL_ABS_DATE_TIME: case COL_UTC_TIME: case COL_UTC_DATE_TIME: return COMPARE_TS(abs_ts); case COL_REL_TIME: return COMPARE_TS(rel_ts); case COL_DELTA_TIME: return frame_data_time_delta_compare(fdata1, fdata2); case COL_DELTA_TIME_DIS: return frame_data_time_delta_dis_compare(fdata1, fdata2); case COL_PACKET_LENGTH: return COMPARE_NUM(pkt_len); case COL_CUMULATIVE_BYTES: return COMPARE_NUM(cum_bytes); } g_return_val_if_reached(0); } void frame_data_init(frame_data *fdata, guint32 num, const struct wtap_pkthdr *phdr, gint64 offset, guint32 cum_bytes) { fdata->pfd = NULL; fdata->num = num; fdata->interface_id = phdr->interface_id; fdata->pkt_len = phdr->len; fdata->cum_bytes = cum_bytes + phdr->len; fdata->cap_len = phdr->caplen; fdata->file_off = offset; fdata->subnum = 0; /* To save some memory, we coerce it into a gint16 */ g_assert(phdr->pkt_encap <= G_MAXINT16); fdata->lnk_t = (gint16) phdr->pkt_encap; fdata->flags.passed_dfilter = 0; fdata->flags.dependent_of_displayed = 0; fdata->flags.encoding = PACKET_CHAR_ENC_CHAR_ASCII; fdata->flags.visited = 0; fdata->flags.marked = 0; fdata->flags.ref_time = 0; fdata->flags.ignored = 0; fdata->flags.has_ts = (phdr->presence_flags & WTAP_HAS_TS) ? 1 : 0; fdata->flags.has_if_id = (phdr->presence_flags & WTAP_HAS_INTERFACE_ID) ? 1 : 0; fdata->color_filter = NULL; fdata->abs_ts.secs = phdr->ts.secs; fdata->abs_ts.nsecs = phdr->ts.nsecs; fdata->shift_offset.secs = 0; fdata->shift_offset.nsecs = 0; fdata->rel_ts.secs = 0; fdata->rel_ts.nsecs = 0; fdata->prev_dis = NULL; fdata->prev_cap = NULL; fdata->opt_comment = phdr->opt_comment; } void frame_data_set_before_dissect(frame_data *fdata, nstime_t *elapsed_time, nstime_t *first_ts, const frame_data *prev_dis, const frame_data *prev_cap) { /* If we don't have the time stamp of the first packet in the capture, it's because this is the first packet. Save the time stamp of this packet as the time stamp of the first packet. */ if (nstime_is_unset(first_ts)) *first_ts = fdata->abs_ts; /* if this frames is marked as a reference time frame, reset firstsec and firstusec to this frame */ if(fdata->flags.ref_time) *first_ts = fdata->abs_ts; /* Get the time elapsed between the first packet and this packet. */ nstime_delta(&fdata->rel_ts, &fdata->abs_ts, first_ts); /* If it's greater than the current elapsed time, set the elapsed time to it (we check for "greater than" so as not to be confused by time moving backwards). */ if ((gint32)elapsed_time->secs < fdata->rel_ts.secs || ((gint32)elapsed_time->secs == fdata->rel_ts.secs && (gint32)elapsed_time->nsecs < fdata->rel_ts.nsecs)) { *elapsed_time = fdata->rel_ts; } fdata->prev_dis = prev_dis; fdata->prev_cap = prev_cap; } void frame_data_set_after_dissect(frame_data *fdata, guint32 *cum_bytes) { /* This frame either passed the display filter list or is marked as a time reference frame. All time reference frames are displayed even if they dont pass the display filter */ if(fdata->flags.ref_time){ /* if this was a TIME REF frame we should reset the cul bytes field */ *cum_bytes = fdata->pkt_len; fdata->cum_bytes = *cum_bytes; } else { /* increase cum_bytes with this packets length */ *cum_bytes += fdata->pkt_len; fdata->cum_bytes = *cum_bytes; } } void frame_data_cleanup(frame_data *fdata) { if (fdata->pfd) { g_slist_free(fdata->pfd); fdata->pfd = NULL; } /* XXX, frame_data_cleanup() is called when redissecting (rescan_packets()), * which might be triggered by lot of things, like: preferences change, * setting manual address resolve, etc.. (grep by redissect_packets) * fdata->opt_comment can be set by user, which we must not discard when redissecting. */ #if 0 if (fdata->opt_comment) { g_free(fdata->opt_comment); fdata->opt_comment = NULL; } #endif }
Java
package org.iproduct.iptpi.domain.movement; import static java.lang.Math.PI; import static java.lang.Math.abs; import static java.lang.Math.atan; import static java.lang.Math.cbrt; import static java.lang.Math.cos; import static java.lang.Math.hypot; import static java.lang.Math.min; import static java.lang.Math.pow; import static java.lang.Math.signum; import static java.lang.Math.sin; import static java.lang.Math.sqrt; import static java.lang.Math.tan; import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAIN_AXE_LENGTH; import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_ANGULAR_ACCELERATION; import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_ACCELERATION; import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_VELOCITY; import static org.iproduct.iptpi.demo.robot.RobotParametrs.ROBOT_STOPPING_DECCELERATION; import static org.iproduct.iptpi.demo.robot.RobotParametrs.WHEEL_RADIUS; import static org.iproduct.iptpi.domain.CommandName.STOP; import static org.iproduct.iptpi.domain.CommandName.VOID; import org.iproduct.iptpi.domain.Command; import org.iproduct.iptpi.domain.arduino.LineReadings; import org.iproduct.iptpi.domain.audio.AudioPlayer; import org.iproduct.iptpi.domain.position.Position; import org.iproduct.iptpi.domain.position.PositionsFlux; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.pi4j.wiringpi.Gpio; import reactor.core.publisher.EmitterProcessor; import reactor.core.publisher.Flux; import reactor.util.function.Tuple2; import reactor.util.function.Tuple3; import reactor.util.function.Tuple4; import reactor.util.function.Tuples; public class MovementCommandSubscriber implements Subscriber<Command> { public static final int MAX_SPEED = 1024; public static final int CLOCK_DIVISOR = 2; public static final double LANDING_CURVE_PARAMETER = 0.000000005; public static final MotorsCommand STOP_COMMAND = new MotorsCommand(0, 0, 0, 0, 0); private Subscription subscription; private PositionsFlux positions; private Flux<LineReadings> lineReadings; // private SchedulerGroup eventLoops = SchedulerGroup.async(); //Create movement command broadcaster private EmitterProcessor<Command> commandFlux = EmitterProcessor.create(); public MovementCommandSubscriber(PositionsFlux positions, Flux<LineReadings> lineReadings) { this.positions = positions; this.lineReadings = lineReadings; } @Override public void onNext(Command command) { setupGpioForMovement(); switch (command.getName()) { case MOVE_FORWARD : moveForward(command); break; case FOLLOW_LINE : followLine(command); break; case MOVE_RELATIVE : moveRelative(command); break; case STOP : System.out.println("STOPPING THE ROBOT"); runMotors(STOP_COMMAND); break; default: break; } } protected void moveRelative(Command command) { RelativeMovement relMove = (RelativeMovement) command.getData(); // start moving - and think later as it comes :) int directionL, directionR; if(relMove.getVelocity() < 0) { directionL = directionR = -1; } else { directionL = directionR = 1; } double targetVelocity = abs(relMove.getVelocity()); int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown System.out.println(initialCommand); runMotors(initialCommand); Position startPos = positions.elementAt(1).block(); double targetDeltaX = relMove.getDeltaX(); double targetDeltaY = relMove.getDeltaY(); double targetX = startPos.getX() + targetDeltaX; double targetY = startPos.getY() + targetDeltaY; double distance = hypot(targetDeltaX, targetDeltaY); System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX ); System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY ); System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance); double targetHeading, targetDeltaHeading, targetCurvature, h = 0; if(relMove.getDeltaHeading() == 0 ) { targetCurvature = targetDeltaHeading = 0; targetHeading = startPos.getHeading(); } else { targetDeltaHeading = relMove.getDeltaHeading(); targetHeading = startPos.getHeading() + targetDeltaHeading ; targetCurvature = (2 * sin(targetDeltaHeading / 2) ) / distance ; h = sqrt( 1/(targetCurvature * targetCurvature) - 0.25 * distance * distance ); } double xC, yC; //circle center coordinates double r = hypot(distance/2, h); if(targetCurvature != 0) { double q = hypot( targetX - startPos.getX(), targetY - startPos.getY() ), x3 = (targetX + startPos.getX()) /2, y3 = (targetY + startPos.getY()) /2; if(targetCurvature > 0) { xC = x3 + sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q; yC = y3 + sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q; } else { xC = x3 - sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q; yC = y3 - sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q; } } else { xC = (targetX + startPos.getX()) /2; yC = (targetY + startPos.getY()) /2; } System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading ); System.out.println("$$$$$$$$$$$$$$ TargetCurvature=" + targetCurvature ); double targetAngularVelocity; if (targetDeltaHeading != 0 && relMove.getAngularVelocity() == 0) targetAngularVelocity = targetVelocity * targetCurvature; else targetAngularVelocity = relMove.getAngularVelocity(); double startH = startPos.getHeading(); System.out.println("START POSITION: " + startPos); Flux<Position> skip1 = positions.skip(1); Flux.zip(positions, skip1) .scan(initialCommand, (last, tupple) -> { Position prevPos = ((Position)tupple.getT1()); Position currPos = ((Position)tupple.getT2()); float prevX = prevPos.getX(); float prevY = prevPos.getY(); double prevH = prevPos.getHeading(); float currX = currPos.getX(); float currY = currPos.getY(); double currH = currPos.getHeading(); System.out.println(currPos + " - " + prevPos); double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings if(dt <= 0) return last; // if invalid sequence do nothing double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0; // calculating the ideal trajectory position double tarX, tarY, tarH, remainingPathLength; if(targetCurvature == 0) { tarX = startPos.getX() + targetVelocity * time * cos(targetHeading); tarY = startPos.getY() + targetVelocity * time * sin(targetHeading); remainingPathLength = hypot(targetX - currX, targetY - currY) ; tarH = targetHeading; } else { double deltaHeading = targetAngularVelocity * time; double startAng = atan((startPos.getY() - yC) / (startPos.getX() - xC)); double angle = startAng + deltaHeading; if(signum(angle) != (startPos.getY() - yC)) angle -= PI; tarX = cos(angle) * r + xC; tarY = sin(angle) * r + yC; tarH = startPos.getHeading() + deltaHeading; remainingPathLength = (targetDeltaHeading - deltaHeading ) / targetCurvature; // System.out.println(" -----> tarX=" + tarX + ", tarY=" + tarY + ", tarH=" + tarH + ", deltaHeading=" + deltaHeading + ", startAng=" + startAng + ", angle=" + angle); // System.out.println(" -----> r=" + r + ", xC=" + xC + ", yC=" + yC ); } //calculating current trajectory parameters float dX = currX - prevX; float dY = currY - prevY; double currDist = hypot(dX, dY); double currV = currDist / dt; // current velocity [mm/s] double currAngV = (currH - prevH) / dt; //calculating errors double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH); double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH); double errH = tarH - currH; //calculating landing curve double Cx = LANDING_CURVE_PARAMETER; double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY); double landH = tarH + atan(dlandY); double dErrY = -targetAngularVelocity * errX + currV * sin (errH); double landAngV = targetAngularVelocity + (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) / (1 + tan(landH - tarH) * tan(landH - tarH)); //calculating the corrected trajectory control parameters double switchAngV = landAngV - currAngV + sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH)) * signum(landH - currH) * 0.2; double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV); double newAngV = currAngV + switchAngA * dt; //calculating new velocity double dErrX = targetVelocity - currV * cos(errH) + targetAngularVelocity * errY; double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX); double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV); //calculating delta motor speed control values double k = 0.1; double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS); //calculating new motor speed control values int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL()); int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL()); System.out.println("--> errH=" + errH + ", targetHeading=" + targetHeading + ", currH=" + currH + ", dist=" + currDist ); // System.out.println("!!! landH=" + landH + ", dErrY=" + dErrY // + ", currAngV=" + currAngV + ", landAngV=" + landAngV + ", switchAngV=" + switchAngV // + ", switchAngA=" + switchAngA + ", newAngV=" + newAngV ); // System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA ); // System.out.println("!!! newDeltaV=" + switchA * dt / WHEEL_RADIUS + ", newDelatLR=" + newDeltaLR + ", newVL=" + newVL + ", newVR=" + newVR); double remainingDeltaHeading = targetHeading - currH; if(remainingPathLength < last.getRemainingPath() && remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION || targetDeltaHeading > 0.01 && abs(remainingDeltaHeading) > 0.05 && remainingDeltaHeading * targetDeltaHeading > 0 ) { //drive until minimum distance to target return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength); } else { System.out.println("FINAL POSITION: " + currPos); return STOP_COMMAND; } }).map((MotorsCommand motorsCommand) -> { runMotors(motorsCommand); return motorsCommand; }) .takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) ) .subscribe( (MotorsCommand motorsCommand) -> { System.out.println(motorsCommand); }); } protected void followLine(Command command) { { ForwardMovement forwardMove = (ForwardMovement) command.getData(); // start moving - and think later as it comes :) int directionL, directionR; if(forwardMove.getVelocity() < 0) { directionL = directionR = -1; } else { directionL = directionR = 1; } double targetVelocity = abs(forwardMove.getVelocity()); int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown System.out.println(initialCommand); runMotors(initialCommand); Position startPos = positions.elementAt(1).block(); double distance = forwardMove.getDistance(); double targetHeading = startPos.getHeading(); double targetDeltaX = distance * cos(targetHeading); double targetDeltaY = distance * sin(targetHeading); double targetX = startPos.getX() + targetDeltaX; double targetY = startPos.getY() + targetDeltaY; System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX ); System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY ); System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance); System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading ); double startH = startPos.getHeading(); System.out.println("START POSITION: " + startPos); Flux<Position> skip1 = positions.skip(1); Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1); Flux<Tuple4<Position, Position, LineReadings, Command>> flux = Flux.combineLatest( lastTwoPositionsFlux, lineReadings, commandFlux.startWith(new Command(VOID, null)), (Object[] args) -> Tuples.of(((Tuple2<Position, Position>)args[0]).getT1(), ((Tuple2<Position, Position>)args[0]).getT2(), (LineReadings)args[1], (Command)args[2]) ); flux.scan(initialCommand, (last, tuple4) -> { System.out.println("########## NEW EVENT !!!!!!!!!!!"); Position prevPos = tuple4.getT1(); Position currPos = tuple4.getT2(); LineReadings lastReadings = tuple4.getT3(); Command lastCommand = tuple4.getT4(); float prevX = prevPos.getX(); float prevY = prevPos.getY(); double prevH = prevPos.getHeading(); float currX = currPos.getX(); float currY = currPos.getY(); double currH = currPos.getHeading(); System.out.println(currPos + " - " + prevPos); double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings if(dt <= 0) return last; // if invalid sequence do nothing double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0; // calculating the ideal trajectory position double tarX, tarY, tarH, remainingPathLength; tarX = startPos.getX() + targetVelocity * time * cos(targetHeading); tarY = startPos.getY() + targetVelocity * time * sin(targetHeading); remainingPathLength = hypot(targetX - currX, targetY - currY) ; tarH = targetHeading; //calculating current trajectory parameters float dX = currX - prevX; float dY = currY - prevY; double currDist = hypot(dX, dY); double currV = currDist / dt; // current velocity [mm/s] double currAngV = (currH - prevH) / dt; //calculating errors double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH); double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH); double errH = tarH - currH; //calculating landing curve double Cx = LANDING_CURVE_PARAMETER; double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY); double landH = tarH + atan(dlandY); double dErrY = currV * sin (errH); double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) / (1 + tan(landH - tarH) * tan(landH - tarH)); //calculating the corrected trajectory control parameters double switchAngV = landAngV - currAngV + sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH)) * signum(landH - currH) * 0.2; double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV); double newAngV = currAngV + switchAngA * dt; //calculating new velocity double dErrX = targetVelocity - currV * cos(errH); double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX); double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV); // double newV = currV + switchA * dt; //calculating delta motor speed control values double k = 0.1; double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS); //calculating new motor speed control values int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL()); int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL()); System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY + ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading + ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist + ", switchAngV/dt=" + switchAngV / dt ); System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA ); if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath() && remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength); } else { System.out.println("FINAL POSITION: " + currPos); return STOP_COMMAND; } }).map((MotorsCommand motorsCommand) -> { runMotors(motorsCommand); return motorsCommand; }) .takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) ) .subscribe( (MotorsCommand motorsCommand) -> { System.out.println(motorsCommand); }); } } protected void moveForward(Command command) { { ForwardMovement forwardMove = (ForwardMovement) command.getData(); // start moving - and think later as it comes :) int directionL, directionR; if(forwardMove.getVelocity() < 0) { directionL = directionR = -1; } else { directionL = directionR = 1; } double targetVelocity = abs(forwardMove.getVelocity()); int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown System.out.println(initialCommand); runMotors(initialCommand); Position startPos = positions.elementAt(1).block(); double distance = forwardMove.getDistance(); double targetHeading = startPos.getHeading(); double targetDeltaX = distance * cos(targetHeading); double targetDeltaY = distance * sin(targetHeading); double targetX = startPos.getX() + targetDeltaX; double targetY = startPos.getY() + targetDeltaY; System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX ); System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY ); System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance); System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading ); double startH = startPos.getHeading(); System.out.println("START POSITION: " + startPos); Flux<Position> skip1 = positions.skip(1); Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1); Flux<Tuple3<Position, Position, Command>> flux = Flux.combineLatest( lastTwoPositionsFlux, commandFlux.startWith(new Command(VOID, null)), (tuple2, lastCommand) -> Tuples.of(tuple2.getT1(), tuple2.getT2(), lastCommand) ); flux.scan(initialCommand, (last, tuple3) -> { System.out.println("########## NEW EVENT !!!!!!!!!!!"); Position prevPos = tuple3.getT1(); Position currPos = tuple3.getT2(); Command lastCommand = tuple3.getT3(); float prevX = prevPos.getX(); float prevY = prevPos.getY(); double prevH = prevPos.getHeading(); float currX = currPos.getX(); float currY = currPos.getY(); double currH = currPos.getHeading(); System.out.println(currPos + " - " + prevPos); double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings if(dt <= 0) return last; // if invalid sequence do nothing double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0; // calculating the ideal trajectory position double tarX, tarY, tarH, remainingPathLength; tarX = startPos.getX() + targetVelocity * time * cos(targetHeading); tarY = startPos.getY() + targetVelocity * time * sin(targetHeading); remainingPathLength = hypot(targetX - currX, targetY - currY) ; tarH = targetHeading; //calculating current trajectory parameters float dX = currX - prevX; float dY = currY - prevY; double currDist = hypot(dX, dY); double currV = currDist / dt; // current velocity [mm/s] double currAngV = (currH - prevH) / dt; //calculating errors double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH); double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH); double errH = tarH - currH; //calculating landing curve double Cx = LANDING_CURVE_PARAMETER; double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY); double landH = tarH + atan(dlandY); double dErrY = currV * sin (errH); double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) / (1 + tan(landH - tarH) * tan(landH - tarH)); //calculating the corrected trajectory control parameters double switchAngV = landAngV - currAngV + sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH)) * signum(landH - currH) * 0.2; double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV); double newAngV = currAngV + switchAngA * dt; //calculating new velocity double dErrX = targetVelocity - currV * cos(errH); double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX); double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV); // double newV = currV + switchA * dt; //calculating delta motor speed control values double k = 0.1; double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS); //calculating new motor speed control values int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL()); int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL()); System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY + ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading + ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist + ", switchAngV/dt=" + switchAngV / dt ); System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA ); if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath() && remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength); } else { System.out.println("FINAL POSITION: " + currPos); return STOP_COMMAND; } }).map((MotorsCommand motorsCommand) -> { runMotors(motorsCommand); return motorsCommand; }) .takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) ) .subscribe( (MotorsCommand motorsCommand) -> { System.out.println(motorsCommand); }); } } protected void setupGpioForMovement() { // Motor direction pins Gpio.pinMode(5, Gpio.OUTPUT); Gpio.pinMode(6, Gpio.OUTPUT); Gpio.pinMode(12, Gpio.PWM_OUTPUT); Gpio.pinMode(13, Gpio.PWM_OUTPUT); Gpio.pwmSetMode(Gpio.PWM_MODE_MS); Gpio.pwmSetRange(MAX_SPEED); Gpio.pwmSetClock(CLOCK_DIVISOR); } private void runMotors(MotorsCommand mc) { //setting motor directions Gpio.digitalWrite(5, mc.getDirR() > 0 ? 1 : 0); Gpio.digitalWrite(6, mc.getDirL() > 0 ? 1 : 0); //setting speed if(mc.getVelocityR() >= 0 && mc.getVelocityR() <= MAX_SPEED) Gpio.pwmWrite(12, mc.getVelocityR()); // speed up to MAX_SPEED if(mc.getVelocityL() >= 0 && mc.getVelocityL() <= MAX_SPEED) Gpio.pwmWrite(13, mc.getVelocityL()); } @Override public void onSubscribe(Subscription s) { subscription = s; subscription.request(Long.MAX_VALUE); } @Override public void onError(Throwable t) { // TODO Auto-generated method stub } @Override public void onComplete() { // TODO Auto-generated method stub } }
Java
package cn.ac.iscas.cloudeploy.v2.puppet.transform.ast; import java.util.List; public class ASTCollExpr extends ASTBase{ private Object test1; private Object test2; private String oper; private List<Object> children; private String form; private String type; public Object getTest1() { return test1; } public void setTest1(Object test1) { this.test1 = test1; } public Object getTest2() { return test2; } public void setTest2(Object test2) { this.test2 = test2; } public String getOper() { return oper; } public void setOper(String oper) { this.oper = oper; } public List<Object> getChildren() { return children; } public void setChildren(List<Object> children) { this.children = children; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.FocusFinder; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import com.android.launcher.R; public class Cling extends FrameLayout { static final String WORKSPACE_CLING_DISMISSED_KEY = "cling.workspace.dismissed"; static final String ALLAPPS_CLING_DISMISSED_KEY = "cling.allapps.dismissed"; static final String FOLDER_CLING_DISMISSED_KEY = "cling.folder.dismissed"; private static String WORKSPACE_PORTRAIT = "workspace_portrait"; private static String WORKSPACE_LANDSCAPE = "workspace_landscape"; private static String WORKSPACE_LARGE = "workspace_large"; private static String WORKSPACE_CUSTOM = "workspace_custom"; private static String ALLAPPS_PORTRAIT = "all_apps_portrait"; private static String ALLAPPS_LANDSCAPE = "all_apps_landscape"; private static String ALLAPPS_LARGE = "all_apps_large"; private static String FOLDER_PORTRAIT = "folder_portrait"; private static String FOLDER_LANDSCAPE = "folder_landscape"; private static String FOLDER_LARGE = "folder_large"; private Launcher mLauncher; private boolean mIsInitialized; private String mDrawIdentifier; private Drawable mBackground; private Drawable mPunchThroughGraphic; private Drawable mHandTouchGraphic; private int mPunchThroughGraphicCenterRadius; private int mAppIconSize; private int mButtonBarHeight; private float mRevealRadius; private int[] mPositionData; private Paint mErasePaint; public Cling(Context context) { this(context, null, 0); } public Cling(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Cling(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Cling, defStyle, 0); mDrawIdentifier = a.getString(R.styleable.Cling_drawIdentifier); a.recycle(); setClickable(true); } void init(Launcher l, int[] positionData) { if (!mIsInitialized) { mLauncher = l; mPositionData = positionData; Resources r = getContext().getResources(); mPunchThroughGraphic = r.getDrawable(R.drawable.cling); mPunchThroughGraphicCenterRadius = r.getDimensionPixelSize(R.dimen.clingPunchThroughGraphicCenterRadius); mAppIconSize = r.getDimensionPixelSize(R.dimen.app_icon_size); mRevealRadius = r.getDimensionPixelSize(R.dimen.reveal_radius) * 1f; mButtonBarHeight = r.getDimensionPixelSize(R.dimen.button_bar_height); mErasePaint = new Paint(); mErasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY)); mErasePaint.setColor(0xFFFFFF); mErasePaint.setAlpha(0); mIsInitialized = true; } } void cleanup() { mBackground = null; mPunchThroughGraphic = null; mHandTouchGraphic = null; mIsInitialized = false; } public String getDrawIdentifier() { return mDrawIdentifier; } private int[] getPunchThroughPositions() { if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT)) { return new int[]{getMeasuredWidth() / 2, getMeasuredHeight() - (mButtonBarHeight / 2)}; } else if (mDrawIdentifier.equals(WORKSPACE_LANDSCAPE)) { return new int[]{getMeasuredWidth() - (mButtonBarHeight / 2), getMeasuredHeight() / 2}; } else if (mDrawIdentifier.equals(WORKSPACE_LARGE)) { final float scale = LauncherApplication.getScreenDensity(); final int cornerXOffset = (int) (scale * 15); final int cornerYOffset = (int) (scale * 10); return new int[]{getMeasuredWidth() - cornerXOffset, cornerYOffset}; } else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) || mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) || mDrawIdentifier.equals(ALLAPPS_LARGE)) { return mPositionData; } return new int[]{-1, -1}; } @Override public View focusSearch(int direction) { return this.focusSearch(this, direction); } @Override public View focusSearch(View focused, int direction) { return FocusFinder.getInstance().findNextFocus(this, focused, direction); } @Override public boolean onHoverEvent(MotionEvent event) { return (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) || mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) || mDrawIdentifier.equals(WORKSPACE_LARGE) || mDrawIdentifier.equals(ALLAPPS_PORTRAIT) || mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) || mDrawIdentifier.equals(ALLAPPS_LARGE) || mDrawIdentifier.equals(WORKSPACE_CUSTOM)); } @Override public boolean onTouchEvent(android.view.MotionEvent event) { if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) || mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) || mDrawIdentifier.equals(WORKSPACE_LARGE) || mDrawIdentifier.equals(ALLAPPS_PORTRAIT) || mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) || mDrawIdentifier.equals(ALLAPPS_LARGE)) { int[] positions = getPunchThroughPositions(); for (int i = 0; i < positions.length; i += 2) { double diff = Math.sqrt(Math.pow(event.getX() - positions[i], 2) + Math.pow(event.getY() - positions[i + 1], 2)); if (diff < mRevealRadius) { return false; } } } else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) || mDrawIdentifier.equals(FOLDER_LANDSCAPE) || mDrawIdentifier.equals(FOLDER_LARGE)) { Folder f = mLauncher.getWorkspace().getOpenFolder(); if (f != null) { Rect r = new Rect(); f.getHitRect(r); if (r.contains((int) event.getX(), (int) event.getY())) { return false; } } } return true; }; @Override protected void dispatchDraw(Canvas canvas) { if (mIsInitialized) { DisplayMetrics metrics = new DisplayMetrics(); mLauncher.getWindowManager().getDefaultDisplay().getMetrics(metrics); // Initialize the draw buffer (to allow punching through) Bitmap b = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); // Draw the background if (mBackground == null) { if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) || mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) || mDrawIdentifier.equals(WORKSPACE_LARGE)) { mBackground = getResources().getDrawable(R.drawable.bg_cling1); } else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) || mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) || mDrawIdentifier.equals(ALLAPPS_LARGE)) { mBackground = getResources().getDrawable(R.drawable.bg_cling2); } else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) || mDrawIdentifier.equals(FOLDER_LANDSCAPE)) { mBackground = getResources().getDrawable(R.drawable.bg_cling3); } else if (mDrawIdentifier.equals(FOLDER_LARGE)) { mBackground = getResources().getDrawable(R.drawable.bg_cling4); } else if (mDrawIdentifier.equals(WORKSPACE_CUSTOM)) { mBackground = getResources().getDrawable(R.drawable.bg_cling5); } } if (mBackground != null) { mBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); mBackground.draw(c); } else { c.drawColor(0x99000000); } int cx = -1; int cy = -1; float scale = mRevealRadius / mPunchThroughGraphicCenterRadius; int dw = (int) (scale * mPunchThroughGraphic.getIntrinsicWidth()); int dh = (int) (scale * mPunchThroughGraphic.getIntrinsicHeight()); // Determine where to draw the punch through graphic int[] positions = getPunchThroughPositions(); for (int i = 0; i < positions.length; i += 2) { cx = positions[i]; cy = positions[i + 1]; if (cx > -1 && cy > -1) { c.drawCircle(cx, cy, mRevealRadius, mErasePaint); mPunchThroughGraphic.setBounds(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2); mPunchThroughGraphic.draw(c); } } // Draw the hand graphic in All Apps if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) || mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) || mDrawIdentifier.equals(ALLAPPS_LARGE)) { if (mHandTouchGraphic == null) { mHandTouchGraphic = getResources().getDrawable(R.drawable.hand); } int offset = mAppIconSize / 4; mHandTouchGraphic.setBounds(cx + offset, cy + offset, cx + mHandTouchGraphic.getIntrinsicWidth() + offset, cy + mHandTouchGraphic.getIntrinsicHeight() + offset); mHandTouchGraphic.draw(c); } canvas.drawBitmap(b, 0, 0, null); c.setBitmap(null); b = null; } // Draw the rest of the cling super.dispatchDraw(canvas); }; }
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- template designed by Marco Von Ballmoos --> <title>Docs for page default.php</title> <link rel="stylesheet" href="../../media/stylesheet.css" /> <script src="../../media/lib/classTree.js"></script> <script language="javascript" type="text/javascript"> var imgPlus = new Image(); var imgMinus = new Image(); imgPlus.src = "../../media/images/plus.png"; imgMinus.src = "../../media/images/minus.png"; function showNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgMinus.src; oTable.style.display = "block"; } function hideNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgPlus.src; oTable.style.display = "none"; } function nodeIsVisible(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); break; } return (oTable && oTable.style.display == "block"); } function toggleNodeVisibility(Node){ if (nodeIsVisible(Node)){ hideNode(Node); }else{ showNode(Node); } } </script> </head> <body> <div class="page-body"> <h2 class="file-name"><img src="../../media/images/Page_logo.png" alt="File" style="vertical-align: middle">/components/com_content/views/featured/tmpl/default.php</h2> <a name="sec-description"></a> <div class="info-box"> <div class="info-box-title">Description</div> <div class="nav-bar"> </div> <div class="info-box-body"> <!-- ========== Info from phpDoc block ========= --> <ul class="tags"> <li><span class="field">copyright:</span> Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.</li> <li><span class="field">filesource:</span> <a href="../../filesource/fsource_Joomla-Site_com_content_componentscom_contentviewsfeaturedtmpldefault.php.html">Source Code for this file</a></li> <li><span class="field">license:</span> GNU</li> </ul> </div> </div> <p class="notes" id="credit"> Documentation generated on Tue, 19 Nov 2013 14:58:39 +0100 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.3</a> </p> </div></body> </html>
Java
package rb; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.persistence.TypedQuery; import rb.helpers.ClassificationResult; import rb.helpers.DBHandler; import rb.helpers.StemmerHelper; import rb.persistentobjects.Statement; import rb.persistentobjects.Word; import ca.uwo.csd.ai.nlp.common.SparseVector; import ca.uwo.csd.ai.nlp.kernel.KernelManager; import ca.uwo.csd.ai.nlp.kernel.LinearKernel; import ca.uwo.csd.ai.nlp.libsvm.svm_model; import ca.uwo.csd.ai.nlp.libsvm.ex.Instance; import ca.uwo.csd.ai.nlp.libsvm.ex.SVMPredictor; import com.cd.reddit.Reddit; import com.cd.reddit.RedditException; import com.cd.reddit.json.jackson.RedditJsonParser; import com.cd.reddit.json.mapping.RedditComment; import com.cd.reddit.json.mapping.RedditLink; import com.cd.reddit.json.util.RedditComments; import de.daslaboratorium.machinelearning.classifier.BayesClassifier; import de.daslaboratorium.machinelearning.classifier.Classification; public class Poster { private static Random randomGenerator; static Reddit reddit = new Reddit("machinelearningbot/0.1 by elggem"); static String subreddit = ""; static BayesClassifier<String, String> bayes = null; static svm_model model = null; static List<Statement> statements = null; static List<Word> words = null; static int max_reply_length = 25; static int classifier = 0; static ArrayList<String> alreadyPostedComments = new ArrayList<String>(); /** * @param args */ public static void main(String[] args) { System.out.println("Reddit BOT Final stage. Armed and ready to go!"); randomGenerator = new Random(); if (args.length < 4) { System.out.println(" usage: java -Xmx4g -jar JAR SUBREDDIT CLASSIFIER USER PASS\n" + " with: SUBREDDIT = the subreddit to post to\n" + " CLASSIFIER = 1:BN, 2:SVM 3:Random\n" + " USER/PASS = username and password\n"); System.exit(1); } subreddit = args[0]; classifier = Integer.valueOf(args[1]); try { reddit.login(args[2], args[3]); } catch (RedditException e) { e.printStackTrace(); } DBHandler.initializeHandler(args[0]); if (statements == null) { TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class); statements = query.getResultList(); } if (words == null) { TypedQuery<Word> queryW=DBHandler.em.createQuery("Select o from Word o",Word.class); words = queryW.getResultList(); } //TIMER CODE Timer timer = new Timer(); long thirty_minutes = 30*60*1000; long one_hour = thirty_minutes*2; long waiting_time = (long) (one_hour+(Math.random()*one_hour)); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("-> Awake from Hibernation"); RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit); System.out.println("-> Generating Reply for " + commentToReplyTo.getBody()); String generatedReply = generateCommentFor(commentToReplyTo, classifier); System.out.println("-> Generated " + generatedReply); System.out.println("-> Posting.."); postCommentAsReplyTo(generatedReply, commentToReplyTo); System.out.println("-> Going Back to Sleep..."); } }, waiting_time, waiting_time); //------------- System.out.println("-> Awake from Hibernation"); RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit); System.out.println("-> Generating Reply for " + commentToReplyTo.getBody()); String generatedReply = generateCommentFor(commentToReplyTo, classifier); System.out.println("-> Generated " + generatedReply); System.out.println("-> Posting.."); postCommentAsReplyTo(generatedReply, commentToReplyTo); System.out.println("-> Going Back to Sleep..."); ///--------------------- //DBHandler.closeHandler(); } public static RedditComment findInterestingCommentRelevance(String subreddit) { //Get the first 25 posts. try { List<RedditLink> links = reddit.listingFor(subreddit, ""); Collections.shuffle(links); RedditLink linkOfInterest = links.get(0); System.out.println(" findInterestingComment post: " + linkOfInterest); List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit); ArrayList<ClassificationResult> classifications = new ArrayList<ClassificationResult>(); for (RedditComment redditComment : comments) { classifications.add(classifyCommentBayes(redditComment)); } RedditComment bestComment = null; double max_prob = 0; int i=0; for (RedditComment redditComment : comments) { double prob = classifications.get(i).probability; if (prob>max_prob && convertStringToStemmedList(redditComment.getBody()).size()>0) { max_prob = prob; bestComment = redditComment; } i++; } System.out.println(" findInterestingComment comment: " + bestComment); return bestComment; } catch (Exception e) { System.out.println("ERROR, trying next time: " + e.getLocalizedMessage()); } return null; } public static RedditComment findInterestingCommentPopularity(String subreddit) { //Get the first 25 posts. try { List<RedditLink> links = reddit.listingFor(subreddit, ""); Collections.shuffle(links); RedditLink linkOfInterest = links.get(0); System.out.println(" findInterestingComment post: " + linkOfInterest); List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit); RedditComment bestComment = null; long max_karma = 0; for (RedditComment redditComment : comments) { if (redditComment.getUps()-redditComment.getDowns() > max_karma) { //if (redditComment.getReplies().toString().length() <= 10) { max_karma = redditComment.getUps()-redditComment.getDowns(); bestComment = redditComment; //} } } System.out.println(" findInterestingComment comment: " + bestComment); return bestComment; } catch (Exception e) { System.out.println("ERROR, trying next time: " + e.getLocalizedMessage()); } return null; } public static String generateCommentFor(RedditComment comment, int classifierID) { String generated = ""; if (classifierID == 1) { generated = classifyCommentBayes(comment).resultString; } else if (classifierID == 2) { generated = classifyCommentSVM(comment); } else if (classifierID == 3) { generated = classifyCommentRandom(comment); } else { System.out.println("Choose a valid classifier dude."); System.exit(1); } return generated; } public static void postCommentAsReplyTo(String comment, RedditComment parent) { try { System.out.println(" postCommentAsReplyTo response: "+reddit.comment(comment, parent.getName())); } catch (RedditException e) { System.out.println("ERROR, trying next time: " + e.getLocalizedMessage()); } } public static String classifyCommentSVM(RedditComment comment) { if (model == null) { try { model = SVMPredictor.loadModel(subreddit + ".model"); } catch (Exception e1) { System.out.println("ERROR: Couldnt load SVM model. Exitting"); System.exit(1); } KernelManager.setCustomKernel(new LinearKernel()); System.out.println(" classifyCommentSVM: loaded model!!"); } ArrayList<String> inputlist = convertStringToStemmedList(comment.getBody()); SparseVector vec = new SparseVector(); for (Word word : words) { int value = 0; if(inputlist.contains(word.word)) { value = 1; } vec.add(words.indexOf(word), value); } Instance inst = new Instance(0, vec); double result = SVMPredictor.predict(inst, model, false); return statements.get((int) result).text; } public static ClassificationResult classifyCommentBayes(RedditComment comment) { if (bayes == null) { // Create a new bayes classifier with string categories and string features. bayes = new BayesClassifier<String, String>(); // Change the memory capacity. New learned classifications (using // learn method are stored in a queue with the size given here and // used to classify unknown sentences. bayes.setMemoryCapacity(50000); TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class); List<Statement> statements = query.getResultList(); System.out.println(" classifyCommentBayes analyzing " + statements.size() + " statements... "); for (Statement statement : statements) { ArrayList<String> wordStrings = new ArrayList<String>(); for (Word word : statement.parentStatement.includedWords) { wordStrings.add(word.word); } //LEARN bayes.learn(statement.text, wordStrings); } } ArrayList<String> list = convertStringToStemmedList(comment.getBody()); Classification<String,String> result = bayes.classify(list); System.out.println(" classifyCommentBayes " + list + " prob " + result.getProbability()); return new ClassificationResult(result.getCategory(), result.getProbability()); } public static String classifyCommentRandom(RedditComment comment) { String result = statements.get(randomGenerator.nextInt(statements.size())).text; System.out.println(" classifyCommentRandom "); return result; } public static List<RedditComment>getAllRepliesForComment(RedditComment redditComment) { List<RedditComment> thelist = new ArrayList<RedditComment>(); try { thelist.add(redditComment); if (redditComment.getReplies().toString().length() >= 10) { final RedditJsonParser parser = new RedditJsonParser(redditComment.getReplies()); List<RedditComment> redditReplies = parser.parseCommentsOnly(); for (RedditComment redditCommentReply : redditReplies) { List<RedditComment> additionalList = getAllRepliesForComment(redditCommentReply); for (RedditComment redditComment2 : additionalList) { redditComment2.parent = redditComment; } thelist.addAll(additionalList); } } } catch (RedditException e) { e.printStackTrace(); } return thelist; } public static List<RedditComment>getAllCommentsForLink(RedditLink redditLink, String subreddit) { List<RedditComment> thelist = new ArrayList<RedditComment>(); try { if (redditLink.getNum_comments()>0) { RedditComments comments; comments = reddit.commentsFor(subreddit, redditLink.getId()); for (RedditComment redditComment : comments.getComments()) { List<RedditComment> additionalList = getAllRepliesForComment(redditComment); thelist.addAll(additionalList); } } } catch (RedditException e) { e.printStackTrace(); } return thelist; } public static ArrayList<String> convertStringToStemmedList(String input) { ArrayList<String> wordStrings = new ArrayList<String>(); for (String string : input.split("\\s+")) { String pruned = string.replaceAll("[^a-zA-Z]", "").toLowerCase(); String stemmed = StemmerHelper.stemWord(pruned); if (DBHandler.checkWord(stemmed)) { wordStrings.add(stemmed); } } return wordStrings; } }
Java
<?php class WebApplication extends CWebApplication { public $keywords; public $description; }
Java
#ifndef __ANSI_H__ #define __ANSI_H__ #define STATE_ESC_SET 0x01 #define STATE_FONT_SET 0x02 #define STATE_NEW_LINE 0x04 #define STATE_QUOTE_LINE 0x08 #define STATE_NONE 0x00 #define STATE_UBB_START 0x10 #define STATE_UBB_MIDDLE 0x20 #define STATE_UBB_END 0x40 #define STATE_TEX_SET 0x80 enum UBBTYPE {UBB_TYPE_IMG, UBB_TYPE_ITALICIZE, UBB_TYPE_UNDERLINE, UBB_TYPE_BOLD, UBB_TYPE_FLY, UBB_TYPE_RM, UBB_TYPE_FLASH, UBB_TYPE_CENTER, UBB_TYPE_EMAIL, UBB_TYPE_HTTPLINK, UBB_TYPE_QUOTE, UBB_TYPE_QUICKTIME, UBB_TYPE_SHOCKWAVE, UBB_TYPE_MOVE, UBB_TYPE_GLOW, UBB_TYPE_SHADOW, UBB_TYPE_FACE, UBB_TYPE_SOUND, UBB_TYPE_ATTACH }; enum ATTACHMENTTYPE { ATTACH_IMG, ATTACH_FLASH, ATTACH_OTHERS }; #define STATE_SET(s, b) ((s) |= (b)) #define STATE_CLR(s, b) ((s) &= ~(b)) #define STATE_ISSET(s, b) ((s) & (b)) #define STATE_ZERO(s) (s = 0) #define STYLE_SET_FG(s, c) (s = (s & ~0x07) | (c & 0x07)) #define STYLE_SET_BG(s, c) (s = (s & ~0x70) | ((c & 0x07) << 4)) #define STYLE_GET_FG(s) (s & 0x0F) #define STYLE_GET_BG(s) ((s & 0x70) >> 4) #define STYLE_CLR_FG(s) (s &= ~0x0F) #define STYLE_CLR_BG(s) (s &= ~0xF0) #define STYLE_ZERO(s) (s = 0) #define STYLE_SET(s, b) (s |= b) #define STYLE_CLR(s, b) (s &= ~b) #define STYLE_ISSET(s, b) (s & b) #define FONT_STYLE_UL 0x0100 #define FONT_STYLE_BLINK 0x0200 #define FONT_STYLE_ITALIC 0x0400 #define FONT_FG_BOLD 0x08 #define FONT_COLOR_BLACK 0x00 #define FONT_COLOR_RED 0x01 #define FONT_COLOR_GREEN 0x02 #define FONT_COLOR_YELLOW 0x03 #define FONT_COLOR_BULE 0x04 #define FONT_COLOR_MAGENTA 0x05 #define FONT_COLOR_CYAN 0x06 #define FONT_COLOR_WHITE 0x07 //#define FONT_STYLE_QUOTE FONT_STYLE_ITALIC #define FONT_STYLE_QUOTE 0x0000 #define FONT_COLOR_QUOTE FONT_COLOR_CYAN #define FONT_BG_SET 0x80 #endif /* __ANSI_H__ */
Java
using System; using Server.Misc; using Server.Network; using System.Collections; using Server.Items; using Server.Targeting; namespace Server.Mobiles { public class KhaldunZealot : BaseCreature { public override bool ClickTitle{ get{ return false; } } public override bool ShowFameTitle{ get{ return false; } } [Constructable] public KhaldunZealot(): base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Body = 0x190; Name = "Zealot of Khaldun"; Title = "the Knight"; Hue = 0; SetStr( 351, 400 ); SetDex( 151, 165 ); SetInt( 76, 100 ); SetHits( 448, 470 ); SetDamage( 15, 25 ); SetDamageType( ResistanceType.Physical, 75 ); SetDamageType( ResistanceType.Cold, 25 ); SetResistance( ResistanceType.Physical, 35, 45 ); SetResistance( ResistanceType.Fire, 25, 30 ); SetResistance( ResistanceType.Cold, 50, 60 ); SetResistance( ResistanceType.Poison, 25, 35 ); SetResistance( ResistanceType.Energy, 25, 35 ); SetSkill( SkillName.Wrestling, 70.1, 80.0 ); SetSkill( SkillName.Swords, 120.1, 130.0 ); SetSkill( SkillName.Anatomy, 120.1, 130.0 ); SetSkill( SkillName.MagicResist, 90.1, 100.0 ); SetSkill( SkillName.Tactics, 90.1, 100.0 ); Fame = 10000; Karma = -10000; VirtualArmor = 40; VikingSword weapon = new VikingSword(); weapon.Hue = 0x835; weapon.Movable = false; AddItem( weapon ); MetalShield shield = new MetalShield(); shield.Hue = 0x835; shield.Movable = false; AddItem( shield ); BoneHelm helm = new BoneHelm(); helm.Hue = 0x835; AddItem( helm ); BoneArms arms = new BoneArms(); arms.Hue = 0x835; AddItem( arms ); BoneGloves gloves = new BoneGloves(); gloves.Hue = 0x835; AddItem( gloves ); BoneChest tunic = new BoneChest(); tunic.Hue = 0x835; AddItem( tunic ); BoneLegs legs = new BoneLegs(); legs.Hue = 0x835; AddItem( legs ); AddItem( new Boots() ); } public override int GetIdleSound() { return 0x184; } public override int GetAngerSound() { return 0x286; } public override int GetDeathSound() { return 0x288; } public override int GetHurtSound() { return 0x19F; } public override bool AlwaysMurderer{ get{ return true; } } public override bool Unprovokable{ get{ return true; } } public override Poison PoisonImmune{ get{ return Poison.Deadly; } } public KhaldunZealot( Serial serial ) : base( serial ) { } public override bool OnBeforeDeath() { BoneKnight rm = new BoneKnight(); rm.Team = this.Team; rm.Combatant = this.Combatant; rm.NoKillAwards = true; if ( rm.Backpack == null ) { Backpack pack = new Backpack(); pack.Movable = false; rm.AddItem( pack ); } for ( int i = 0; i < 2; i++ ) { LootPack.FilthyRich.Generate( this, rm.Backpack, true, LootPack.GetLuckChanceForKiller( this ) ); LootPack.FilthyRich.Generate( this, rm.Backpack, false, LootPack.GetLuckChanceForKiller( this ) ); } Effects.PlaySound(this, Map, GetDeathSound()); Effects.SendLocationEffect( Location, Map, 0x3709, 30, 10, 0x835, 0 ); rm.MoveToWorld( Location, Map ); Delete(); return false; } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */reader.ReadInt(); } } }
Java
<?php /** * WordPress CRON API * * @package WordPress */ /** * Schedules a hook to run only once. * * Schedules a hook which will be executed once by the Wordpress actions core at * a time which you specify. The action will fire off when someone visits your * WordPress site, if the schedule time has passed. * * @since 2.1.0 * @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event * * @param int $timestamp Timestamp for when to run the event. * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. */ function wp_schedule_single_event( $timestamp, $hook, $args = array()) { // don't schedule a duplicate if there's already an identical event due in the next 10 minutes $next = wp_next_scheduled($hook, $args); if ( $next && $next <= $timestamp + 600 ) return; $crons = _get_cron_array(); $key = md5(serialize($args)); $crons[$timestamp][$hook][$key] = array( 'schedule' => false, 'args' => $args ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Schedule a periodic event. * * Schedules a hook which will be executed by the WordPress actions core on a * specific interval, specified by you. The action will trigger when someone * visits your WordPress site, if the scheduled time has passed. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. * @return bool|null False on failure, null when complete with scheduling event. */ function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); $key = md5(serialize($args)); if ( !isset( $schedules[$recurrence] ) ) return false; $crons[$timestamp][$hook][$key] = array( 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Reschedule a recurring event. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. * @return bool|null False on failure. Null when event is rescheduled. */ function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); $key = md5(serialize($args)); $interval = 0; // First we try to get it from the schedule if ( 0 == $interval ) $interval = $schedules[$recurrence]['interval']; // Now we try to get it from the saved interval in case the schedule disappears if ( 0 == $interval ) $interval = $crons[$timestamp][$hook][$key]['interval']; // Now we assume something is wrong and fail to schedule if ( 0 == $interval ) return false; while ( $timestamp < time() + 1 ) $timestamp += $interval; wp_schedule_event( $timestamp, $recurrence, $hook, $args ); } /** * Unschedule a previously scheduled cron job. * * The $timestamp and $hook parameters are required, so that the event can be * identified. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. */ function wp_unschedule_event( $timestamp, $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); unset( $crons[$timestamp][$hook][$key] ); if ( empty($crons[$timestamp][$hook]) ) unset( $crons[$timestamp][$hook] ); if ( empty($crons[$timestamp]) ) unset( $crons[$timestamp] ); _set_cron_array( $crons ); } /** * Unschedule all cron jobs attached to a specific hook. * * @since 2.1.0 * * @param callback $hook Function or method to call, when cron is run. * @param mixed $args,... Optional. Event arguments. */ function wp_clear_scheduled_hook( $hook ) { $args = array_slice( func_get_args(), 1 ); while ( $timestamp = wp_next_scheduled( $hook, $args ) ) wp_unschedule_event( $timestamp, $hook, $args ); } /** * Retrieve the next timestamp for a cron event. * * @since 2.1.0 * * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. * @return bool|int The UNIX timestamp of the next time the scheduled event will occur. */ function wp_next_scheduled( $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $timestamp; } return false; } /** * Send request to run cron through HTTP request that doesn't halt page loading. * * @since 2.1.0 * * @return null Cron could not be spawned, because it is not needed to run. */ function spawn_cron( $local_time ) { /* * do not even start the cron if local server timer has drifted * such as due to power failure, or misconfiguration */ $timer_accurate = check_server_timer( $local_time ); if ( !$timer_accurate ) return; //sanity check $crons = _get_cron_array(); if ( !is_array($crons) ) return; $keys = array_keys( $crons ); $timestamp = $keys[0]; if ( $timestamp > $local_time ) return; $cron_url = get_option( 'siteurl' ) . '/wp-cron.php?check=' . wp_hash('187425'); /* * multiple processes on multiple web servers can run this code concurrently * try to make this as atomic as possible by setting doing_cron switch */ $flag = get_option('doing_cron'); // clean up potential invalid value resulted from various system chaos if ( $flag != 0 ) { if ( $flag > $local_time + 10*60 || $flag < $local_time - 10*60 ) { update_option('doing_cron', 0); $flag = 0; } } //don't run if another process is currently running it if ( $flag > $local_time ) return; update_option( 'doing_cron', $local_time + 30 ); wp_remote_post($cron_url, array('timeout' => 0.01, 'blocking' => false)); } /** * Run scheduled callbacks or spawn cron for all scheduled events. * * @since 2.1.0 * * @return null When doesn't need to run Cron. */ function wp_cron() { // Prevent infinite loops caused by lack of wp-cron.php if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false ) return; $crons = _get_cron_array(); if ( !is_array($crons) ) return; $keys = array_keys( $crons ); if ( isset($keys[0]) && $keys[0] > time() ) return; $local_time = time(); $schedules = wp_get_schedules(); foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $local_time ) break; foreach ( (array) $cronhooks as $hook => $args ) { if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) ) continue; spawn_cron( $local_time ); break 2; } } } /** * Retrieve supported and filtered Cron recurrences. * * The supported recurrences are 'hourly' and 'daily'. A plugin may add more by * hooking into the 'cron_schedules' filter. The filter accepts an array of * arrays. The outer array has a key that is the name of the schedule or for * example 'weekly'. The value is an array with two keys, one is 'interval' and * the other is 'display'. * * The 'interval' is a number in seconds of when the cron job should run. So for * 'hourly', the time is 3600 or 60*60. For weekly, the value would be * 60*60*24*7 or 604800. The value of 'interval' would then be 604800. * * The 'display' is the description. For the 'weekly' key, the 'display' would * be <code>__('Once Weekly')</code>. * * For your plugin, you will be passed an array. you can easily add your * schedule by doing the following. * <code> * // filter parameter variable name is 'array' * $array['weekly'] = array( * 'interval' => 604800, * 'display' => __('Once Weekly') * ); * </code> * * @since 2.1.0 * * @return array */ function wp_get_schedules() { $schedules = array( 'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ), 'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ), 'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ), ); return array_merge( apply_filters( 'cron_schedules', array() ), $schedules ); } /** * Retrieve Cron schedule for hook with arguments. * * @since 2.1.0 * * @param callback $hook Function or method to call, when cron is run. * @param array $args Optional. Arguments to pass to the hook function. * @return string|bool False, if no schedule. Schedule on success. */ function wp_get_schedule($hook, $args = array()) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $cron[$hook][$key]['schedule']; } return false; } // // Private functions // /** * Retrieve cron info array option. * * @since 2.1.0 * @access private * * @return array CRON info array. */ function _get_cron_array() { $cron = get_option('cron'); if ( ! is_array($cron) ) return false; if ( !isset($cron['version']) ) $cron = _upgrade_cron_array($cron); unset($cron['version']); return $cron; } /** * Updates the CRON option with the new CRON array. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. */ function _set_cron_array($cron) { $cron['version'] = 2; update_option( 'cron', $cron ); } /** * Upgrade a Cron info array. * * This function upgrades the Cron info array to version 2. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. * @return array An upgraded Cron info array. */ function _upgrade_cron_array($cron) { if ( isset($cron['version']) && 2 == $cron['version']) return $cron; $new_cron = array(); foreach ( (array) $cron as $timestamp => $hooks) { foreach ( (array) $hooks as $hook => $args ) { $key = md5(serialize($args['args'])); $new_cron[$timestamp][$hook][$key] = $args; } } $new_cron['version'] = 2; update_option( 'cron', $new_cron ); return $new_cron; } // stub for checking server timer accuracy, using outside standard time sources function check_server_timer( $local_time ) { return true; } ?>
Java
#!/usr/bin/env python ## tumblrserv.py implements a Tumblr (http://www.tumblr.com) markup parsing ## engine and compatible webserver. ## ## Version: 0.2 final ## ## Copyright (C) 2009 Jeremy Herbert ## Contact mailto:jeremy@jeremyherbert.net ## ## 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 2 ## 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. import os, sys, ftplib, yaml, cherrypy, re, urllib2 from src.post_classes import * from src import json from src.constants import * from src.support import * from src.net import * from src.server import * post_types = ['Regular', 'Photo', 'Quote', 'Link', 'Conversation', 'Video', 'Audio', 'Conversation'] args_dict = { 'autoreload': 0, # Whether to add the meta refresh tag 'publish': False, # Whether to push the new theme data to tumblr 'data_source': DATA_LOCAL, # Whether to use local data in the theme } ######################################## # take the arguments and place them in a mutable list arguments = sys.argv # if the script has been run with the interpreter prefix, get rid of it if arguments[0] == 'python' or arguments[0] == 'ipython' \ or arguments[0] == 'python2.5': arguments.pop(0) # pop off the script name arguments.pop(0) # load the configuration file config_path = 'data/config.yml' if contains(arguments, '--config'): if os.path.exists(next_arg(arguments, '--config')): config_path = next_arg(arguments, '--config') config = get_config(config_path) # now we check if there are any data processing flags if contains(arguments, '--pull-data'): # call pull_data with the argument after the flag pull_data( next_arg(arguments, '--pull-data') ) if contains(arguments, '--theme'): if not os.path.exists("themes/" + next_arg(arguments, '--theme') + '.thtml'): err_exit("The theme file %s.thtml does not exist in the themes\ directory." % next_arg(arguments, '--theme')) config['defaults']['theme_name'] = next_arg(arguments, '--theme') if contains(arguments, '--publish'): if not has_keys(config['publishing_info'], \ ( 'url', 'username', 'password' )): err_exit('The configuration file is missing some critical publishing\ information. Please make sure you have specified your url, username and\ password.') publish_theme(config['publishing_info']['url'],\ config['publishing_info']['username'],\ config['publishing_info']['password'],\ get_markup('themes/%s.thtml' % config['defaults']['theme_name'])) if contains(arguments, '--do-nothing'): config['optimisations']['do_nothing'] = True # start the server up cherrypy.config.update('data/cherrypy.conf') cherrypy.quickstart(TumblrServ(config), '/')
Java
package pf::Switch::Motorola; =head1 NAME pf::Switch::Motorola =head1 SYNOPSIS The pf::Switch::Motorola module implements an object oriented interface to manage Motorola RF Switches (Wireless Controllers) =head1 STATUS Developed and tested on RFS7000 running OS release 4.3.0.0-059R, and RFS6000 running OS 5.2.0.0-069R. =over =item Supports =over =item Deauthentication with RADIUS Disconnect (RFC3576) =item Deauthentication with SNMP =item Roles-assignment through RADIUS =back =back =head1 BUGS AND LIMITATIONS =over =item Firmware 4.x support Deauthentication against firmware 4.x series is done using SNMP =item Firmware 5.x support Deauthentication against firmware 5.x series is done using RADIUS CoA. =item SNMPv3 SNMPv3 support is untested. =back =cut use strict; use warnings; use base ('pf::Switch'); use pf::accounting qw(node_accounting_current_sessionid); use pf::constants; use pf::config qw( $MAC $SSID ); use pf::util; =head1 SUBROUTINES =over =cut # CAPABILITIES # access technology supported sub supportsRoleBasedEnforcement { return $TRUE; } sub supportsWirelessDot1x { return $TRUE; } sub supportsWirelessMacAuth { return $TRUE; } # inline capabilities sub inlineCapabilities { return ($MAC,$SSID); } =item getVersion obtain image version information from switch =cut sub getVersion { my ($self) = @_; my $oid_sysDescr = '1.3.6.1.2.1.1.1.0'; my $logger = $self->logger; if ( !$self->connectRead() ) { return ''; } $logger->trace("SNMP get_request for sysDescr: $oid_sysDescr"); my $result = $self->{_sessionRead}->get_request( -varbindlist => [$oid_sysDescr] ); my $sysDescr = ( $result->{$oid_sysDescr} || '' ); # sysDescr sample output: # RFS7000 Wireless Switch, Version 4.3.0.0-059R MIB=01a # all non-whitespace characters grouped after the string Version if ( $sysDescr =~ / Version (\S+)/ ) { return $1; } else { $logger->warn("couldn't extract exact version information, returning SNMP System Description instead"); return $sysDescr; } } =item parseTrap Parsing SNMP Traps - WIDS stuff only, other types are discarded =cut sub parseTrap { my ( $self, $trapString ) = @_; my $trapHashRef; my $logger = $self->logger; # Handle WIPS Trap if ( $trapString =~ /BEGIN VARIABLEBINDINGS.*\.1\.3\.6\.1\.4\.1\.388\.50\.1\.2\.1\.4 = STRING: "Unsanctioned AP ([A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2})/){ $trapHashRef->{'trapType'} = 'wirelessIPS'; $trapHashRef->{'trapMac'} = clean_mac($1); } else { $logger->debug("trap currently not handled"); $trapHashRef->{'trapType'} = 'unknown'; } return $trapHashRef; } =item deauthenticateMacDefault De-authenticate a MAC address from wireless network (including 802.1x). New implementation using RADIUS Disconnect-Request. =cut sub deauthenticateMacDefault { my ( $self, $mac, $is_dot1x ) = @_; my $logger = $self->logger; if ( !$self->isProductionMode() ) { $logger->info("not in production mode... we won't perform deauthentication"); return 1; } if ($self->getVersion() =~ /^5/) { #Fetching the acct-session-id, mandatory for Motorola my $acctsessionid = node_accounting_current_sessionid($mac); $logger->debug("deauthenticate $mac using RADIUS Disconnect-Request deauth method"); return $self->radiusDisconnect( $mac, { 'Acct-Session-Id' => $acctsessionid } ); } else { $logger->debug("deauthenticate $mac using SNMP deauth method"); return $self->_deauthenticateMacSNMP($mac); } } =item _deauthenticateMacSNMP deauthenticate a MAC address from wireless network (including 802.1x) =cut sub _deauthenticateMacSNMP { my ($self, $mac) = @_; my $logger = $self->logger; my $oid_wsCcRfMuDisassociateNow = '1.3.6.1.4.1.388.14.3.2.1.12.3.1.19'; # from WS-CC-RF-MIB if ( !$self->isProductionMode() ) { $logger->info("not in production mode ... we won't write to wsCcRfMuDisassociateNow"); return 1; } # handles if deauth should be performed against controller or actual device. Returns sessionWrite hash key to use. my $performDeauthOn = $self->getDeauthSnmpConnectionKey(); if ( !defined($performDeauthOn) ) { return; } # append MAC to deauthenticate to oid to set $oid_wsCcRfMuDisassociateNow .= '.' . mac2oid($mac); $logger->info("deauthenticate mac $mac from controller: " . $self->{_ip}); $logger->trace("SNMP set_request for wsCcRfMuDisassociateNow: $oid_wsCcRfMuDisassociateNow"); my $result = $self->{$performDeauthOn}->set_request( -varbindlist => [ "$oid_wsCcRfMuDisassociateNow", Net::SNMP::INTEGER, $TRUE ] ); if (defined($result)) { $logger->debug("deauthenticatation successful"); return $TRUE; } else { $logger->warn("deauthenticatation failed with " . $self->{$performDeauthOn}->error()); return; } } =item returnRoleAttribute Motorola uses the following VSA for role assignment =cut sub returnRoleAttribute { my ($self) = @_; return 'Symbol-User-Group'; } =item deauthTechniques Return the reference to the deauth technique or the default deauth technique. =cut sub deauthTechniques { my ($self, $method) = @_; my $logger = $self->logger; my $default = $SNMP::SNMP; my %tech = ( $SNMP::SNMP => 'deauthenticateMacDefault', ); if (!defined($method) || !defined($tech{$method})) { $method = $default; } return $method,$tech{$method}; } =back =head1 AUTHOR Inverse inc. <info@inverse.ca> =head1 COPYRIGHT Copyright (C) 2005-2017 Inverse inc. =head1 LICENSE 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 2 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. =cut 1; # vim: set shiftwidth=4: # vim: set expandtab: # vim: set backspace=indent,eol,start:
Java
/* * Copyright 2006-2016 The MZmine 3 Development Team * * This file is part of MZmine 3. * * MZmine 3 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 of the * License, or (at your option) any later version. * * MZmine 3 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 MZmine 3; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package io.github.mzmine.util; import java.io.File; import java.util.List; import javax.annotation.Nonnull; import com.google.common.io.Files; /** * File name utilities */ public class FileNameUtil { public static @Nonnull String findCommonPrefix(@Nonnull List<File> fileNames) { if (fileNames.size() < 2) return ""; String firstName = fileNames.get(0).getName(); for (int prefixLen = 0; prefixLen < firstName.length(); prefixLen++) { char c = firstName.charAt(prefixLen); for (int i = 1; i < fileNames.size(); i++) { String ithName = fileNames.get(i).getName(); if (prefixLen >= ithName.length() || ithName.charAt(prefixLen) != c) { // Mismatch found return ithName.substring(0, prefixLen); } } } return firstName; } public static @Nonnull String findCommonSuffix(@Nonnull List<File> fileNames) { if (fileNames.isEmpty()) return ""; if (fileNames.size() == 1) { // Return file extension String ext = Files.getFileExtension(fileNames.get(0).getAbsolutePath()); return "." + ext; } String firstName = fileNames.get(0).getName(); for (int suffixLen = 0; suffixLen < firstName.length(); suffixLen++) { char c = firstName.charAt(firstName.length() - 1 - suffixLen); for (int i = 1; i < fileNames.size(); i++) { String ithName = fileNames.get(i).getName(); if (suffixLen >= ithName.length() || ithName.charAt(ithName.length() - 1 - suffixLen) != c) { // Mismatch found return ithName.substring(ithName.length() - suffixLen); } } } return firstName; } }
Java
/* PHYML : a program that computes maximum likelihood phylogenies from DNA or AA homologous sequences Copyright (C) Stephane Guindon. Oct 2003 onward All parts of the source except where indicated are distributed under the GNU public licence. See http://www.opensource.org for details. */ #include <config.h> #ifndef IO_H #define IO_H #include "utilities.h" t_tree *Read_Tree(char **s_tree); void R_rtree(char *s_tree_a,char *s_tree_d,t_node *a,t_tree *tree,int *n_int,int *n_ext); void Read_Branch_Label(char *s_d,char *s_a,t_edge *b); void Read_Branch_Length(char *s_d,char *s_a,t_tree *tree); void Read_Node_Name(t_node *d,char *s_tree_d,t_tree *tree); void Clean_Multifurcation(char **subtrees,int current_deg,int end_deg); char **Sub_Trees(char *tree,int *degree); int Next_Par(char *s,int pos); void Print_Tree(FILE *fp,t_tree *tree); char *Write_Tree(t_tree *tree,int custom); void R_wtree(t_node *pere,t_node *fils,int *available,char **s_tree,t_tree *tree); void R_wtree_Custom(t_node *pere,t_node *fils,int *available,char **s_tree,int *pos,t_tree *tree); void Detect_Align_File_Format(option *io); void Detect_Tree_File_Format(option *io); align **Get_Seq(option *io); void Get_Nexus_Data(FILE *fp,option *io); int Get_Token(FILE *fp,char *token); align **Get_Seq_Phylip(option *io); void Read_Ntax_Len_Phylip(FILE *fp,int *n_otu,int *n_tax); align **Read_Seq_Sequential(option *io); align **Read_Seq_Interleaved(option *io); int Read_One_Line_Seq(align ***data,int num_otu,FILE *in); t_tree *Read_Tree_File(option *io); char *Return_Tree_String_Phylip(FILE *fp_input_tree); t_tree *Read_Tree_File_Phylip(FILE *fp_input_tree); void Print_Site_Lk(t_tree *tree,FILE *fp); void Print_Seq(FILE *fp, align **data, int n_otu); void Print_CSeq(FILE *fp,int compressed,calign *cdata); void Print_CSeq_Select(FILE *fp,int compressed,calign *cdata,t_tree *tree); void Print_Dist(matrix *mat); void Print_Node(t_node *a,t_node *d,t_tree *tree); void Print_Model(t_mod *mod); void Print_Mat(matrix *mat); FILE *Openfile(char *filename,int mode); void Print_Fp_Out(FILE *fp_out,time_t t_beg,time_t t_end,t_tree *tree,option *io,int n_data_set,int num_tree, int add_citation); void Print_Fp_Out_Lines(FILE *fp_out,time_t t_beg,time_t t_end,t_tree *tree,option *io,int n_data_set); void Print_Freq(t_tree *tree); void Print_Settings(option *io); void Print_Banner(FILE *fp); void Print_Banner_Small(FILE *fp); void Print_Data_Set_Number(option *io,FILE *fp); void Print_Lk(t_tree *tree,char *string); void Print_Pars(t_tree *tree); void Print_Lk_And_Pars(t_tree *tree); void Read_Qmat(phydbl *daa,phydbl *pi,FILE *fp); void Print_Qmat_AA(phydbl *daa,phydbl *pi); void Print_Square_Matrix_Generic(int n,phydbl *mat); void Print_Diversity(FILE *fp,t_tree *tree); void Print_Diversity_Pre(t_node *a,t_node *d,t_edge *b,FILE *fp,t_tree *tree); t_tree *Read_User_Tree(calign *cdata,t_mod *mod,option *io); void Print_Time_Info(time_t t_beg,time_t t_end); void PhyML_Printf(char *format,...); void PhyML_Fprintf(FILE *fp,char *format,...); void Read_Clade_Priors(char *file_name,t_tree *tree); option *Get_Input(int argc,char **argv); void Print_Data_Structure(int final, FILE *fp, t_tree *root); int Set_Whichmodel(int select); void Print_Site(calign *cdata, int num, int n_otu, char *sep, int stepsize, FILE *fp); option *PhyML_XML(char *xml_filename); void Check_Taxa_Sets(t_tree *mixt_tree); void Make_Ratematrice_From_XML_Node(xml_node *instance, option *io, t_mod *mod); void Make_Efrq_From_XML_Node(xml_node *instance, option *io, t_mod *mod); void Make_Topology_From_XML_Node(xml_node *instance, option *io, t_mod *mod); void Make_RAS_From_XML_Node(xml_node *parent, t_mod *mod); void Post_Process_Data(option *io); int *Return_Int(int in); void Print_All_Edge_PMats(t_tree* tree); void Print_All_Edge_Likelihoods(t_tree* tree); void Print_Edge_Likelihoods(t_tree* tree, t_edge* b, bool scientific); void Print_Edge_PMats(t_tree* tree, t_edge* b); void Print_Tip_Partials(t_tree* tree, t_node* d); void Dump_Arr_D(phydbl* arr, int num); void Dump_Arr_S(short int* arr, int num); void Dump_Arr_I(int* arr, int num); void Print_Tree_Structure(t_tree* tree); void Print_Node_Brief(t_node *a, t_node *d, t_tree *tree, FILE *fp); void Generic_Exit(const char *file, int line, const char *function); #endif
Java
/* * computeOnsetFeatures.c * * Code generation for function 'computeOnsetFeatures' * * C source code generated on: Fri Apr 25 23:35:45 2014 * */ /* Include files */ #include "rt_nonfinite.h" #include "computeOnsetFeatures_export.h" /* Type Definitions */ #ifndef struct_emxArray__common #define struct_emxArray__common struct emxArray__common { void *data; int32_T *size; int32_T allocatedSize; int32_T numDimensions; boolean_T canFreeData; }; #endif /*struct_emxArray__common*/ #ifndef typedef_emxArray__common #define typedef_emxArray__common typedef struct emxArray__common emxArray__common; #endif /*typedef_emxArray__common*/ #ifndef struct_emxArray_int32_T #define struct_emxArray_int32_T struct emxArray_int32_T { int32_T *data; int32_T *size; int32_T allocatedSize; int32_T numDimensions; boolean_T canFreeData; }; #endif /*struct_emxArray_int32_T*/ #ifndef typedef_emxArray_int32_T #define typedef_emxArray_int32_T typedef struct emxArray_int32_T emxArray_int32_T; #endif /*typedef_emxArray_int32_T*/ /* Function Declarations */ static void ConstantPad(const emxArray_real_T *a, const real_T padSize[2], emxArray_real_T *b); static void b_eml_li_find(const boolean_T x[12], int32_T y_data[12], int32_T y_size[1]); static void b_eml_null_assignment(emxArray_boolean_T *x, const emxArray_real_T *idx); static void b_emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T numDimensions); static void b_emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions); static real_T b_std(const real_T varargin_1[17]); static void bsxfun(const real_T a[17], real_T b, real_T c[17]); static void c_eml_null_assignment(emxArray_real_T *x, const emxArray_real_T *idx); static real_T c_std(const real_T varargin_1[17]); static int32_T div_s32(int32_T numerator, int32_T denominator); static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y); static void eml_null_assignment(emxArray_boolean_T *x); static void eml_sort(const real_T x[17], real_T y[17], int32_T idx[17]); static void emxEnsureCapacity(emxArray__common *emxArray, int32_T oldNumel, int32_T elementSize); static void emxFree_boolean_T(emxArray_boolean_T **pEmxArray); static void emxFree_int32_T(emxArray_int32_T **pEmxArray); static void emxFree_real_T(emxArray_real_T **pEmxArray); static void emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T numDimensions); static void emxInit_int32_T(emxArray_int32_T **pEmxArray, int32_T numDimensions); static void emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions); static real_T featureSpectralCentroid(real_T S[17]); static real_T featureSpectralCrest(const real_T S[17]); static void filter(const emxArray_real_T *x, real_T zi, emxArray_real_T *y); static void filtfilt(const emxArray_real_T *x_in, emxArray_real_T *y_out); static void histogramFeatures(const real_T ioiHist[17], real_T features[12]); static void ioiHistogram(emxArray_boolean_T *onsets, const emxArray_real_T *T, real_T ioiHist[17]); static void onsetDetection(const emxArray_real_T *spec, emxArray_boolean_T *onsets, emxArray_real_T *flux); static void onsetFlux(const emxArray_real_T *S, emxArray_real_T *flux); static void padarray(const emxArray_real_T *varargin_1, emxArray_real_T *b); static void rdivide(const emxArray_real_T *x, real_T y, emxArray_real_T *z); static real_T rt_powd_snf(real_T u0, real_T u1); /* Function Definitions */ static void ConstantPad(const emxArray_real_T *a, const real_T padSize[2], emxArray_real_T *b) { real_T sizeB[2]; int32_T cdiff; uint32_T varargin_1[2]; int32_T ndbl; emxArray_real_T *idxB; emxArray_int32_T *r7; emxArray_real_T *r8; emxArray_real_T *r9; int32_T k; int32_T absb; int32_T apnd; int32_T i4; emxArray_boolean_T *x; real_T idxB1; real_T idxB2; int32_T b_sizeB[2]; int32_T outsize[2]; for (cdiff = 0; cdiff < 2; cdiff++) { sizeB[cdiff] = 0.0; } for (cdiff = 0; cdiff < 2; cdiff++) { varargin_1[cdiff] = (uint32_T)a->size[cdiff]; } ndbl = (int32_T)varargin_1[0]; if ((int32_T)varargin_1[1] > (int32_T)varargin_1[0]) { ndbl = (int32_T)varargin_1[1]; } emxInit_real_T(&idxB, 2); cdiff = idxB->size[0] * idxB->size[1]; idxB->size[0] = ndbl; idxB->size[1] = 2; emxEnsureCapacity((emxArray__common *)idxB, cdiff, (int32_T)sizeof(real_T)); ndbl <<= 1; for (cdiff = 0; cdiff < ndbl; cdiff++) { idxB->data[cdiff] = 0.0; } emxInit_int32_T(&r7, 1); emxInit_real_T(&r8, 2); emxInit_real_T(&r9, 2); for (k = 0; k < 2; k++) { sizeB[k] = (real_T)a->size[k] + 2.0 * padSize[k]; if (1 > a->size[k]) { ndbl = 0; } else { ndbl = a->size[k]; } cdiff = r7->size[0]; r7->size[0] = ndbl; emxEnsureCapacity((emxArray__common *)r7, cdiff, (int32_T)sizeof(int32_T)); for (cdiff = 0; cdiff < ndbl; cdiff++) { r7->data[cdiff] = cdiff; } if (a->size[k] < 1) { absb = -1; apnd = 0; } else { ndbl = (int32_T)floor(((real_T)a->size[k] - 1.0) + 0.5); apnd = ndbl + 1; cdiff = (ndbl - a->size[k]) + 1; absb = a->size[k]; if (1 > absb) { i4 = 1; } else { i4 = absb; } if (fabs(cdiff) < 4.4408920985006262E-16 * (real_T)i4) { ndbl++; apnd = a->size[k]; } else if (cdiff > 0) { apnd = ndbl; } else { ndbl++; } absb = ndbl - 1; } cdiff = r8->size[0] * r8->size[1]; r8->size[0] = 1; r8->size[1] = absb + 1; emxEnsureCapacity((emxArray__common *)r8, cdiff, (int32_T)sizeof(real_T)); if (absb + 1 > 0) { r8->data[0] = 1.0; if (absb + 1 > 1) { r8->data[absb] = apnd; ndbl = absb / 2; for (cdiff = 1; cdiff < ndbl; cdiff++) { r8->data[cdiff] = 1.0 + (real_T)cdiff; r8->data[absb - cdiff] = apnd - cdiff; } if (ndbl << 1 == absb) { r8->data[ndbl] = (1.0 + (real_T)apnd) / 2.0; } else { r8->data[ndbl] = 1.0 + (real_T)ndbl; r8->data[ndbl + 1] = apnd - ndbl; } } } cdiff = r9->size[0] * r9->size[1]; r9->size[0] = 1; r9->size[1] = r8->size[1]; emxEnsureCapacity((emxArray__common *)r9, cdiff, (int32_T)sizeof(real_T)); ndbl = r8->size[1]; for (cdiff = 0; cdiff < ndbl; cdiff++) { r9->data[r9->size[0] * cdiff] = r8->data[r8->size[0] * cdiff] + padSize[k]; } ndbl = r7->size[0]; for (cdiff = 0; cdiff < ndbl; cdiff++) { idxB->data[r7->data[cdiff] + idxB->size[0] * k] = r9->data[cdiff]; } } emxFree_real_T(&r9); emxFree_real_T(&r8); emxFree_int32_T(&r7); b_emxInit_boolean_T(&x, 1); ndbl = idxB->size[0]; cdiff = x->size[0]; x->size[0] = ndbl; emxEnsureCapacity((emxArray__common *)x, cdiff, (int32_T)sizeof(boolean_T)); for (cdiff = 0; cdiff < ndbl; cdiff++) { x->data[cdiff] = (idxB->data[cdiff] != 0.0); } if (x->size[0] == 0) { idxB1 = 0.0; } else { idxB1 = x->data[0]; for (k = 2; k <= x->size[0]; k++) { idxB1 += (real_T)x->data[k - 1]; } } ndbl = idxB->size[0]; cdiff = x->size[0]; x->size[0] = ndbl; emxEnsureCapacity((emxArray__common *)x, cdiff, (int32_T)sizeof(boolean_T)); for (cdiff = 0; cdiff < ndbl; cdiff++) { x->data[cdiff] = (idxB->data[cdiff + idxB->size[0]] != 0.0); } if (x->size[0] == 0) { idxB2 = 0.0; } else { idxB2 = x->data[0]; for (k = 2; k <= x->size[0]; k++) { idxB2 += (real_T)x->data[k - 1]; } } emxFree_boolean_T(&x); b_sizeB[0] = (int32_T)sizeB[0]; b_sizeB[1] = (int32_T)sizeB[1]; for (cdiff = 0; cdiff < 2; cdiff++) { outsize[cdiff] = b_sizeB[cdiff]; } cdiff = b->size[0] * b->size[1]; b->size[0] = outsize[0]; emxEnsureCapacity((emxArray__common *)b, cdiff, (int32_T)sizeof(real_T)); cdiff = b->size[0] * b->size[1]; b->size[1] = outsize[1]; emxEnsureCapacity((emxArray__common *)b, cdiff, (int32_T)sizeof(real_T)); ndbl = outsize[0] * outsize[1]; for (cdiff = 0; cdiff < ndbl; cdiff++) { b->data[cdiff] = 0.0; } for (ndbl = 0; ndbl < (int32_T)idxB1; ndbl++) { for (cdiff = 0; cdiff < (int32_T)idxB2; cdiff++) { b->data[((int32_T)idxB->data[(int32_T)(1.0 + (real_T)ndbl) - 1] + b->size [0] * ((int32_T)idxB->data[((int32_T)(1.0 + (real_T)cdiff) + idxB->size[0]) - 1] - 1)) - 1] = a->data[((int32_T)(1.0 + (real_T)ndbl) + a->size[0] * ((int32_T)(1.0 + (real_T)cdiff) - 1)) - 1]; } } emxFree_real_T(&idxB); } static void b_eml_li_find(const boolean_T x[12], int32_T y_data[12], int32_T y_size[1]) { int32_T k; int32_T i; k = 0; for (i = 0; i < 12; i++) { if (x[i]) { k++; } } y_size[0] = k; k = 0; for (i = 0; i < 12; i++) { if (x[i]) { y_data[k] = i + 1; k++; } } } static void b_eml_null_assignment(emxArray_boolean_T *x, const emxArray_real_T *idx) { int32_T nxin; int32_T k; emxArray_int32_T *r13; emxArray_boolean_T *b_x; emxArray_boolean_T *c_x; int32_T nxout; int32_T i6; int32_T k0; emxArray_boolean_T *b; nxin = x->size[0] * x->size[1]; if (idx->size[1] == 1) { for (k = (int32_T)idx->data[0]; k < nxin; k++) { x->data[k - 1] = x->data[k]; } emxInit_int32_T(&r13, 1); emxInit_boolean_T(&b_x, 2); b_emxInit_boolean_T(&c_x, 1); if ((x->size[0] != 1) && (x->size[1] == 1)) { if (1 > nxin - 1) { nxout = 0; } else { nxout = nxin - 1; } i6 = c_x->size[0]; c_x->size[0] = nxout; emxEnsureCapacity((emxArray__common *)c_x, i6, (int32_T)sizeof(boolean_T)); for (i6 = 0; i6 < nxout; i6++) { c_x->data[i6] = x->data[i6]; } i6 = x->size[0] * x->size[1]; x->size[0] = nxout; x->size[1] = 1; emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T)); i6 = 0; while (i6 <= 0) { for (i6 = 0; i6 < nxout; i6++) { x->data[i6] = c_x->data[i6]; } i6 = 1; } } else { if (1 > nxin - 1) { nxout = 0; } else { nxout = nxin - 1; } i6 = r13->size[0]; r13->size[0] = nxout; emxEnsureCapacity((emxArray__common *)r13, i6, (int32_T)sizeof(int32_T)); for (i6 = 0; i6 < nxout; i6++) { r13->data[i6] = 1 + i6; } nxout = r13->size[0]; i6 = b_x->size[0] * b_x->size[1]; b_x->size[0] = 1; b_x->size[1] = nxout; emxEnsureCapacity((emxArray__common *)b_x, i6, (int32_T)sizeof(boolean_T)); for (i6 = 0; i6 < nxout; i6++) { k = 0; while (k <= 0) { b_x->data[b_x->size[0] * i6] = x->data[r13->data[i6] - 1]; k = 1; } } i6 = x->size[0] * x->size[1]; x->size[0] = b_x->size[0]; x->size[1] = b_x->size[1]; emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T)); nxout = b_x->size[1]; for (i6 = 0; i6 < nxout; i6++) { k0 = b_x->size[0]; for (k = 0; k < k0; k++) { x->data[k + x->size[0] * i6] = b_x->data[k + b_x->size[0] * i6]; } } } emxFree_boolean_T(&c_x); emxFree_boolean_T(&b_x); emxFree_int32_T(&r13); } else { emxInit_boolean_T(&b, 2); i6 = b->size[0] * b->size[1]; b->size[0] = 1; b->size[1] = nxin; emxEnsureCapacity((emxArray__common *)b, i6, (int32_T)sizeof(boolean_T)); for (i6 = 0; i6 < nxin; i6++) { b->data[i6] = FALSE; } for (k = 1; k <= idx->size[1]; k++) { b->data[(int32_T)idx->data[k - 1] - 1] = TRUE; } nxout = 0; for (k = 1; k <= b->size[1]; k++) { nxout += b->data[k - 1]; } nxout = nxin - nxout; k0 = -1; for (k = 1; k <= nxin; k++) { if ((k > b->size[1]) || (!b->data[k - 1])) { k0++; x->data[k0] = x->data[k - 1]; } } emxFree_boolean_T(&b); emxInit_int32_T(&r13, 1); emxInit_boolean_T(&b_x, 2); b_emxInit_boolean_T(&c_x, 1); if ((x->size[0] != 1) && (x->size[1] == 1)) { if (1 > nxout) { nxout = 0; } i6 = c_x->size[0]; c_x->size[0] = nxout; emxEnsureCapacity((emxArray__common *)c_x, i6, (int32_T)sizeof(boolean_T)); for (i6 = 0; i6 < nxout; i6++) { c_x->data[i6] = x->data[i6]; } i6 = x->size[0] * x->size[1]; x->size[0] = nxout; x->size[1] = 1; emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T)); i6 = 0; while (i6 <= 0) { for (i6 = 0; i6 < nxout; i6++) { x->data[i6] = c_x->data[i6]; } i6 = 1; } } else { if (1 > nxout) { nxout = 0; } i6 = r13->size[0]; r13->size[0] = nxout; emxEnsureCapacity((emxArray__common *)r13, i6, (int32_T)sizeof(int32_T)); for (i6 = 0; i6 < nxout; i6++) { r13->data[i6] = 1 + i6; } nxout = r13->size[0]; i6 = b_x->size[0] * b_x->size[1]; b_x->size[0] = 1; b_x->size[1] = nxout; emxEnsureCapacity((emxArray__common *)b_x, i6, (int32_T)sizeof(boolean_T)); for (i6 = 0; i6 < nxout; i6++) { k = 0; while (k <= 0) { b_x->data[b_x->size[0] * i6] = x->data[r13->data[i6] - 1]; k = 1; } } i6 = x->size[0] * x->size[1]; x->size[0] = b_x->size[0]; x->size[1] = b_x->size[1]; emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T)); nxout = b_x->size[1]; for (i6 = 0; i6 < nxout; i6++) { k0 = b_x->size[0]; for (k = 0; k < k0; k++) { x->data[k + x->size[0] * i6] = b_x->data[k + b_x->size[0] * i6]; } } } emxFree_boolean_T(&c_x); emxFree_boolean_T(&b_x); emxFree_int32_T(&r13); } } static void b_emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T numDimensions) { emxArray_boolean_T *emxArray; int32_T i; *pEmxArray = (emxArray_boolean_T *)malloc(sizeof(emxArray_boolean_T)); emxArray = *pEmxArray; emxArray->data = (boolean_T *)NULL; emxArray->numDimensions = numDimensions; emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions)); emxArray->allocatedSize = 0; emxArray->canFreeData = TRUE; for (i = 0; i < numDimensions; i++) { emxArray->size[i] = 0; } } static void b_emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions) { emxArray_real_T *emxArray; int32_T i; *pEmxArray = (emxArray_real_T *)malloc(sizeof(emxArray_real_T)); emxArray = *pEmxArray; emxArray->data = (real_T *)NULL; emxArray->numDimensions = numDimensions; emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions)); emxArray->allocatedSize = 0; emxArray->canFreeData = TRUE; for (i = 0; i < numDimensions; i++) { emxArray->size[i] = 0; } } static real_T b_std(const real_T varargin_1[17]) { real_T y; int32_T ix; real_T xbar; int32_T k; real_T r; ix = 0; xbar = varargin_1[0]; for (k = 0; k < 16; k++) { ix++; xbar += varargin_1[ix]; } xbar /= 17.0; ix = 0; r = varargin_1[0] - xbar; y = r * r; for (k = 0; k < 16; k++) { ix++; r = varargin_1[ix] - xbar; y += r * r; } y /= 16.0; return sqrt(y); } static void bsxfun(const real_T a[17], real_T b, real_T c[17]) { int32_T k; for (k = 0; k < 17; k++) { c[k] = a[k] - b; } } static void c_eml_null_assignment(emxArray_real_T *x, const emxArray_real_T *idx) { int32_T nxin; int32_T k; emxArray_int32_T *r14; emxArray_real_T *b_x; emxArray_real_T *c_x; int32_T nxout; int32_T i7; int32_T k0; emxArray_boolean_T *b; nxin = x->size[0] * x->size[1]; if (idx->size[1] == 1) { for (k = (int32_T)idx->data[0]; k < nxin; k++) { x->data[k - 1] = x->data[k]; } emxInit_int32_T(&r14, 1); emxInit_real_T(&b_x, 2); b_emxInit_real_T(&c_x, 1); if ((x->size[0] != 1) && (x->size[1] == 1)) { if (1 > nxin - 1) { nxout = 0; } else { nxout = nxin - 1; } i7 = c_x->size[0]; c_x->size[0] = nxout; emxEnsureCapacity((emxArray__common *)c_x, i7, (int32_T)sizeof(real_T)); for (i7 = 0; i7 < nxout; i7++) { c_x->data[i7] = x->data[i7]; } i7 = x->size[0] * x->size[1]; x->size[0] = nxout; x->size[1] = 1; emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T)); i7 = 0; while (i7 <= 0) { for (i7 = 0; i7 < nxout; i7++) { x->data[i7] = c_x->data[i7]; } i7 = 1; } } else { if (1 > nxin - 1) { nxout = 0; } else { nxout = nxin - 1; } i7 = r14->size[0]; r14->size[0] = nxout; emxEnsureCapacity((emxArray__common *)r14, i7, (int32_T)sizeof(int32_T)); for (i7 = 0; i7 < nxout; i7++) { r14->data[i7] = 1 + i7; } nxout = r14->size[0]; i7 = b_x->size[0] * b_x->size[1]; b_x->size[0] = 1; b_x->size[1] = nxout; emxEnsureCapacity((emxArray__common *)b_x, i7, (int32_T)sizeof(real_T)); for (i7 = 0; i7 < nxout; i7++) { k = 0; while (k <= 0) { b_x->data[b_x->size[0] * i7] = x->data[r14->data[i7] - 1]; k = 1; } } i7 = x->size[0] * x->size[1]; x->size[0] = b_x->size[0]; x->size[1] = b_x->size[1]; emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T)); nxout = b_x->size[1]; for (i7 = 0; i7 < nxout; i7++) { k0 = b_x->size[0]; for (k = 0; k < k0; k++) { x->data[k + x->size[0] * i7] = b_x->data[k + b_x->size[0] * i7]; } } } emxFree_real_T(&c_x); emxFree_real_T(&b_x); emxFree_int32_T(&r14); } else { emxInit_boolean_T(&b, 2); i7 = b->size[0] * b->size[1]; b->size[0] = 1; b->size[1] = nxin; emxEnsureCapacity((emxArray__common *)b, i7, (int32_T)sizeof(boolean_T)); for (i7 = 0; i7 < nxin; i7++) { b->data[i7] = FALSE; } for (k = 1; k <= idx->size[1]; k++) { b->data[(int32_T)idx->data[k - 1] - 1] = TRUE; } nxout = 0; for (k = 1; k <= b->size[1]; k++) { nxout += b->data[k - 1]; } nxout = nxin - nxout; k0 = -1; for (k = 1; k <= nxin; k++) { if ((k > b->size[1]) || (!b->data[k - 1])) { k0++; x->data[k0] = x->data[k - 1]; } } emxFree_boolean_T(&b); emxInit_int32_T(&r14, 1); emxInit_real_T(&b_x, 2); b_emxInit_real_T(&c_x, 1); if ((x->size[0] != 1) && (x->size[1] == 1)) { if (1 > nxout) { nxout = 0; } i7 = c_x->size[0]; c_x->size[0] = nxout; emxEnsureCapacity((emxArray__common *)c_x, i7, (int32_T)sizeof(real_T)); for (i7 = 0; i7 < nxout; i7++) { c_x->data[i7] = x->data[i7]; } i7 = x->size[0] * x->size[1]; x->size[0] = nxout; x->size[1] = 1; emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T)); i7 = 0; while (i7 <= 0) { for (i7 = 0; i7 < nxout; i7++) { x->data[i7] = c_x->data[i7]; } i7 = 1; } } else { if (1 > nxout) { nxout = 0; } i7 = r14->size[0]; r14->size[0] = nxout; emxEnsureCapacity((emxArray__common *)r14, i7, (int32_T)sizeof(int32_T)); for (i7 = 0; i7 < nxout; i7++) { r14->data[i7] = 1 + i7; } nxout = r14->size[0]; i7 = b_x->size[0] * b_x->size[1]; b_x->size[0] = 1; b_x->size[1] = nxout; emxEnsureCapacity((emxArray__common *)b_x, i7, (int32_T)sizeof(real_T)); for (i7 = 0; i7 < nxout; i7++) { k = 0; while (k <= 0) { b_x->data[b_x->size[0] * i7] = x->data[r14->data[i7] - 1]; k = 1; } } i7 = x->size[0] * x->size[1]; x->size[0] = b_x->size[0]; x->size[1] = b_x->size[1]; emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T)); nxout = b_x->size[1]; for (i7 = 0; i7 < nxout; i7++) { k0 = b_x->size[0]; for (k = 0; k < k0; k++) { x->data[k + x->size[0] * i7] = b_x->data[k + b_x->size[0] * i7]; } } } emxFree_real_T(&c_x); emxFree_real_T(&b_x); emxFree_int32_T(&r14); } } static real_T c_std(const real_T varargin_1[17]) { real_T y; int32_T ix; real_T xbar; int32_T k; real_T r; ix = 0; xbar = varargin_1[0]; for (k = 0; k < 16; k++) { ix++; xbar += varargin_1[ix]; } xbar /= 17.0; ix = 0; r = varargin_1[0] - xbar; y = r * r; for (k = 0; k < 16; k++) { ix++; r = varargin_1[ix] - xbar; y += r * r; } y /= 17.0; return sqrt(y); } static int32_T div_s32(int32_T numerator, int32_T denominator) { int32_T quotient; uint32_T absNumerator; uint32_T absDenominator; int32_T quotientNeedsNegation; if (denominator == 0) { if (numerator >= 0) { quotient = MAX_int32_T; } else { quotient = MIN_int32_T; } } else { if (numerator >= 0) { absNumerator = (uint32_T)numerator; } else { absNumerator = (uint32_T)-numerator; } if (denominator >= 0) { absDenominator = (uint32_T)denominator; } else { absDenominator = (uint32_T)-denominator; } quotientNeedsNegation = ((numerator < 0) != (denominator < 0)); absNumerator /= absDenominator; if ((uint32_T)quotientNeedsNegation) { quotient = -(int32_T)absNumerator; } else { quotient = (int32_T)absNumerator; } } return quotient; } static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y) { int32_T n; int32_T k; int32_T i; int32_T j; n = x->size[0] * x->size[1]; k = 0; for (i = 1; i <= n; i++) { if (x->data[i - 1]) { k++; } } j = y->size[0]; y->size[0] = k; emxEnsureCapacity((emxArray__common *)y, j, (int32_T)sizeof(int32_T)); j = 0; for (i = 1; i <= n; i++) { if (x->data[i - 1]) { y->data[j] = i; j++; } } } static void eml_null_assignment(emxArray_boolean_T *x) { emxArray_boolean_T *b; int32_T nxin; int32_T i5; int32_T k; int32_T nxout; int32_T k0; emxArray_int32_T *r12; emxArray_boolean_T *b_x; emxArray_boolean_T *c_x; emxInit_boolean_T(&b, 2); nxin = x->size[0] * x->size[1]; i5 = b->size[0] * b->size[1]; b->size[0] = 1; b->size[1] = nxin; emxEnsureCapacity((emxArray__common *)b, i5, (int32_T)sizeof(boolean_T)); for (i5 = 0; i5 < nxin; i5++) { b->data[i5] = FALSE; } for (k = 0; k < 2; k++) { b->data[k] = TRUE; } nxout = 0; for (k = 1; k <= b->size[1]; k++) { nxout += b->data[k - 1]; } nxout = nxin - nxout; k0 = -1; for (k = 1; k <= nxin; k++) { if ((k > b->size[1]) || (!b->data[k - 1])) { k0++; x->data[k0] = x->data[k - 1]; } } emxFree_boolean_T(&b); emxInit_int32_T(&r12, 1); emxInit_boolean_T(&b_x, 2); b_emxInit_boolean_T(&c_x, 1); if ((x->size[0] != 1) && (x->size[1] == 1)) { if (1 > nxout) { nxout = 0; } i5 = c_x->size[0]; c_x->size[0] = nxout; emxEnsureCapacity((emxArray__common *)c_x, i5, (int32_T)sizeof(boolean_T)); for (i5 = 0; i5 < nxout; i5++) { c_x->data[i5] = x->data[i5]; } i5 = x->size[0] * x->size[1]; x->size[0] = nxout; x->size[1] = 1; emxEnsureCapacity((emxArray__common *)x, i5, (int32_T)sizeof(boolean_T)); i5 = 0; while (i5 <= 0) { for (i5 = 0; i5 < nxout; i5++) { x->data[i5] = c_x->data[i5]; } i5 = 1; } } else { if (1 > nxout) { nxout = 0; } i5 = r12->size[0]; r12->size[0] = nxout; emxEnsureCapacity((emxArray__common *)r12, i5, (int32_T)sizeof(int32_T)); for (i5 = 0; i5 < nxout; i5++) { r12->data[i5] = 1 + i5; } nxout = r12->size[0]; i5 = b_x->size[0] * b_x->size[1]; b_x->size[0] = 1; b_x->size[1] = nxout; emxEnsureCapacity((emxArray__common *)b_x, i5, (int32_T)sizeof(boolean_T)); for (i5 = 0; i5 < nxout; i5++) { k = 0; while (k <= 0) { b_x->data[b_x->size[0] * i5] = x->data[r12->data[i5] - 1]; k = 1; } } i5 = x->size[0] * x->size[1]; x->size[0] = b_x->size[0]; x->size[1] = b_x->size[1]; emxEnsureCapacity((emxArray__common *)x, i5, (int32_T)sizeof(boolean_T)); nxout = b_x->size[1]; for (i5 = 0; i5 < nxout; i5++) { k0 = b_x->size[0]; for (k = 0; k < k0; k++) { x->data[k + x->size[0] * i5] = b_x->data[k + b_x->size[0] * i5]; } } } emxFree_boolean_T(&c_x); emxFree_boolean_T(&b_x); emxFree_int32_T(&r12); } static void eml_sort(const real_T x[17], real_T y[17], int32_T idx[17]) { int32_T k; boolean_T p; int8_T idx0[17]; int32_T i; int32_T i2; int32_T j; int32_T pEnd; int32_T b_p; int32_T q; int32_T qEnd; int32_T kEnd; for (k = 0; k < 17; k++) { idx[k] = k + 1; } for (k = 0; k < 15; k += 2) { if ((x[k] <= x[k + 1]) || rtIsNaN(x[k + 1])) { p = TRUE; } else { p = FALSE; } if (p) { } else { idx[k] = k + 2; idx[k + 1] = k + 1; } } for (i = 0; i < 17; i++) { idx0[i] = 1; } i = 2; while (i < 17) { i2 = i << 1; j = 1; for (pEnd = 1 + i; pEnd < 18; pEnd = qEnd + i) { b_p = j; q = pEnd - 1; qEnd = j + i2; if (qEnd > 18) { qEnd = 18; } k = 0; kEnd = qEnd - j; while (k + 1 <= kEnd) { if ((x[idx[b_p - 1] - 1] <= x[idx[q] - 1]) || rtIsNaN(x[idx[q] - 1])) { p = TRUE; } else { p = FALSE; } if (p) { idx0[k] = (int8_T)idx[b_p - 1]; b_p++; if (b_p == pEnd) { while (q + 1 < qEnd) { k++; idx0[k] = (int8_T)idx[q]; q++; } } } else { idx0[k] = (int8_T)idx[q]; q++; if (q + 1 == qEnd) { while (b_p < pEnd) { k++; idx0[k] = (int8_T)idx[b_p - 1]; b_p++; } } } k++; } for (k = 0; k + 1 <= kEnd; k++) { idx[(j + k) - 1] = idx0[k]; } j = qEnd; } i = i2; } for (k = 0; k < 17; k++) { y[k] = x[idx[k] - 1]; } } static void emxEnsureCapacity(emxArray__common *emxArray, int32_T oldNumel, int32_T elementSize) { int32_T newNumel; int32_T i; void *newData; newNumel = 1; for (i = 0; i < emxArray->numDimensions; i++) { newNumel *= emxArray->size[i]; } if (newNumel > emxArray->allocatedSize) { i = emxArray->allocatedSize; if (i < 16) { i = 16; } while (i < newNumel) { i <<= 1; } newData = calloc((uint32_T)i, (uint32_T)elementSize); if (emxArray->data != NULL) { memcpy(newData, emxArray->data, (uint32_T)(elementSize * oldNumel)); if (emxArray->canFreeData) { free(emxArray->data); } } emxArray->data = newData; emxArray->allocatedSize = i; emxArray->canFreeData = TRUE; } } static void emxFree_boolean_T(emxArray_boolean_T **pEmxArray) { if (*pEmxArray != (emxArray_boolean_T *)NULL) { if ((*pEmxArray)->canFreeData) { free((void *)(*pEmxArray)->data); } free((void *)(*pEmxArray)->size); free((void *)*pEmxArray); *pEmxArray = (emxArray_boolean_T *)NULL; } } static void emxFree_int32_T(emxArray_int32_T **pEmxArray) { if (*pEmxArray != (emxArray_int32_T *)NULL) { if ((*pEmxArray)->canFreeData) { free((void *)(*pEmxArray)->data); } free((void *)(*pEmxArray)->size); free((void *)*pEmxArray); *pEmxArray = (emxArray_int32_T *)NULL; } } static void emxFree_real_T(emxArray_real_T **pEmxArray) { if (*pEmxArray != (emxArray_real_T *)NULL) { if ((*pEmxArray)->canFreeData) { free((void *)(*pEmxArray)->data); } free((void *)(*pEmxArray)->size); free((void *)*pEmxArray); *pEmxArray = (emxArray_real_T *)NULL; } } static void emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T numDimensions) { emxArray_boolean_T *emxArray; int32_T i; *pEmxArray = (emxArray_boolean_T *)malloc(sizeof(emxArray_boolean_T)); emxArray = *pEmxArray; emxArray->data = (boolean_T *)NULL; emxArray->numDimensions = numDimensions; emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions)); emxArray->allocatedSize = 0; emxArray->canFreeData = TRUE; for (i = 0; i < numDimensions; i++) { emxArray->size[i] = 0; } } static void emxInit_int32_T(emxArray_int32_T **pEmxArray, int32_T numDimensions) { emxArray_int32_T *emxArray; int32_T i; *pEmxArray = (emxArray_int32_T *)malloc(sizeof(emxArray_int32_T)); emxArray = *pEmxArray; emxArray->data = (int32_T *)NULL; emxArray->numDimensions = numDimensions; emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions)); emxArray->allocatedSize = 0; emxArray->canFreeData = TRUE; for (i = 0; i < numDimensions; i++) { emxArray->size[i] = 0; } } static void emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions) { emxArray_real_T *emxArray; int32_T i; *pEmxArray = (emxArray_real_T *)malloc(sizeof(emxArray_real_T)); emxArray = *pEmxArray; emxArray->data = (real_T *)NULL; emxArray->numDimensions = numDimensions; emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions)); emxArray->allocatedSize = 0; emxArray->canFreeData = TRUE; for (i = 0; i < numDimensions; i++) { emxArray->size[i] = 0; } } static real_T featureSpectralCentroid(real_T S[17]) { real_T y; int32_T i; real_T b_y; /* FEATURESPECTRALCENTROID Computes spectral centroid feature */ /* It is the mass center of the spectrum */ /* [r,c] = size(S); */ /* feature = sum(repmat((1:r)',1,c).* S)./sum(S); */ y = 0.0; for (i = 0; i < 17; i++) { b_y = S[i] * S[i]; y += (((real_T)i + 1.0) - 1.0) * b_y; S[i] = b_y; } b_y = S[0]; for (i = 0; i < 16; i++) { b_y += S[i + 1]; } return y / b_y; } static real_T featureSpectralCrest(const real_T S[17]) { int32_T ixstart; real_T mtmp; int32_T ix; boolean_T exitg1; real_T y; /* FEATURESPECTRALCREST Computes spectral crest */ /* It is a rough measure of tonality */ ixstart = 1; mtmp = S[0]; if (rtIsNaN(S[0])) { ix = 2; exitg1 = FALSE; while ((exitg1 == FALSE) && (ix < 18)) { ixstart = ix; if (!rtIsNaN(S[ix - 1])) { mtmp = S[ix - 1]; exitg1 = TRUE; } else { ix++; } } } if (ixstart < 17) { while (ixstart + 1 < 18) { if (S[ixstart] > mtmp) { mtmp = S[ixstart]; } ixstart++; } } y = S[0]; for (ixstart = 0; ixstart < 16; ixstart++) { y += S[ixstart + 1]; } return mtmp / y; } static void filter(const emxArray_real_T *x, real_T zi, emxArray_real_T *y) { uint32_T unnamed_idx_0; int32_T j; real_T dbuffer[2]; int32_T k; real_T b_dbuffer; unnamed_idx_0 = (uint32_T)x->size[0]; j = y->size[0]; y->size[0] = (int32_T)unnamed_idx_0; emxEnsureCapacity((emxArray__common *)y, j, (int32_T)sizeof(real_T)); dbuffer[1] = zi; for (j = 0; j + 1 <= x->size[0]; j++) { dbuffer[0] = dbuffer[1]; dbuffer[1] = 0.0; for (k = 0; k < 2; k++) { b_dbuffer = dbuffer[k] + x->data[j] * 0.33333333333333331; dbuffer[k] = b_dbuffer; } y->data[j] = dbuffer[0]; } } static void filtfilt(const emxArray_real_T *x_in, emxArray_real_T *y_out) { emxArray_real_T *x; int32_T i2; int32_T loop_ub; emxArray_real_T *y; real_T xtmp; real_T b_y; int32_T md2; emxArray_real_T *c_y; int32_T m; emxArray_real_T *d_y; emxArray_int32_T *r6; b_emxInit_real_T(&x, 1); if (x_in->size[0] == 1) { i2 = x->size[0]; x->size[0] = 1; emxEnsureCapacity((emxArray__common *)x, i2, (int32_T)sizeof(real_T)); x->data[0] = x_in->data[0]; } else { i2 = x->size[0]; x->size[0] = x_in->size[0]; emxEnsureCapacity((emxArray__common *)x, i2, (int32_T)sizeof(real_T)); loop_ub = x_in->size[0]; for (i2 = 0; i2 < loop_ub; i2++) { x->data[i2] = x_in->data[i2]; } } if (x->size[0] == 0) { i2 = y_out->size[0] * y_out->size[1]; y_out->size[0] = 0; y_out->size[1] = 0; emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T)); } else { b_emxInit_real_T(&y, 1); xtmp = 2.0 * x->data[0]; b_y = 2.0 * x->data[x->size[0] - 1]; md2 = x->size[0] - 1; i2 = y->size[0]; y->size[0] = 6 + x->size[0]; emxEnsureCapacity((emxArray__common *)y, i2, (int32_T)sizeof(real_T)); for (i2 = 0; i2 < 3; i2++) { y->data[i2] = xtmp - x->data[3 - i2]; } loop_ub = x->size[0]; for (i2 = 0; i2 < loop_ub; i2++) { y->data[i2 + 3] = x->data[i2]; } for (i2 = 0; i2 < 3; i2++) { y->data[(i2 + x->size[0]) + 3] = b_y - x->data[(md2 - i2) - 1]; } b_emxInit_real_T(&c_y, 1); i2 = c_y->size[0]; c_y->size[0] = y->size[0]; emxEnsureCapacity((emxArray__common *)c_y, i2, (int32_T)sizeof(real_T)); loop_ub = y->size[0]; for (i2 = 0; i2 < loop_ub; i2++) { c_y->data[i2] = y->data[i2]; } xtmp = y->data[0]; filter(c_y, 0.33333333333333331 * xtmp, y); m = y->size[0]; i2 = y->size[0]; md2 = i2 / 2; loop_ub = 1; emxFree_real_T(&c_y); while (loop_ub <= md2) { xtmp = y->data[loop_ub - 1]; y->data[loop_ub - 1] = y->data[m - loop_ub]; y->data[m - loop_ub] = xtmp; loop_ub++; } b_emxInit_real_T(&d_y, 1); i2 = d_y->size[0]; d_y->size[0] = y->size[0]; emxEnsureCapacity((emxArray__common *)d_y, i2, (int32_T)sizeof(real_T)); loop_ub = y->size[0]; for (i2 = 0; i2 < loop_ub; i2++) { d_y->data[i2] = y->data[i2]; } xtmp = y->data[0]; filter(d_y, 0.33333333333333331 * xtmp, y); m = y->size[0]; i2 = y->size[0]; md2 = i2 / 2; loop_ub = 1; emxFree_real_T(&d_y); while (loop_ub <= md2) { xtmp = y->data[loop_ub - 1]; y->data[loop_ub - 1] = y->data[m - loop_ub]; y->data[m - loop_ub] = xtmp; loop_ub++; } if (x_in->size[0] == 1) { emxInit_int32_T(&r6, 1); loop_ub = (int32_T)((real_T)x->size[0] + 3.0) - 4; i2 = r6->size[0]; r6->size[0] = loop_ub + 1; emxEnsureCapacity((emxArray__common *)r6, i2, (int32_T)sizeof(int32_T)); for (i2 = 0; i2 <= loop_ub; i2++) { r6->data[i2] = 4 + i2; } i2 = y_out->size[0] * y_out->size[1]; y_out->size[0] = 1; emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T)); md2 = r6->size[0]; i2 = y_out->size[0] * y_out->size[1]; y_out->size[1] = md2; emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T)); loop_ub = r6->size[0]; for (i2 = 0; i2 < loop_ub; i2++) { y_out->data[i2] = y->data[r6->data[i2] - 1]; } emxFree_int32_T(&r6); } else { emxInit_int32_T(&r6, 1); loop_ub = (int32_T)((real_T)x->size[0] + 3.0) - 3; i2 = y_out->size[0] * y_out->size[1]; y_out->size[0] = loop_ub; y_out->size[1] = 1; emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T)); md2 = (int32_T)((real_T)x->size[0] + 3.0) - 4; i2 = r6->size[0]; r6->size[0] = md2 + 1; emxEnsureCapacity((emxArray__common *)r6, i2, (int32_T)sizeof(int32_T)); for (i2 = 0; i2 <= md2; i2++) { r6->data[i2] = 4 + i2; } for (i2 = 0; i2 < loop_ub; i2++) { y_out->data[i2] = y->data[r6->data[i2] - 1]; } emxFree_int32_T(&r6); } emxFree_real_T(&y); } emxFree_real_T(&x); } static void histogramFeatures(const real_T ioiHist[17], real_T features[12]) { int32_T iidx[17]; real_T k[17]; int32_T ind[17]; boolean_T S[17]; int32_T cindx; real_T xlast; int32_T b_k; real_T b_ioiHist[17]; real_T sigma; real_T b_S[17]; real_T b[17]; int32_T ix; boolean_T x; int8_T S_size[2]; int8_T outsz[2]; int32_T loop_ub; int32_T iindx_data[1]; int32_T b_ix; int32_T indx_data[1]; /* UNTITLED Summary of this function goes here */ /* Detailed explanation goes here */ /* features(1) = mean(ioiHist); */ features[0] = b_std(ioiHist); eml_sort(ioiHist, k, iidx); features[1] = k[16] / k[15]; for (cindx = 0; cindx < 17; cindx++) { ind[cindx] = iidx[cindx]; S[cindx] = (ioiHist[cindx] == 0.0); } features[2] = (real_T)ind[16] / (real_T)ind[15]; xlast = S[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += (real_T)S[b_k + 1]; } features[3] = xlast / 17.0; for (cindx = 0; cindx < 17; cindx++) { b_ioiHist[cindx] = ioiHist[cindx]; /* FEATURESPECTRALDECREASE Computes the Spectral Decrease */ /* A measure of steepness of spectral envelope over frequency */ k[cindx] = cindx; } features[4] = featureSpectralCentroid(b_ioiHist); features[5] = featureSpectralCrest(ioiHist); k[0] = 1.0; xlast = 0.0; for (cindx = 0; cindx < 17; cindx++) { /* compute slope */ xlast += 1.0 / k[cindx] * (ioiHist[cindx] - ioiHist[0]); } sigma = ioiHist[1]; for (b_k = 0; b_k < 15; b_k++) { sigma += ioiHist[b_k + 2]; } features[6] = xlast / sigma; /* FEATURESPECTRALKURTOSIS Computes the Spectral Kurtosis */ /* It is a measure of gaussianity of a spectrum */ sigma = c_std(ioiHist); /* Subtracting means */ xlast = ioiHist[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += ioiHist[b_k + 1]; } bsxfun(ioiHist, xlast / 17.0, b_S); for (b_k = 0; b_k < 17; b_k++) { k[b_k] = rt_powd_snf(b_S[b_k], 4.0) / (rt_powd_snf(sigma, 4.0) * 17.0); } sigma = k[0]; for (b_k = 0; b_k < 16; b_k++) { sigma += k[b_k + 1]; } features[7] = sigma; /* FEATURESPECTRALROLLOFF Computes Spectral Rolloff */ /* Finds frequency bin where cumsum reaches 0.85 of magnitude */ /* compute rolloff */ xlast = ioiHist[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += ioiHist[b_k + 1]; } sigma = 0.85 * xlast; /* Find indices where cumulative sum is greater */ memcpy(&b[0], &ioiHist[0], 17U * sizeof(real_T)); ix = 0; xlast = ioiHist[0]; for (b_k = 0; b_k < 16; b_k++) { ix++; xlast += b[ix]; b[ix] = xlast; } for (b_k = 0; b_k < 17; b_k++) { S[b_k] = (b[b_k] >= sigma); } /* Find the maximum value */ xlast = S[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += (real_T)S[b_k + 1]; } x = (xlast > 0.0); b_k = 0; if (x) { b_k = 1; } S_size[0] = 17; S_size[1] = (int8_T)b_k; for (cindx = 0; cindx < 2; cindx++) { outsz[cindx] = S_size[cindx]; } loop_ub = outsz[1]; for (cindx = 0; cindx < loop_ub; cindx++) { iindx_data[cindx] = 1; } ix = -16; cindx = 1; while (cindx <= b_k) { ix += 17; x = S[(ix - 1) % 17]; loop_ub = 1; cindx = 1; if (ix < ix + 16) { for (b_ix = ix; b_ix + 1 <= ix + 16; b_ix++) { cindx++; if (S[b_ix % 17] > x) { x = S[b_ix % 17]; loop_ub = cindx; } } } iindx_data[0] = loop_ub; cindx = 2; } loop_ub = outsz[1]; for (cindx = 0; cindx < loop_ub; cindx++) { indx_data[cindx] = iindx_data[cindx]; } features[8] = indx_data[0]; /* FEATURESPECTRALSKEWNESS Compute spectral skewness */ /* A measure of symmettricity of pdf */ sigma = c_std(ioiHist); /* Subtracting means */ xlast = ioiHist[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += ioiHist[b_k + 1]; } bsxfun(ioiHist, xlast / 17.0, b_S); for (b_k = 0; b_k < 17; b_k++) { k[b_k] = rt_powd_snf(b_S[b_k], 3.0) / (rt_powd_snf(sigma, 3.0) * 17.0); } sigma = k[0]; for (b_k = 0; b_k < 16; b_k++) { sigma += k[b_k + 1]; } features[9] = sigma; /* FUNCTIONSPECTRALSLOPE Computes the spectral slope */ /* */ /* compute index vector */ /* compute slope */ xlast = ioiHist[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += ioiHist[b_k + 1]; } bsxfun(ioiHist, xlast / 17.0, b_S); xlast = 0.0; sigma = 0.0; for (b_k = 0; b_k < 17; b_k++) { xlast += (-8.5 + (((real_T)b_k + 1.0) - 1.0)) * b_S[b_k]; sigma += (-8.5 + (((real_T)b_k + 1.0) - 1.0)) * (-8.5 + (((real_T)b_k + 1.0) - 1.0)); b_ioiHist[b_k] = ioiHist[b_k]; k[b_k] = b_k; b_S[b_k] = ioiHist[b_k] * ioiHist[b_k]; } features[10] = xlast / sigma; /* FEATURESPECTRALSPREAD Computes spectral spread */ /* Concentration of energy around spectral centroid */ bsxfun(k, featureSpectralCentroid(b_ioiHist), b); for (b_k = 0; b_k < 17; b_k++) { k[b_k] = b[b_k] * b[b_k] * b_S[b_k]; } xlast = k[0]; sigma = b_S[0]; for (b_k = 0; b_k < 16; b_k++) { xlast += k[b_k + 1]; sigma += b_S[b_k + 1]; } features[11] = sqrt(xlast / sigma); } static void ioiHistogram(emxArray_boolean_T *onsets, const emxArray_real_T *T, real_T ioiHist[17]) { emxArray_real_T *tOnset; emxArray_int32_T *r10; int32_T high_i; int32_T ixLead; emxArray_real_T *ioi; emxArray_real_T *b_y1; int32_T iyLead; real_T work_data_idx_0; real_T tmp1; real_T tmp2; int32_T sz[2]; real_T meanIOI_data[1]; int32_T meanIOI_size[2]; int32_T k; emxArray_real_T *r11; emxArray_real_T b_meanIOI_data; int32_T d; real_T stdIOI_data[1]; boolean_T goodInd_data[1]; real_T histEdges[17]; int32_T exitg1; b_emxInit_real_T(&tOnset, 1); emxInit_int32_T(&r10, 1); /* UNTITLED2 Summary of this function goes here */ /* Detailed explanation goes here */ /* Setting the first one as true */ onsets->data[0] = TRUE; /* onsetInd = onsets; */ eml_li_find(onsets, r10); high_i = tOnset->size[0]; tOnset->size[0] = r10->size[0]; emxEnsureCapacity((emxArray__common *)tOnset, high_i, (int32_T)sizeof(real_T)); ixLead = r10->size[0]; for (high_i = 0; high_i < ixLead; high_i++) { tOnset->data[high_i] = T->data[r10->data[high_i] - 1]; } emxFree_int32_T(&r10); emxInit_real_T(&ioi, 2); if (tOnset->size[0] == 0) { high_i = ioi->size[0] * ioi->size[1]; ioi->size[0] = 0; ioi->size[1] = 1; emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T)); } else { ixLead = tOnset->size[0] - 1; if (ixLead <= 1) { } else { ixLead = 1; } if (ixLead < 1) { high_i = ioi->size[0] * ioi->size[1]; ioi->size[0] = 0; ioi->size[1] = 0; emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T)); } else { b_emxInit_real_T(&b_y1, 1); high_i = b_y1->size[0]; b_y1->size[0] = tOnset->size[0] - 1; emxEnsureCapacity((emxArray__common *)b_y1, high_i, (int32_T)sizeof(real_T)); ixLead = 1; iyLead = 0; work_data_idx_0 = tOnset->data[0]; for (high_i = 2; high_i <= tOnset->size[0]; high_i++) { tmp1 = tOnset->data[ixLead]; tmp2 = work_data_idx_0; work_data_idx_0 = tmp1; tmp1 -= tmp2; ixLead++; b_y1->data[iyLead] = tmp1; iyLead++; } ixLead = b_y1->size[0]; high_i = ioi->size[0] * ioi->size[1]; ioi->size[0] = ixLead; emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T)); high_i = ioi->size[0] * ioi->size[1]; ioi->size[1] = 1; emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T)); ixLead = b_y1->size[0]; for (high_i = 0; high_i < ixLead; high_i++) { ioi->data[high_i] = b_y1->data[high_i]; } emxFree_real_T(&b_y1); } } emxFree_real_T(&tOnset); for (high_i = 0; high_i < 2; high_i++) { sz[high_i] = ioi->size[high_i]; } meanIOI_size[0] = 1; meanIOI_size[1] = sz[1]; if ((ioi->size[0] == 0) || (ioi->size[1] == 0)) { meanIOI_size[0] = 1; meanIOI_size[1] = sz[1]; ixLead = sz[1]; for (high_i = 0; high_i < ixLead; high_i++) { meanIOI_data[high_i] = 0.0; } } else { iyLead = -1; work_data_idx_0 = ioi->data[0]; for (k = 2; k <= ioi->size[0]; k++) { iyLead++; work_data_idx_0 += ioi->data[iyLead + 1]; } meanIOI_data[0] = work_data_idx_0; } emxInit_real_T(&r11, 2); b_meanIOI_data.data = (real_T *)&meanIOI_data; b_meanIOI_data.size = (int32_T *)&meanIOI_size; b_meanIOI_data.allocatedSize = 1; b_meanIOI_data.numDimensions = 2; b_meanIOI_data.canFreeData = FALSE; rdivide(&b_meanIOI_data, ioi->size[0], r11); meanIOI_size[0] = 1; meanIOI_size[1] = r11->size[1]; ixLead = r11->size[0] * r11->size[1]; for (high_i = 0; high_i < ixLead; high_i++) { meanIOI_data[high_i] = r11->data[high_i]; } emxFree_real_T(&r11); if (ioi->size[0] > 1) { d = ioi->size[0] - 1; } else { d = ioi->size[0]; } for (high_i = 0; high_i < 2; high_i++) { sz[high_i] = ioi->size[high_i]; } iyLead = 0; ixLead = 1; while (ixLead <= ioi->size[1]) { if ((ioi->size[0] == 0) || (ioi->size[1] == 0)) { work_data_idx_0 = rtNaN; } else { ixLead = iyLead; tmp1 = ioi->data[iyLead]; for (k = 0; k <= ioi->size[0] - 2; k++) { ixLead++; tmp1 += ioi->data[ixLead]; } tmp1 /= (real_T)ioi->size[0]; ixLead = iyLead; tmp2 = ioi->data[iyLead] - tmp1; work_data_idx_0 = tmp2 * tmp2; for (k = 0; k <= ioi->size[0] - 2; k++) { ixLead++; tmp2 = ioi->data[ixLead] - tmp1; work_data_idx_0 += tmp2 * tmp2; } work_data_idx_0 /= (real_T)d; } stdIOI_data[0] = work_data_idx_0; iyLead += ioi->size[0]; ixLead = 2; } k = 0; while (k <= sz[1] - 1) { stdIOI_data[0] = sqrt(stdIOI_data[0]); k = 1; } iyLead = ioi->size[1]; ixLead = ioi->size[0] * ioi->size[1]; for (high_i = 0; high_i < ixLead; high_i++) { goodInd_data[high_i] = ((ioi->data[high_i] > meanIOI_data[high_i] - 2.0 * stdIOI_data[high_i]) && (ioi->data[high_i] < meanIOI_data[high_i] + 2.0 * stdIOI_data[high_i])); } k = 0; ixLead = 1; while (ixLead <= iyLead) { if (goodInd_data[0]) { k++; } ixLead = 2; } /* Avoiding code export bug */ /* ioi(ioi>upperThresh) = []; */ /* ioi(ioi<lowerThresh) = []; */ /* nBins = 16; */ for (high_i = 0; high_i < 17; high_i++) { histEdges[high_i] = 0.125 * (real_T)high_i; ioiHist[high_i] = 0.0; } histEdges[16] = rtInf; high_i = 0; do { exitg1 = 0; if (high_i < 16) { if (histEdges[1 + high_i] < histEdges[high_i]) { for (high_i = 0; high_i < 17; high_i++) { ioiHist[high_i] = rtNaN; } exitg1 = 1; } else { high_i++; } } else { ixLead = 0; while (ixLead <= k - 1) { ixLead = 0; if (!rtIsNaN(ioi->data[0])) { if ((ioi->data[0] >= 0.0) && (ioi->data[0] < rtInf)) { ixLead = 1; iyLead = 2; high_i = 17; while (high_i > iyLead) { d = (ixLead + high_i) >> 1; if (ioi->data[0] >= histEdges[d - 1]) { ixLead = d; iyLead = d + 1; } else { high_i = d; } } } if (ioi->data[0] == rtInf) { ixLead = 17; } } if (ixLead > 0) { ioiHist[ixLead - 1]++; } ixLead = 1; } exitg1 = 1; } } while (exitg1 == 0); emxFree_real_T(&ioi); work_data_idx_0 = ioiHist[0]; for (k = 0; k < 16; k++) { work_data_idx_0 += ioiHist[k + 1]; } for (high_i = 0; high_i < 17; high_i++) { ioiHist[high_i] /= work_data_idx_0; } } static void onsetDetection(const emxArray_real_T *spec, emxArray_boolean_T *onsets, emxArray_real_T *flux) { emxArray_real_T *b_flux; int32_T ixstart; real_T mtmp; int32_T k0; boolean_T exitg1; int32_T i0; emxArray_real_T *flux1; int32_T varargin_1[2]; int32_T i; boolean_T x[7]; int32_T k; emxArray_real_T *r0; int32_T nxin; emxArray_real_T *r1; emxArray_real_T *mask2; emxArray_boolean_T *b; emxArray_int32_T *r2; emxArray_real_T *b_mask2; emxArray_real_T *c_mask2; emxArray_real_T *r3; int32_T vstride; int32_T npages; int32_T dim; int32_T j; int32_T ia; b_emxInit_real_T(&b_flux, 1); /* UNTITLED2 Summary of this function goes here */ /* Detailed explanation goes here */ onsetFlux(spec, b_flux); /* Normalizing */ ixstart = 1; mtmp = b_flux->data[0]; if (b_flux->size[0] > 1) { if (rtIsNaN(b_flux->data[0])) { k0 = 2; exitg1 = FALSE; while ((exitg1 == FALSE) && (k0 <= b_flux->size[0])) { ixstart = k0; if (!rtIsNaN(b_flux->data[k0 - 1])) { mtmp = b_flux->data[k0 - 1]; exitg1 = TRUE; } else { k0++; } } } if (ixstart < b_flux->size[0]) { while (ixstart + 1 <= b_flux->size[0]) { if (b_flux->data[ixstart] > mtmp) { mtmp = b_flux->data[ixstart]; } ixstart++; } } } i0 = b_flux->size[0]; emxEnsureCapacity((emxArray__common *)b_flux, i0, (int32_T)sizeof(real_T)); ixstart = b_flux->size[0]; for (i0 = 0; i0 < ixstart; i0++) { b_flux->data[i0] /= mtmp; } emxInit_real_T(&flux1, 2); /* Smoothing */ /* h=fdesign.lowpass('N,F3dB',12,0.15); */ /* d1 = design(h,'elliptic'); */ /* flux = filtfilt(d1.sosMatrix,d1.ScaleValues,flux); */ filtfilt(b_flux, flux); /* h = 1/4*ones(4,1); */ /* flux = filter(h,1,flux); */ /* Peak picking */ /* w = 2; % Size of window to find local maxima */ padarray(flux, flux1); emxFree_real_T(&b_flux); for (i0 = 0; i0 < 2; i0++) { varargin_1[i0] = flux1->size[i0]; } i0 = onsets->size[0] * onsets->size[1]; onsets->size[0] = varargin_1[0]; emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T)); i0 = onsets->size[0] * onsets->size[1]; onsets->size[1] = varargin_1[1]; emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T)); ixstart = varargin_1[0] * varargin_1[1]; for (i0 = 0; i0 < ixstart; i0++) { onsets->data[i0] = FALSE; } if ((0 == flux1->size[0]) || (0 == flux1->size[1])) { ixstart = 0; } else if (flux1->size[0] > flux1->size[1]) { ixstart = flux1->size[0]; } else { ixstart = flux1->size[1]; } for (i = 3; i - 3 <= ixstart - 7; i++) { mtmp = flux1->data[i]; for (i0 = 0; i0 < 7; i0++) { x[i0] = (mtmp >= flux1->data[(i0 + i) - 3]); } mtmp = x[0]; for (k = 0; k < 6; k++) { mtmp += (real_T)x[k + 1]; } if (mtmp == 7.0) { onsets->data[i] = TRUE; } } b_emxInit_real_T(&r0, 1); /* Remove m elements at the start and end */ eml_null_assignment(onsets); mtmp = (real_T)(onsets->size[0] * onsets->size[1]) - 3.0; i0 = onsets->size[0] * onsets->size[1]; nxin = r0->size[0]; r0->size[0] = (int32_T)((real_T)i0 - mtmp) + 1; emxEnsureCapacity((emxArray__common *)r0, nxin, (int32_T)sizeof(real_T)); ixstart = (int32_T)((real_T)i0 - mtmp); for (i0 = 0; i0 <= ixstart; i0++) { r0->data[i0] = mtmp + (real_T)i0; } emxInit_real_T(&r1, 2); i0 = r1->size[0] * r1->size[1]; r1->size[0] = 1; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T)); ixstart = r0->size[0]; i0 = r1->size[0] * r1->size[1]; r1->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T)); ixstart = r0->size[0]; for (i0 = 0; i0 < ixstart; i0++) { r1->data[i0] = r0->data[i0]; } emxFree_real_T(&r0); b_eml_null_assignment(onsets, r1); /* Perform second thresholding operation */ /* m = 1; % Multiplier so mean is calculated over a larger range before peak */ /* delta = 0.01; % Threshold above local mean */ padarray(flux, flux1); for (i0 = 0; i0 < 2; i0++) { varargin_1[i0] = flux1->size[i0]; } emxInit_real_T(&mask2, 2); i0 = mask2->size[0] * mask2->size[1]; mask2->size[0] = varargin_1[0]; emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T)); i0 = mask2->size[0] * mask2->size[1]; mask2->size[1] = varargin_1[1]; emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T)); ixstart = varargin_1[0] * varargin_1[1]; for (i0 = 0; i0 < ixstart; i0++) { mask2->data[i0] = 0.0; } if ((0 == flux1->size[0]) || (0 == flux1->size[1])) { ixstart = 0; } else if (flux1->size[0] > flux1->size[1]) { ixstart = flux1->size[0]; } else { ixstart = flux1->size[1]; } for (i = 3; i - 3 <= ixstart - 7; i++) { /* flux = onsetDetection(denoisedSpec); */ mtmp = flux1->data[-3 + i]; for (k = 0; k < 6; k++) { mtmp += flux1->data[(k + i) - 2]; } if (flux1->data[i] >= mtmp / 7.0 + 0.01) { mask2->data[i] = 1.0; } } emxFree_real_T(&flux1); emxInit_boolean_T(&b, 2); /* Remove mw elements at the start and end */ nxin = mask2->size[0] * mask2->size[1]; i0 = b->size[0] * b->size[1]; b->size[0] = 1; b->size[1] = nxin; emxEnsureCapacity((emxArray__common *)b, i0, (int32_T)sizeof(boolean_T)); for (i0 = 0; i0 < nxin; i0++) { b->data[i0] = FALSE; } for (k = 0; k < 2; k++) { b->data[k] = TRUE; } ixstart = 0; for (k = 1; k <= b->size[1]; k++) { ixstart += b->data[k - 1]; } ixstart = nxin - ixstart; k0 = -1; for (k = 1; k <= nxin; k++) { if ((k > b->size[1]) || (!b->data[k - 1])) { k0++; mask2->data[k0] = mask2->data[k - 1]; } } emxInit_int32_T(&r2, 1); emxInit_real_T(&b_mask2, 2); b_emxInit_real_T(&c_mask2, 1); if ((mask2->size[0] != 1) && (mask2->size[1] == 1)) { if (1 > ixstart) { ixstart = 0; } i0 = c_mask2->size[0]; c_mask2->size[0] = ixstart; emxEnsureCapacity((emxArray__common *)c_mask2, i0, (int32_T)sizeof(real_T)); for (i0 = 0; i0 < ixstart; i0++) { c_mask2->data[i0] = mask2->data[i0]; } i0 = mask2->size[0] * mask2->size[1]; mask2->size[0] = ixstart; mask2->size[1] = 1; emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T)); i0 = 0; while (i0 <= 0) { for (i0 = 0; i0 < ixstart; i0++) { mask2->data[i0] = c_mask2->data[i0]; } i0 = 1; } } else { if (1 > ixstart) { ixstart = 0; } i0 = r2->size[0]; r2->size[0] = ixstart; emxEnsureCapacity((emxArray__common *)r2, i0, (int32_T)sizeof(int32_T)); for (i0 = 0; i0 < ixstart; i0++) { r2->data[i0] = 1 + i0; } ixstart = r2->size[0]; i0 = b_mask2->size[0] * b_mask2->size[1]; b_mask2->size[0] = 1; b_mask2->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)b_mask2, i0, (int32_T)sizeof(real_T)); for (i0 = 0; i0 < ixstart; i0++) { nxin = 0; while (nxin <= 0) { b_mask2->data[b_mask2->size[0] * i0] = mask2->data[r2->data[i0] - 1]; nxin = 1; } } i0 = mask2->size[0] * mask2->size[1]; mask2->size[0] = b_mask2->size[0]; mask2->size[1] = b_mask2->size[1]; emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T)); ixstart = b_mask2->size[1]; for (i0 = 0; i0 < ixstart; i0++) { k0 = b_mask2->size[0]; for (nxin = 0; nxin < k0; nxin++) { mask2->data[nxin + mask2->size[0] * i0] = b_mask2->data[nxin + b_mask2->size[0] * i0]; } } } emxFree_real_T(&c_mask2); emxFree_real_T(&b_mask2); emxFree_int32_T(&r2); b_emxInit_real_T(&r3, 1); mtmp = (real_T)(mask2->size[0] * mask2->size[1]) - 3.0; i0 = mask2->size[0] * mask2->size[1]; nxin = r3->size[0]; r3->size[0] = (int32_T)((real_T)i0 - mtmp) + 1; emxEnsureCapacity((emxArray__common *)r3, nxin, (int32_T)sizeof(real_T)); ixstart = (int32_T)((real_T)i0 - mtmp); for (i0 = 0; i0 <= ixstart; i0++) { r3->data[i0] = mtmp + (real_T)i0; } i0 = r1->size[0] * r1->size[1]; r1->size[0] = 1; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T)); ixstart = r3->size[0]; i0 = r1->size[0] * r1->size[1]; r1->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T)); ixstart = r3->size[0]; for (i0 = 0; i0 < ixstart; i0++) { r1->data[i0] = r3->data[i0]; } emxFree_real_T(&r3); c_eml_null_assignment(mask2, r1); i0 = onsets->size[0] * onsets->size[1]; emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T)); ixstart = onsets->size[0]; k0 = onsets->size[1]; ixstart *= k0; emxFree_real_T(&r1); for (i0 = 0; i0 < ixstart; i0++) { onsets->data[i0] = (onsets->data[i0] && (mask2->data[i0] != 0.0)); } emxFree_real_T(&mask2); onsets->data[0] = FALSE; if ((onsets->size[0] == 0) || (onsets->size[1] == 0) || ((onsets->size[0] == 1) && (onsets->size[1] == 1))) { } else { for (i0 = 0; i0 < 2; i0++) { varargin_1[i0] = onsets->size[i0]; } ixstart = varargin_1[0]; if (varargin_1[1] > varargin_1[0]) { ixstart = varargin_1[1]; } i0 = b->size[0] * b->size[1]; b->size[0] = 1; b->size[1] = ixstart; emxEnsureCapacity((emxArray__common *)b, i0, (int32_T)sizeof(boolean_T)); vstride = 1; npages = onsets->size[0] * onsets->size[1]; for (dim = 0; dim < 2; dim++) { i0 = onsets->size[dim]; npages = div_s32(npages, onsets->size[dim]); if (onsets->size[dim] > 1) { ixstart = (int32_T)fabs(-1.0 + (((real_T)dim + 1.0) - 1.0)); if (ixstart - div_s32(ixstart, onsets->size[dim]) * onsets->size[dim] > 0) { ixstart = (onsets->size[dim] - 1) * vstride; k0 = 0; for (i = 1; i <= npages; i++) { nxin = k0; k0 += ixstart; for (j = 1; j <= vstride; j++) { nxin++; k0++; ia = nxin; for (k = 1; k <= i0; k++) { b->data[k - 1] = onsets->data[ia - 1]; ia += vstride; } ia = nxin - 1; for (k = 2; k <= i0; k++) { onsets->data[ia] = b->data[k - 1]; ia += vstride; } onsets->data[ia] = b->data[0]; } } } } vstride *= i0; } } emxFree_boolean_T(&b); /* Some post processing to remove sequences of onsets */ /* Changing to non vectorized versions for export */ if ((0 == onsets->size[0]) || (0 == onsets->size[1])) { ixstart = 0; } else if (onsets->size[0] > onsets->size[1]) { ixstart = onsets->size[0]; } else { ixstart = onsets->size[1]; } for (i = 0; i <= ixstart - 3; i++) { if ((onsets->data[i] == 1) && (onsets->data[i + 1] == 1)) { if (onsets->data[i + 2] == 1) { onsets->data[i + 2] = FALSE; } onsets->data[i + 1] = FALSE; } } /* tripleInd = strfind(onsets',[1,1,1]); */ /* onsets(tripleInd+1) = 0; */ /* onsets(tripleInd+2) = 0; */ /* */ /* doubleInd = strfind(onsets',[1,1]); */ /* onsets(doubleInd+1) = 0; */ /* onsets(1) = 0; */ /* flux(1) = 0; */ /* onsets(end+1) = 0; */ /* flux(end+1) = 0; */ /* xmin = 1; */ /* xmax = length(flux); */ /* */ /* figure */ /* subplot(4,1,1) */ /* stem(mask1); */ /* axis([xmin xmax 0 1]); */ /* subplot(4,1,2) */ /* stem(mask2); */ /* axis([xmin xmax 0 1]); */ /* subplot(4,1,3) */ /* stem(mask1&mask2); */ /* axis([xmin xmax 0 1]); */ /* subplot(4,1,4); */ /* imagesc(denoisedSpec); */ /* axis([xmin xmax 0 512]); */ /* axis('xy'); */ /* colormap(hot); */ } static void onsetFlux(const emxArray_real_T *S, emxArray_real_T *flux) { emxArray_real_T *b_S; int32_T iyLead; int32_T loop_ub; int32_T ixLead; int32_T iy; emxArray_real_T *x; int32_T d; emxArray_real_T *b_y1; uint32_T ySize[2]; int32_T ix; real_T work; real_T tmp2; emxArray_real_T *r4; emxArray_real_T *b_flux; real_T y; real_T r; emxArray_real_T *c_flux; emxArray_boolean_T *b_x; emxArray_int32_T *r5; b_emxInit_real_T(&b_S, 1); /* ONSETFLUX Computes new spectral flux */ /* Detailed explanation goes here */ /* Just to be sure */ /* S = abs(S); */ iyLead = S->size[0]; loop_ub = S->size[0]; ixLead = S->size[1]; iy = b_S->size[0]; b_S->size[0] = loop_ub; emxEnsureCapacity((emxArray__common *)b_S, iy, (int32_T)sizeof(real_T)); for (iy = 0; iy < loop_ub; iy++) { b_S->data[iy] = S->data[iy + S->size[0] * (ixLead - 1)]; } emxInit_real_T(&x, 2); iy = x->size[0] * x->size[1]; x->size[0] = S->size[0]; x->size[1] = S->size[1] + 1; emxEnsureCapacity((emxArray__common *)x, iy, (int32_T)sizeof(real_T)); loop_ub = S->size[1]; for (iy = 0; iy < loop_ub; iy++) { d = S->size[0]; for (ixLead = 0; ixLead < d; ixLead++) { x->data[ixLead + x->size[0] * iy] = S->data[ixLead + S->size[0] * iy]; } } iy = 0; while (iy <= 0) { for (iy = 0; iy < iyLead; iy++) { x->data[iy + x->size[0] * S->size[1]] = b_S->data[iy]; } iy = 1; } emxFree_real_T(&b_S); emxInit_real_T(&b_y1, 2); if (1 >= x->size[1]) { for (iy = 0; iy < 2; iy++) { ySize[iy] = (uint32_T)x->size[iy]; } iy = b_y1->size[0] * b_y1->size[1]; b_y1->size[0] = (int32_T)ySize[0]; emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T)); iy = b_y1->size[0] * b_y1->size[1]; b_y1->size[1] = 0; emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T)); } else { for (iy = 0; iy < 2; iy++) { ySize[iy] = (uint32_T)x->size[iy]; } iy = b_y1->size[0] * b_y1->size[1]; b_y1->size[0] = (int32_T)ySize[0]; b_y1->size[1] = x->size[1] - 1; emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T)); ix = 0; iy = 1; for (d = 1; d <= x->size[0]; d++) { ixLead = ix + x->size[0]; iyLead = iy; work = x->data[ix]; for (loop_ub = 2; loop_ub <= x->size[1]; loop_ub++) { tmp2 = work; work = x->data[ixLead]; tmp2 = x->data[ixLead] - tmp2; ixLead += x->size[0]; b_y1->data[iyLead - 1] = tmp2; iyLead += x->size[0]; } ix++; iy++; } } emxFree_real_T(&x); /* Half wave rectification */ for (iy = 0; iy < 2; iy++) { ySize[iy] = (uint32_T)b_y1->size[iy]; } emxInit_real_T(&r4, 2); iy = r4->size[0] * r4->size[1]; r4->size[0] = (int32_T)ySize[0]; r4->size[1] = (int32_T)ySize[1]; emxEnsureCapacity((emxArray__common *)r4, iy, (int32_T)sizeof(real_T)); iy = b_y1->size[0] * b_y1->size[1]; for (loop_ub = 0; loop_ub < iy; loop_ub++) { r4->data[(int32_T)(1.0 + (real_T)loop_ub) - 1] = fabs(b_y1->data[(int32_T) (1.0 + (real_T)loop_ub) - 1]); } iy = b_y1->size[0] * b_y1->size[1]; emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T)); ixLead = b_y1->size[0]; d = b_y1->size[1]; iyLead = ixLead * d; for (iy = 0; iy < iyLead; iy++) { b_y1->data[iy] = (b_y1->data[iy] + r4->data[iy]) / 2.0; } emxFree_real_T(&r4); /* Summed across all bins */ for (iy = 0; iy < 2; iy++) { ySize[iy] = (uint32_T)b_y1->size[iy]; } emxInit_real_T(&b_flux, 2); iy = b_flux->size[0] * b_flux->size[1]; b_flux->size[0] = 1; b_flux->size[1] = (int32_T)ySize[1]; emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T)); if ((b_y1->size[0] == 0) || (b_y1->size[1] == 0)) { iy = b_flux->size[0] * b_flux->size[1]; b_flux->size[0] = 1; emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T)); iy = b_flux->size[0] * b_flux->size[1]; b_flux->size[1] = (int32_T)ySize[1]; emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T)); iyLead = (int32_T)ySize[1]; for (iy = 0; iy < iyLead; iy++) { b_flux->data[iy] = 0.0; } } else { ix = -1; iy = -1; for (d = 1; d <= b_y1->size[1]; d++) { ixLead = ix + 1; ix++; tmp2 = b_y1->data[ixLead]; for (loop_ub = 2; loop_ub <= b_y1->size[0]; loop_ub++) { ix++; tmp2 += b_y1->data[ix]; } iy++; b_flux->data[iy] = tmp2; } } emxFree_real_T(&b_y1); if (b_flux->size[1] == 0) { tmp2 = 0.0; } else { tmp2 = b_flux->data[0]; for (loop_ub = 2; loop_ub <= b_flux->size[1]; loop_ub++) { tmp2 += b_flux->data[loop_ub - 1]; } } tmp2 /= (real_T)b_flux->size[1]; if (b_flux->size[1] > 1) { d = b_flux->size[1] - 1; } else { d = b_flux->size[1]; } if (b_flux->size[1] == 0) { y = rtNaN; } else { ix = 0; work = b_flux->data[0]; for (loop_ub = 0; loop_ub <= b_flux->size[1] - 2; loop_ub++) { ix++; work += b_flux->data[ix]; } work /= (real_T)b_flux->size[1]; ix = 0; r = b_flux->data[0] - work; y = r * r; for (loop_ub = 0; loop_ub <= b_flux->size[1] - 2; loop_ub++) { ix++; r = b_flux->data[ix] - work; y += r * r; } y /= (real_T)d; } emxInit_real_T(&c_flux, 2); iy = c_flux->size[0] * c_flux->size[1]; c_flux->size[0] = 1; c_flux->size[1] = b_flux->size[1]; emxEnsureCapacity((emxArray__common *)c_flux, iy, (int32_T)sizeof(real_T)); iyLead = b_flux->size[0] * b_flux->size[1]; for (iy = 0; iy < iyLead; iy++) { c_flux->data[iy] = b_flux->data[iy] - tmp2; } rdivide(c_flux, y, b_flux); iy = flux->size[0]; flux->size[0] = b_flux->size[1]; emxEnsureCapacity((emxArray__common *)flux, iy, (int32_T)sizeof(real_T)); iyLead = b_flux->size[1]; emxFree_real_T(&c_flux); for (iy = 0; iy < iyLead; iy++) { flux->data[iy] = b_flux->data[iy]; } emxFree_real_T(&b_flux); b_emxInit_boolean_T(&b_x, 1); iy = b_x->size[0]; b_x->size[0] = flux->size[0]; emxEnsureCapacity((emxArray__common *)b_x, iy, (int32_T)sizeof(boolean_T)); iyLead = flux->size[0]; for (iy = 0; iy < iyLead; iy++) { b_x->data[iy] = (flux->data[iy] < 0.0); } loop_ub = 0; for (d = 1; d <= b_x->size[0]; d++) { if (b_x->data[d - 1]) { loop_ub++; } } emxInit_int32_T(&r5, 1); iy = r5->size[0]; r5->size[0] = loop_ub; emxEnsureCapacity((emxArray__common *)r5, iy, (int32_T)sizeof(int32_T)); ixLead = 0; for (d = 1; d <= b_x->size[0]; d++) { if (b_x->data[d - 1]) { r5->data[ixLead] = d; ixLead++; } } emxFree_boolean_T(&b_x); iyLead = r5->size[0]; for (iy = 0; iy < iyLead; iy++) { flux->data[r5->data[iy] - 1] = 0.0; } emxFree_int32_T(&r5); } static void padarray(const emxArray_real_T *varargin_1, emxArray_real_T *b) { real_T sizeB[2]; int32_T i3; real_T b_sizeB; int32_T c_sizeB[2]; int32_T outsize[2]; int32_T loop_ub; for (i3 = 0; i3 < 2; i3++) { sizeB[i3] = 0.0; } sizeB[0] = 3.0; if ((varargin_1->size[0] == 0) || (varargin_1->size[1] == 0)) { for (i3 = 0; i3 < 2; i3++) { b_sizeB = (real_T)varargin_1->size[i3] + 2.0 * sizeB[i3]; sizeB[i3] = b_sizeB; } c_sizeB[0] = (int32_T)sizeB[0]; c_sizeB[1] = (int32_T)sizeB[1]; for (i3 = 0; i3 < 2; i3++) { outsize[i3] = c_sizeB[i3]; } i3 = b->size[0] * b->size[1]; b->size[0] = outsize[0]; emxEnsureCapacity((emxArray__common *)b, i3, (int32_T)sizeof(real_T)); i3 = b->size[0] * b->size[1]; b->size[1] = outsize[1]; emxEnsureCapacity((emxArray__common *)b, i3, (int32_T)sizeof(real_T)); loop_ub = outsize[0] * outsize[1]; for (i3 = 0; i3 < loop_ub; i3++) { b->data[i3] = 0.0; } } else { ConstantPad(varargin_1, sizeB, b); } } static void rdivide(const emxArray_real_T *x, real_T y, emxArray_real_T *z) { int32_T i1; int32_T loop_ub; i1 = z->size[0] * z->size[1]; z->size[0] = 1; z->size[1] = x->size[1]; emxEnsureCapacity((emxArray__common *)z, i1, (int32_T)sizeof(real_T)); loop_ub = x->size[0] * x->size[1]; for (i1 = 0; i1 < loop_ub; i1++) { z->data[i1] = x->data[i1] / y; } } static real_T rt_powd_snf(real_T u0, real_T u1) { real_T y; real_T d0; real_T d1; if (rtIsNaN(u0) || rtIsNaN(u1)) { y = rtNaN; } else { d0 = fabs(u0); d1 = fabs(u1); if (rtIsInf(u1)) { if (d0 == 1.0) { y = rtNaN; } else if (d0 > 1.0) { if (u1 > 0.0) { y = rtInf; } else { y = 0.0; } } else if (u1 > 0.0) { y = 0.0; } else { y = rtInf; } } else if (d1 == 0.0) { y = 1.0; } else if (d1 == 1.0) { if (u1 > 0.0) { y = u0; } else { y = 1.0 / u0; } } else if (u1 == 2.0) { y = u0 * u0; } else if ((u1 == 0.5) && (u0 >= 0.0)) { y = sqrt(u0); } else if ((u0 < 0.0) && (u1 > floor(u1))) { y = rtNaN; } else { y = pow(u0, u1); } } return y; } void computeOnsetFeatures(const emxArray_real_T *denoisedSpectrum, const emxArray_real_T *T, real_T ioiFeatures[12], emxArray_boolean_T *onsets) { emxArray_real_T *unusedU0; emxArray_boolean_T *b_onsets; int32_T i; int32_T loop_ub; real_T ioiHist[17]; boolean_T bv0[12]; int32_T tmp_size[1]; int32_T tmp_data[12]; emxInit_real_T(&unusedU0, 2); emxInit_boolean_T(&b_onsets, 2); /* COMPUTEONSETFEATURES Computes onset features */ onsetDetection(denoisedSpectrum, onsets, unusedU0); /* Collecting number of onsets per 2 second window */ /* onsetFeatures1 = onsetFeatures(onsets,T); */ /* Collect IOI histogram */ i = b_onsets->size[0] * b_onsets->size[1]; b_onsets->size[0] = onsets->size[0]; b_onsets->size[1] = onsets->size[1]; emxEnsureCapacity((emxArray__common *)b_onsets, i, (int32_T)sizeof(boolean_T)); loop_ub = onsets->size[0] * onsets->size[1]; emxFree_real_T(&unusedU0); for (i = 0; i < loop_ub; i++) { b_onsets->data[i] = onsets->data[i]; } ioiHistogram(b_onsets, T, ioiHist); histogramFeatures(ioiHist, ioiFeatures); /* ioiFeatures = vertcat(ioiFeatures,onsetFeatures1); */ emxFree_boolean_T(&b_onsets); for (i = 0; i < 12; i++) { bv0[i] = rtIsNaN(ioiFeatures[i]); } b_eml_li_find(bv0, tmp_data, tmp_size); loop_ub = tmp_size[0]; for (i = 0; i < loop_ub; i++) { ioiFeatures[tmp_data[i] - 1] = 0.0; } for (i = 0; i < 12; i++) { bv0[i] = rtIsInf(ioiFeatures[i]); } b_eml_li_find(bv0, tmp_data, tmp_size); loop_ub = tmp_size[0]; for (i = 0; i < loop_ub; i++) { ioiFeatures[tmp_data[i] - 1] = 0.0; } } void computeOnsetFeatures_initialize(void) { rt_InitInfAndNaN(8U); } void computeOnsetFeatures_terminate(void) { /* (no terminate code required) */ } emxArray_boolean_T *emxCreateND_boolean_T(int32_T numDimensions, int32_T *size) { emxArray_boolean_T *emx; int32_T numEl; int32_T i; emxInit_boolean_T(&emx, numDimensions); numEl = 1; for (i = 0; i < numDimensions; i++) { numEl *= size[i]; emx->size[i] = size[i]; } emx->data = (boolean_T *)calloc((uint32_T)numEl, sizeof(boolean_T)); emx->numDimensions = numDimensions; emx->allocatedSize = numEl; return emx; } //emxArray_real_T *emxCreateND_real_T(int32_T numDimensions, int32_T *size) //{ // emxArray_real_T *emx; // int32_T numEl; // int32_T i; // emxInit_real_T(&emx, numDimensions); // numEl = 1; // for (i = 0; i < numDimensions; i++) { // numEl *= size[i]; // emx->size[i] = size[i]; // } // // emx->data = (real_T *)calloc((uint32_T)numEl, sizeof(real_T)); // emx->numDimensions = numDimensions; // emx->allocatedSize = numEl; // return emx; //} emxArray_boolean_T *emxCreateWrapperND_boolean_T(boolean_T *data, int32_T numDimensions, int32_T *size) { emxArray_boolean_T *emx; int32_T numEl; int32_T i; emxInit_boolean_T(&emx, numDimensions); numEl = 1; for (i = 0; i < numDimensions; i++) { numEl *= size[i]; emx->size[i] = size[i]; } emx->data = data; emx->numDimensions = numDimensions; emx->allocatedSize = numEl; emx->canFreeData = FALSE; return emx; } //emxArray_real_T *emxCreateWrapperND_real_T(real_T *data, int32_T numDimensions, // int32_T *size) //{ // emxArray_real_T *emx; // int32_T numEl; // int32_T i; // emxInit_real_T(&emx, numDimensions); // numEl = 1; // for (i = 0; i < numDimensions; i++) { // numEl *= size[i]; // emx->size[i] = size[i]; // } // // emx->data = data; // emx->numDimensions = numDimensions; // emx->allocatedSize = numEl; // emx->canFreeData = FALSE; // return emx; //} emxArray_boolean_T *emxCreateWrapper_boolean_T(boolean_T *data, int32_T rows, int32_T cols) { emxArray_boolean_T *emx; int32_T size[2]; int32_T numEl; int32_T i; size[0] = rows; size[1] = cols; emxInit_boolean_T(&emx, 2); numEl = 1; for (i = 0; i < 2; i++) { numEl *= size[i]; emx->size[i] = size[i]; } emx->data = data; emx->numDimensions = 2; emx->allocatedSize = numEl; emx->canFreeData = FALSE; return emx; } //emxArray_real_T *emxCreateWrapper_real_T(real_T *data, int32_T rows, int32_T // cols) //{ // emxArray_real_T *emx; // int32_T size[2]; // int32_T numEl; // int32_T i; // size[0] = rows; // size[1] = cols; // emxInit_real_T(&emx, 2); // numEl = 1; // for (i = 0; i < 2; i++) { // numEl *= size[i]; // emx->size[i] = size[i]; // } // // emx->data = data; // emx->numDimensions = 2; // emx->allocatedSize = numEl; // emx->canFreeData = FALSE; // return emx; //} emxArray_boolean_T *emxCreate_boolean_T(int32_T rows, int32_T cols) { emxArray_boolean_T *emx; int32_T size[2]; int32_T numEl; int32_T i; size[0] = rows; size[1] = cols; emxInit_boolean_T(&emx, 2); numEl = 1; for (i = 0; i < 2; i++) { numEl *= size[i]; emx->size[i] = size[i]; } emx->data = (boolean_T *)calloc((uint32_T)numEl, sizeof(boolean_T)); emx->numDimensions = 2; emx->allocatedSize = numEl; return emx; } //emxArray_real_T *emxCreate_real_T(int32_T rows, int32_T cols) //{ // emxArray_real_T *emx; // int32_T size[2]; // int32_T numEl; // int32_T i; // size[0] = rows; // size[1] = cols; // emxInit_real_T(&emx, 2); // numEl = 1; // for (i = 0; i < 2; i++) { // numEl *= size[i]; // emx->size[i] = size[i]; // } // // emx->data = (real_T *)calloc((uint32_T)numEl, sizeof(real_T)); // emx->numDimensions = 2; // emx->allocatedSize = numEl; // return emx; //} void emxDestroyArray_boolean_T(emxArray_boolean_T *emxArray) { emxFree_boolean_T(&emxArray); } //void emxDestroyArray_real_T(emxArray_real_T *emxArray) //{ // emxFree_real_T(&emxArray); //} /* End of code generation (computeOnsetFeatures.c) */
Java
/* * Copyright (C) 2009-2015 Pivotal Software, Inc * * This program is is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. * * 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. */ .tundra .dijitDialogRtl .dijitDialogCloseIcon { right: auto; left: 5px; }
Java
<?php locate_template( array( 'mobile/header-mobile.php' ), true, false ); ?> <?php if ( have_posts() ) { ?> <?php while ( have_posts() ) { the_post(); ?> <div <?php post_class( 'tbm-post tbm-padded' ) ?> id="post-<?php the_ID(); ?>"> <h2><?php the_title(); ?></h2> <?php the_content(); ?> <?php wp_link_pages('before=<div class="tbm-pc-navi">' . __('Pages', 'fastfood') . ':&after=</div>'); ?> </div> <?php comments_template('/mobile/comments-mobile.php'); ?> <?php $tbm_args = array( 'post_type' => 'page', 'post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order', 'numberposts' => 0 ); $tbm_sub_pages = get_posts( $tbm_args ); // retrieve the child pages if (!empty($tbm_sub_pages)) { ?> <?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Child pages', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?> <ul class="tbm-group"> <?php foreach ( $tbm_sub_pages as $tbm_children ) { echo '<li class="outset"><a href="' . get_permalink( $tbm_children ) . '" title="' . esc_attr( strip_tags( get_the_title( $tbm_children ) ) ) . '">' . get_the_title( $tbm_children ) . '</a></li>'; } ?> </ul> <?php } ?> <?php $tbm_the_parent_page = $post->post_parent; // retrieve the parent page if ( $tbm_the_parent_page ) {?> <?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Parent page', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?> <ul class="tbm-group"> <li class="outset"><a href="<?php echo get_permalink( $tbm_the_parent_page ); ?>" title="<?php echo esc_attr( strip_tags( get_the_title( $tbm_the_parent_page ) ) ); ?>"><?php echo get_the_title( $tbm_the_parent_page ); ?></a></li> </ul> <?php } ?> <?php } ?> <?php } else { ?> <p class="tbm-padded"><?php _e( 'Sorry, no posts matched your criteria.', 'fastfood' );?></p> <?php } ?> <?php locate_template( array( 'mobile/footer-mobile.php' ), true, false ); ?>
Java
<?php // The name of this module define("_MI_MEDIAWIKI_NAME", "MediaWiki"); // A brief description of this module define("_MI_MEDIAWIKI_DESC", "MediaWiki For XOOPS Community"); // Configs define("_MI_MEDIAWIKI_STYLE", "Interface style"); define("_MI_MEDIAWIKI_STYLE_DESC", "Xoops style, MediaWiki style, or user selectable"); define("_MI_MEDIAWIKI_BLOCK_SIDEBAR", "MediaWiki Sidebar"); define("_MI_MEDIAWIKI_BLOCK_RECENTCHANGES", "MediaWiki Recent changes"); define("_MI_MEDIAWIKI_BLOCK_TOP", "Most revisions"); define("_MI_MEDIAWIKI_BLOCK_HOT", "Hot contents"); ?>
Java
/* * Copyright (C) 2016, 2017 by Rafael Santiago * * This is a free software. You can redistribute it and/or modify under * the terms of the GNU General Public License version 2. * */ #include <cpu/itp/itp0.h> #include <ctx/ctx.h> #include <vid/vid.h> unsigned short itp0_gate(const unsigned short nnn, struct cp8_ctx *cp8) { unsigned short next = 2; switch (nnn) { case 0x00e0: // INFO(Rafael): CLS cp8_vidcls(); break; case 0x00ee: // INFO(Rafael): RET cp8->pc = cp8_pop(cp8); break; default: // INFO(Rafael): SYS addr is a pretty old stuff and should be ignored. break; } return (cp8->pc + next); }
Java
package nl.pelagic.musicTree.flac2mp3.cli; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.file.Files; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import nl.pelagic.audio.conversion.flac2mp3.api.Flac2Mp3Configuration; import nl.pelagic.audio.conversion.flac2mp3.api.FlacToMp3; import nl.pelagic.audio.musicTree.configuration.api.MusicTreeConfiguration; import nl.pelagic.audio.musicTree.configuration.api.MusicTreeConstants; import nl.pelagic.audio.musicTree.syncer.api.Syncer; import nl.pelagic.audio.musicTree.util.MusicTreeHelpers; import nl.pelagic.musicTree.flac2mp3.cli.i18n.Messages; import nl.pelagic.shell.script.listener.api.ShellScriptListener; import nl.pelagic.shutdownhook.api.ShutdownHookParticipant; import nl.pelagic.util.file.FileUtils; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.osgi.framework.BundleContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; /** * The main program that synchronises a flac tree into a mp3 tree or just * converts one or more flac files in mp3 files, based on a music tree * configuration */ @Component(property = { "main.thread=true" /* Signal the launcher that this is the main thread */ }) public class Main implements Runnable, ShutdownHookParticipant { /** the application logger name */ static private final String LOGGER_APPLICATION_NAME = "nl.pelagic"; //$NON-NLS-1$ /** the application logger level to allow */ static private final Level LOGGER_APPLICATION_LEVEL = Level.SEVERE; /** the jaudiotagger library logger name */ static private final String LOGGER_JAUDIOTAGGER_NAME = "org.jaudiotagger"; //$NON-NLS-1$ /** the jaudiotagger library logger level to allow */ static private final Level LOGGER_JAUDIOTAGGER_LEVEL = Level.SEVERE; /** the program name */ static final String PROGRAM_NAME = "flac2mp3"; //$NON-NLS-1$ /** the application logger */ private final Logger applicationLogger; /** the jaudiotagger library logger */ private final Logger jaudiotaggerLogger; /** the list of extension to use in the flac tree */ private final HashSet<String> extensionsList = new HashSet<>(); /** the filenames for covers to use in the flac tree */ private final HashSet<String> coversList = new HashSet<>(); /* * Construction */ /** * Default constructor */ public Main() { super(); /** * <pre> * 1=timestamp * 2=level * 3=logger * 4=class method * 5=message * 6=stack trace, preceded by a newline (if exception is present) * </pre> */ System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$10s %2$s : %5$s%6$s%n"); //$NON-NLS-1$ //$NON-NLS-2$ applicationLogger = Logger.getLogger(LOGGER_APPLICATION_NAME); applicationLogger.setLevel(LOGGER_APPLICATION_LEVEL); jaudiotaggerLogger = Logger.getLogger(LOGGER_JAUDIOTAGGER_NAME); jaudiotaggerLogger.setLevel(LOGGER_JAUDIOTAGGER_LEVEL); extensionsList.add(MusicTreeConstants.FLACEXTENSION); coversList.add(MusicTreeConstants.COVER); } /* * Consumed Services */ /** the shell script listener (optional) */ private ShellScriptListener shellScriptListener = null; /** * @param shellScriptListener the shellScriptListener to set */ @Reference void setShellScriptListener(ShellScriptListener shellScriptListener) { this.shellScriptListener = shellScriptListener; } /** the flac2Mp3 service */ private FlacToMp3 flacToMp3 = null; /** * @param flacToMp3 the flacToMp3 to set */ @Reference void setFlacToMp3(FlacToMp3 flacToMp3) { this.flacToMp3 = flacToMp3; } /** the syncer service */ private Syncer syncer = null; /** * @param syncer the syncer to set */ @Reference void setSyncer(Syncer syncer) { this.syncer = syncer; } /* * Command line arguments */ /** the launcher arguments property name */ static final String LAUNCHER_ARGUMENTS = "launcher.arguments"; //$NON-NLS-1$ /** the command line arguments */ private String[] args = null; /** * The bnd launcher provides access to the command line arguments via the * Launcher object. This object is also registered under Object. * * @param done unused * @param parameters the launcher parameters, which includes the command line * arguments */ @Reference void setDone(@SuppressWarnings("unused") Object done, Map<String, Object> parameters) { args = (String[]) parameters.get(LAUNCHER_ARGUMENTS); } /* * Bundle */ /** The setting name for the stayAlive property */ public static final String SETTING_STAYALIVE = "stayAlive"; //$NON-NLS-1$ /** true when the application should NOT automatically exit when done */ private boolean stayAlive = false; /** * Bundle activator * * @param bundleContext the bundle context */ @Activate void activate(BundleContext bundleContext) { String ex = bundleContext.getProperty(PROGRAM_NAME + "." + SETTING_STAYALIVE); //$NON-NLS-1$ if (ex != null) { stayAlive = Boolean.parseBoolean(ex); } } /** * Bundle deactivator */ @Deactivate void deactivate() { /* nothing to do */ } /* * Helpers */ /** * Read a filelist file into a list of entries to convert * * @param out the stream to print the error messages to * @param fileList the filelist file * @param entriesToConvert a list of files to convert, to which the files read * from the filelist file must be added * @return true when successful */ static boolean readFileList(PrintStream out, File fileList, List<String> entriesToConvert) { assert (out != null); assert (fileList != null); assert (entriesToConvert != null); if (!fileList.isFile()) { out.printf(Messages.getString("Main.8"), fileList.getPath()); //$NON-NLS-1$ return false; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(fileList.toPath()), "UTF-8"))) { //$NON-NLS-1$ String line = null; while ((line = reader.readLine()) != null) { /* skip empty lines */ if (line.trim().isEmpty()) { continue; } entriesToConvert.add(line); } } catch (IOException e) { /* can't be covered in a test */ out.printf(Messages.getString("Main.11"), fileList, e.getLocalizedMessage()); //$NON-NLS-1$ return false; } return true; } /** * Validate the entry to convert to filter out non-existing directories and * files. An entry to convert must exist and be below the flac base directory. * * @param out the stream to print the error messages to * @param musicTreeConfiguration the music tree configuration * @param entryToConvert the entry to convert * @return true when validation is successful */ static boolean validateEntryToConvert(PrintStream out, MusicTreeConfiguration musicTreeConfiguration, File entryToConvert) { assert (out != null); assert (musicTreeConfiguration != null); assert (entryToConvert != null); /* check that the entry exists */ if (!entryToConvert.exists()) { out.printf(Messages.getString("Main.5"), entryToConvert.getPath()); //$NON-NLS-1$ return false; } /* * check that entry is below the flac base directory so that it doesn't * escape the base directory by doing a ../../.. */ if (!FileUtils.isFileBelowDirectory(musicTreeConfiguration.getFlacBaseDir(), entryToConvert, true)) { out.printf(Messages.getString("Main.6"), //$NON-NLS-1$ entryToConvert.getPath(), musicTreeConfiguration.getFlacBaseDir().getPath()); return false; } return true; } /** * Convert a flac file into an mp3 file. * * @param err the stream to print to * @param flac2Mp3Configuration the conversion configuration. When null then * the default configuration is used. * @param musicTreeConfiguration the music tree configuration * @param simulate true to simulate conversion * @param fileToConvert the flac file to convert * * @return true when successful */ boolean convertFile(PrintStream err, Flac2Mp3Configuration flac2Mp3Configuration, MusicTreeConfiguration musicTreeConfiguration, boolean simulate, File fileToConvert) { assert (err != null); assert (flac2Mp3Configuration != null); assert (musicTreeConfiguration != null); assert (fileToConvert != null); assert (fileToConvert.isFile()); File mp3File = MusicTreeHelpers.flacFileToMp3File(musicTreeConfiguration, fileToConvert); if (mp3File == null) { err.printf(Messages.getString("Main.12"), fileToConvert.getPath(), //$NON-NLS-1$ musicTreeConfiguration.getMp3BaseDir().getPath()); return false; } boolean doConversion = !mp3File.exists() || (fileToConvert.lastModified() > mp3File.lastModified()); if (!doConversion) { return true; } boolean converted = false; try { converted = flacToMp3.convert(flac2Mp3Configuration, fileToConvert, mp3File, simulate); if (!converted) { err.printf(Messages.getString("Main.1"), fileToConvert.getPath()); //$NON-NLS-1$ } } catch (IOException e) { converted = false; err.printf(Messages.getString("Main.2"), fileToConvert.getPath(), e.getLocalizedMessage()); //$NON-NLS-1$ } return converted; } /** * Stay alive, if needed (which is when the component has a SETTING_STAYALIVE * property set to true). * * @param err the stream to print a 'staying alive' message to */ void stayAlive(PrintStream err) { if (!stayAlive) { return; } err.printf(Messages.getString("Main.7")); //$NON-NLS-1$ try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { /* swallow */ } } /* * ShutdownHookParticipant */ /** true when we have to stop */ private AtomicBoolean stop = new AtomicBoolean(false); @Override public void shutdownHook() { stop.set(true); } /* * Main */ /** * Run the main program * * @param err the stream to print errors to * @return true when successful */ boolean doMain(PrintStream err) { if (args == null) { /* * the launcher didn't set our command line options so set empty arguments * (use defaults) */ args = new String[0]; } /* * Parse the command line */ CommandLineOptions commandLineOptions = new CommandLineOptions(); CmdLineParser parser = new CmdLineParser(commandLineOptions); try { parser.parseArgument(args); } catch (CmdLineException e) { err.printf(Messages.getString("Main.4"), e.getLocalizedMessage()); //$NON-NLS-1$ commandLineOptions.setErrorReported(true); } /* * Process command-line options */ /* print usage when so requested and exit */ if (commandLineOptions.isHelp() || commandLineOptions.isErrorReported()) { try { /* can't be covered by a test */ int cols = Integer.parseInt(System.getenv("COLUMNS")); //$NON-NLS-1$ if (cols > 80) { parser.getProperties().withUsageWidth(cols); } } catch (NumberFormatException e) { /* swallow, can't be covered by a test */ } CommandLineOptions.usage(err, PROGRAM_NAME, parser); return false; } /* * Setup verbose modes in the shell script listener */ shellScriptListener.setVerbose(commandLineOptions.isVerbose(), commandLineOptions.isExtraVerbose(), commandLineOptions.isQuiet()); /* * Setup & validate the music tree configuration */ MusicTreeConfiguration musicTreeConfiguration = new MusicTreeConfiguration(commandLineOptions.getFlacBaseDir(), commandLineOptions.getMp3BaseDir()); List<String> errors = musicTreeConfiguration.validate(true); if (errors != null) { for (String error : errors) { err.println(error); } return false; } /* * Setup & validate the flac2mp3 configuration */ Flac2Mp3Configuration flac2Mp3Configuration = new Flac2Mp3Configuration(); flac2Mp3Configuration.setFlacExecutable(commandLineOptions.getFlacExecutable().getPath()); flac2Mp3Configuration.setLameExecutable(commandLineOptions.getLameExecutable().getPath()); flac2Mp3Configuration.setFlacOptions(commandLineOptions.getFlacOptions()); flac2Mp3Configuration.setLameOptions(commandLineOptions.getLameOptions()); flac2Mp3Configuration.setUseId3V1Tags(commandLineOptions.isUseID3v1()); flac2Mp3Configuration.setUseId3V24Tags(commandLineOptions.isUseID3v24()); flac2Mp3Configuration.setForceConversion(commandLineOptions.isForceConversion()); flac2Mp3Configuration.setRunFlacLame(!commandLineOptions.isDoNotRunFlacAndLame()); flac2Mp3Configuration.setCopyTag(!commandLineOptions.isDoNotCopyTag()); flac2Mp3Configuration.setCopyTimestamp(!commandLineOptions.isDoNotCopyTimestamp()); errors = flac2Mp3Configuration.validate(); if (errors != null) { /* can't be covered by a test */ for (String error : errors) { err.println(error); } return false; } /* * Setup the entries to convert: first get them from the command-line (if * specified) and then add those in the file list (if set) */ List<String> entriesToConvert = commandLineOptions.getEntriesToConvert(); File fileList = commandLineOptions.getFileList(); if (fileList != null) { readFileList(err, fileList, entriesToConvert); } if (entriesToConvert.isEmpty()) { /* * no entries to convert, so default to the flac base directory: sync the * whole tree */ entriesToConvert.add(musicTreeConfiguration.getFlacBaseDir().getAbsolutePath()); } /* * Run */ boolean result = true; for (String entryToConvert : entriesToConvert) { if (stop.get()) { break; } File entryToConvertFile = new File(entryToConvert); boolean validationResult = validateEntryToConvert(err, musicTreeConfiguration, entryToConvertFile); if (validationResult) { if (entryToConvertFile.isDirectory()) { result = result && syncer.syncFlac2Mp3(flac2Mp3Configuration, musicTreeConfiguration, entryToConvertFile, extensionsList, coversList, commandLineOptions.isSimulate()); } else if (entryToConvertFile.isFile()) { result = result && convertFile(err, flac2Mp3Configuration, musicTreeConfiguration, commandLineOptions.isSimulate(), entryToConvertFile); } else { /* can't be covered by a test */ err.printf(Messages.getString("Main.3"), entryToConvert); //$NON-NLS-1$ } } else { result = false; } } return result; } /* * Since we're registered as a Runnable with the main.thread property we get * called when the system is fully initialised. */ @Override public void run() { boolean success = doMain(System.err); stayAlive(System.err); if (!success) { /* can't be covered by a test */ System.exit(1); } } }
Java
--真竜皇リトスアジムD function c30539496.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(30539496,0)) e1:SetCategory(CATEGORY_DESTROY+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,30539496) e1:SetTarget(c30539496.sptg) e1:SetOperation(c30539496.spop) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(30539496,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCode(EVENT_DESTROYED) e2:SetCountLimit(1,30539497) e2:SetCondition(c30539496.spcon2) e2:SetTarget(c30539496.sptg2) e2:SetOperation(c30539496.spop2) c:RegisterEffect(e2) end function c30539496.desfilter(c) return c:IsType(TYPE_MONSTER) and ((c:IsLocation(LOCATION_MZONE) and c:IsFaceup()) or c:IsLocation(LOCATION_HAND)) end function c30539496.locfilter(c,tp) return c:IsLocation(LOCATION_MZONE) and c:IsControler(tp) end function c30539496.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) local loc=LOCATION_MZONE+LOCATION_HAND if ft<0 then loc=LOCATION_MZONE end local loc2=0 if Duel.IsPlayerAffectedByEffect(tp,88581108) then loc2=LOCATION_MZONE end local g=Duel.GetMatchingGroup(c30539496.desfilter,tp,loc,loc2,c) if chk==0 then return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and g:GetCount()>=2 and g:IsExists(Card.IsAttribute,1,nil,ATTRIBUTE_EARTH) and (ft>0 or g:IsExists(c30539496.locfilter,-ft+1,nil,tp)) end Duel.SetOperationInfo(0,CATEGORY_DESTROY,nil,2,tp,loc) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function c30539496.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) local loc=LOCATION_MZONE+LOCATION_HAND if ft<0 then loc=LOCATION_MZONE end local loc2=0 if Duel.IsPlayerAffectedByEffect(tp,88581108) then loc2=LOCATION_MZONE end local g=Duel.GetMatchingGroup(c30539496.desfilter,tp,loc,loc2,c) if g:GetCount()<2 or not g:IsExists(Card.IsAttribute,1,nil,ATTRIBUTE_EARTH) then return end local g1=nil local g2=nil Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) if ft<1 then g1=g:FilterSelect(tp,c30539496.locfilter,1,1,nil,tp) else g1=g:Select(tp,1,1,nil) end g:RemoveCard(g1:GetFirst()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) if g1:GetFirst():IsAttribute(ATTRIBUTE_EARTH) then g2=g:Select(tp,1,1,nil) else g2=g:FilterSelect(tp,Card.IsAttribute,1,1,nil,ATTRIBUTE_EARTH) end g1:Merge(g2) local rm=g1:IsExists(Card.IsAttribute,2,nil,ATTRIBUTE_EARTH) if Duel.Destroy(g1,REASON_EFFECT)==2 then if not c:IsRelateToEffect(e) then return end if Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)==0 then return end local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_EXTRA,nil) if rm and rg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(30539496,2)) then Duel.ConfirmCards(tp,rg) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local tg=rg:SelectSubGroup(tp,aux.dncheck,false,1,3) Duel.Remove(tg,POS_FACEUP,REASON_EFFECT) Duel.ShuffleExtra(1-tp) end end end function c30539496.spcon2(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_EFFECT) end function c30539496.thfilter(c,e,tp) return not c:IsAttribute(ATTRIBUTE_EARTH) and c:IsRace(RACE_WYRM) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c30539496.sptg2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c30539496.thfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE) end function c30539496.spop2(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c30539496.thfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
Java
/** * \file ApplyMaskImageFilterParallel.h * \brief Definition of the thelib::ApplyMaskImageFilterParallel class. */ #ifndef THELIB_APPLYMASKIMAGEFILTERPARALLEL_H #define THELIB_APPLYMASKIMAGEFILTERPARALLEL_H // ITK #include <itkImageToImageFilter.h> // namespace namespace thelib { /** * \brief Mask an input image (input 0) using a mask image (input 1) (parrallel). * \ingroup TheLib */ template< class T > class ApplyMaskImageFilterParallel : public itk::ImageToImageFilter<T,T> { public: //! Standard class typedefs. typedef ApplyMaskImageFilterParallel Self; typedef itk::ImageToImageFilter<T,T> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; //! Method for creation through the object factory. itkNewMacro(Self); //! Run-time type information (and related methods). itkTypeMacro(ApplyMaskImageFilter, ImageToImageFilter); //! Set the invert flag. itkSetMacro(InvertMask, bool); //! Get the invert flag. itkGetConstMacro(InvertMask, bool); /** * Print information about this class. * \param os The stream to output to. * \param indent The indent to apply to the output. */ void PrintSelf(std::ostream& os, itk::Indent indent) const; protected: //! Constructor: protect from instantiation. ApplyMaskImageFilterParallel(); //! Destructor: protect from instantiation. ~ApplyMaskImageFilterParallel(); /** * Main method. * \param outputRegionForThread Image region to apply the filter to. * \param threadId The thread identifier. */ void ThreadedGenerateData( const typename itk::ImageSource<T>::OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId); private: //! Copy constructor: purposely not implemented. ApplyMaskImageFilterParallel( const Self& filter); //! Assignement operator: purposely not implemented. void operator=( const Self& filter); //! Flag to invert the mask or not bool m_InvertMask; }; // class ApplyMaskImageFilterParallel } // namespace thelib #endif //THELIB_APPLYMASKIMAGEFILTERPARALLEL_H
Java
<?php /** * @author Linkero * @filename fselink.class.php * @copyright 2014 * @version 0.1b */ class fseLink { protected $userKey = "INSERT_USER_KEY"; //User Key protected $groupKey = "INSERT_GROUP_KEY"; //Group Key protected $groupId = "INSERT_GROUP_ID"; //Group ID /* --------DO NOT EDIT BELOW THIS LINE-------- */ /* --Define initial arrays-- */ public $memberArray = array(); public $groupArray = array(); public $aircraftArray = array(); /* --Initializer-- */ public function startFSELink() { /* --Sets up groupArray-- */ /* --Structure: Flights, Time, Distance, Profit-- */ $this->groupArray = array( 0, 0, 0, number_format(0.00, 2)); /* --Loads Aircraft feed and sets up aircraftArray-- */ /* --Structure: Registration, Make/Model, Flights, Time, Distance, Profit-- */ $ac = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=aircraft&search=key&readaccesskey=$this->groupKey"); foreach ($ac->Aircraft as $aircraft) { array_push($this->aircraftArray, array( "$aircraft->Registration", "$aircraft->MakeModel", 0, 0, 0, number_format(0.00, 2))); } /* --Loads Group Member feed and sets up memberArray-- */ /* --Structure: Pilot Name, Group Status, Flights, Time, Distance, Profit-- */ $mem = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=group&search=members&readaccesskey=$this->groupKey"); foreach ($mem->Member as $Member) { array_push($this->memberArray, array( "$Member->Name", "$Member->Status", 0, 0, 0, number_format(0.00, 2))); //name, status, flights, time, distance, profit } /* --Populate arrays and return for use-- */ $this->populateArrays($this->memberArray, $this->groupArray, $this-> aircraftArray); return $this->memberArray; return $this->groupArray; return $this->aircraftArray; } /* --Populate Arrays-- */ private function populateArrays(&$memberArray, &$groupArray, &$aircraftArray) { /* --Loads Flight Log feed(LIMIT 500) and starts populating-- */ $logs = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=flightlogs&search=id&readaccesskey=$this->groupKey&fromid=$this->groupId"); foreach ($logs->FlightLog as $log) { $ft = explode(":", $log->FlightTime); //Split time for use /* --Populate memberArray-- */ for ($x = 0; $x < count($memberArray); $x++) { if (strcmp($memberArray[$x][0], $log->Pilot) == 0) { $memberArray[$x][2] = $memberArray[$x][2] + 1; //Increment flight counter $memberArray[$x][3] = $memberArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes) $memberArray[$x][4] = $memberArray[$x][4] + $log->Distance; //Add Distance $memberArray[$x][5] = $memberArray[$x][5] + floatval($log->PilotFee); //Add Pilot's Pay } } /* --Populates groupArray-- */ $groupArray[1] = $groupArray[1] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes) $groupArray[2] = $groupArray[2] + $log->Distance; //Add Distance $groupArray[3] = $groupArray[3] + floatval($log->Income) - floatval($log-> PilotFee) - floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log-> FuelCost) - floatval($log->GCF) - floatval($log->RentalCost); //Calculate Profit /* --Populates aircraftArray-- */ for ($x = 0; $x < count($aircraftArray); $x++) { if (strcmp($aircraftArray[$x][0], $log->Aircraft) == 0) { $aircraftArray[$x][2] = $aircraftArray[$x][2] + 1; //Increment flight counter $aircraftArray[$x][3] = $aircraftArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes) $aircraftArray[$x][4] = $aircraftArray[$x][4] + $log->Distance; //Add Distance $aircraftArray[$x][5] = $aircraftArray[$x][5] + floatval($log->Income) - floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log->FuelCost) - floatval($log->GCF); //Calculate Profit } } $groupArray[0] = count($logs->FlightLog); //Increment flight counter } /* --Returns populated arrays-- */ return $aircraftArray; return $memberArray; return $groupArray; } /* --Display sortable Pilot stats table-- */ public function displayPilotStats() { echo "<table id=\"memberTable\" class=\"tablesorter\"><thead><tr><th>Pilot</th><th>Status</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>"; for ($x = 0; $x < count($this->memberArray); $x++) { echo "<tr><td>" . $this->memberArray[$x][0] . "</td><td>" . ucfirst($this-> memberArray[$x][1]) . "</td><td>" . $this->memberArray[$x][2] . "</td><td>" . $this-> formatTime($this->memberArray[$x][3]) . "</td><td>" . $this->memberArray[$x][4] . "nm</td><td>$" . number_format($this->memberArray[$x][5], 2) . "</td></tr>"; } echo "</tbody></table>"; } /* --Display sortable Pilot stats table-- */ public function displayGroupStats() { echo "<table id=\"groupTable\" class=\"tablesorter\"><thead><tr><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>"; echo "<tr><td>" . $this->groupArray[0] . "</td><td>" . $this->formatTime($this-> groupArray[1]) . "</td><td>" . $this->groupArray[2] . "nm</td><td>$" . number_format($this->groupArray[3], 2) . "</td></tr> "; echo "</tbody></table>"; } /* --Display sortable Pilot stats table-- */ public function displayAircraftStats() { echo "<table id=\"aircraftTable\" class=\"tablesorter\"><thead><tr><th>Aircraft Registration</th><th>Make/Model</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>"; for ($x = 0; $x < count($this->aircraftArray); $x++) { echo "<tr><td>" . $this->aircraftArray[$x][0] . "</td><td>" . $this-> aircraftArray[$x][1] . "</td><td>" . $this->aircraftArray[$x][2] . "</td><td>" . $this->formatTime($this->aircraftArray[$x][3]) . "</td><td>" . $this-> aircraftArray[$x][4] . "nm</td><td>$" . number_format($this->aircraftArray[$x][5], 2) . "</td></tr>"; } echo "</tbody></table> "; } /* --Formats time-- */ public function formatTime($minutes) { $hours = floor($minutes / 60); $min = $minutes - ($hours * 60); $formattedTime = $hours . ":" . $min; return $formattedTime; } } ?>
Java
<?php /** * @file * The PHP page that serves all page requests on a Drupal installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All Drupal code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ /** * Root directory of Drupal installation. */ define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); menu_execute_active_handler();
Java
/* * This file contains work-arounds for many known PCI hardware * bugs. Devices present only on certain architectures (host * bridges et cetera) should be handled in arch-specific code. * * Note: any quirks for hotpluggable devices must _NOT_ be declared __init. * * Copyright (c) 1999 Martin Mares <mj@ucw.cz> * * Init/reset quirks for USB host controllers should be in the * USB quirks file, where their drivers can access reuse it. */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/export.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/acpi.h> #include <linux/kallsyms.h> #include <linux/dmi.h> #include <linux/pci-aspm.h> #include <linux/ioport.h> #include <linux/sched.h> #include <linux/ktime.h> #include <linux/mm.h> #include <asm/dma.h> /* isa_dma_bridge_buggy */ #include "pci.h" /* * Decoding should be disabled for a PCI device during BAR sizing to avoid * conflict. But doing so may cause problems on host bridge and perhaps other * key system devices. For devices that need to have mmio decoding always-on, * we need to set the dev->mmio_always_on bit. */ static void quirk_mmio_always_on(struct pci_dev *dev) { dev->mmio_always_on = 1; } DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_HOST, 8, quirk_mmio_always_on); /* The Mellanox Tavor device gives false positive parity errors * Mark this device with a broken_parity_status, to allow * PCI scanning code to "skip" this now blacklisted device. */ static void quirk_mellanox_tavor(struct pci_dev *dev) { dev->broken_parity_status = 1; /* This device gives false positives */ } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_DEVICE_ID_MELLANOX_TAVOR, quirk_mellanox_tavor); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_DEVICE_ID_MELLANOX_TAVOR_BRIDGE, quirk_mellanox_tavor); /* Deal with broken BIOSes that neglect to enable passive release, which can cause problems in combination with the 82441FX/PPro MTRRs */ static void quirk_passive_release(struct pci_dev *dev) { struct pci_dev *d = NULL; unsigned char dlc; /* We have to make sure a particular bit is set in the PIIX3 ISA bridge, so we have to go out and find it. */ while ((d = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_0, d))) { pci_read_config_byte(d, 0x82, &dlc); if (!(dlc & 1<<1)) { dev_info(&d->dev, "PIIX3: Enabling Passive Release\n"); dlc |= 1<<1; pci_write_config_byte(d, 0x82, dlc); } } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_passive_release); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_passive_release); /* The VIA VP2/VP3/MVP3 seem to have some 'features'. There may be a workaround but VIA don't answer queries. If you happen to have good contacts at VIA ask them for me please -- Alan This appears to be BIOS not version dependent. So presumably there is a chipset level fix */ static void quirk_isa_dma_hangs(struct pci_dev *dev) { if (!isa_dma_bridge_buggy) { isa_dma_bridge_buggy = 1; dev_info(&dev->dev, "Activating ISA DMA hang workarounds\n"); } } /* * Its not totally clear which chipsets are the problematic ones * We know 82C586 and 82C596 variants are affected. */ DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_0, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C596, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_0, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_1, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_2, quirk_isa_dma_hangs); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_3, quirk_isa_dma_hangs); /* * Intel NM10 "TigerPoint" LPC PM1a_STS.BM_STS must be clear * for some HT machines to use C4 w/o hanging. */ static void quirk_tigerpoint_bm_sts(struct pci_dev *dev) { u32 pmbase; u16 pm1a; pci_read_config_dword(dev, 0x40, &pmbase); pmbase = pmbase & 0xff80; pm1a = inw(pmbase); if (pm1a & 0x10) { dev_info(&dev->dev, FW_BUG "TigerPoint LPC.BM_STS cleared\n"); outw(0x10, pmbase); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_TGP_LPC, quirk_tigerpoint_bm_sts); /* * Chipsets where PCI->PCI transfers vanish or hang */ static void quirk_nopcipci(struct pci_dev *dev) { if ((pci_pci_problems & PCIPCI_FAIL) == 0) { dev_info(&dev->dev, "Disabling direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_FAIL; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_5597, quirk_nopcipci); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_496, quirk_nopcipci); static void quirk_nopciamd(struct pci_dev *dev) { u8 rev; pci_read_config_byte(dev, 0x08, &rev); if (rev == 0x13) { /* Erratum 24 */ dev_info(&dev->dev, "Chipset erratum: Disabling direct PCI/AGP transfers\n"); pci_pci_problems |= PCIAGP_FAIL; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8151_0, quirk_nopciamd); /* * Triton requires workarounds to be used by the drivers */ static void quirk_triton(struct pci_dev *dev) { if ((pci_pci_problems&PCIPCI_TRITON) == 0) { dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_TRITON; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437, quirk_triton); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437VX, quirk_triton); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82439, quirk_triton); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82439TX, quirk_triton); /* * VIA Apollo KT133 needs PCI latency patch * Made according to a windows driver based patch by George E. Breese * see PCI Latency Adjust on http://www.viahardware.com/download/viatweak.shtm * Also see http://www.au-ja.org/review-kt133a-1-en.phtml for * the info on which Mr Breese based his work. * * Updated based on further information from the site and also on * information provided by VIA */ static void quirk_vialatency(struct pci_dev *dev) { struct pci_dev *p; u8 busarb; /* Ok we have a potential problem chipset here. Now see if we have a buggy southbridge */ p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, NULL); if (p != NULL) { /* 0x40 - 0x4f == 686B, 0x10 - 0x2f == 686A; thanks Dan Hollis */ /* Check for buggy part revisions */ if (p->revision < 0x40 || p->revision > 0x42) goto exit; } else { p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231, NULL); if (p == NULL) /* No problem parts */ goto exit; /* Check for buggy part revisions */ if (p->revision < 0x10 || p->revision > 0x12) goto exit; } /* * Ok we have the problem. Now set the PCI master grant to * occur every master grant. The apparent bug is that under high * PCI load (quite common in Linux of course) you can get data * loss when the CPU is held off the bus for 3 bus master requests * This happens to include the IDE controllers.... * * VIA only apply this fix when an SB Live! is present but under * both Linux and Windows this isn't enough, and we have seen * corruption without SB Live! but with things like 3 UDMA IDE * controllers. So we ignore that bit of the VIA recommendation.. */ pci_read_config_byte(dev, 0x76, &busarb); /* Set bit 4 and bi 5 of byte 76 to 0x01 "Master priority rotation on every PCI master grant */ busarb &= ~(1<<5); busarb |= (1<<4); pci_write_config_byte(dev, 0x76, busarb); dev_info(&dev->dev, "Applying VIA southbridge workaround\n"); exit: pci_dev_put(p); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8363_0, quirk_vialatency); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8371_1, quirk_vialatency); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8361, quirk_vialatency); /* Must restore this on a resume from RAM */ DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8363_0, quirk_vialatency); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8371_1, quirk_vialatency); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8361, quirk_vialatency); /* * VIA Apollo VP3 needs ETBF on BT848/878 */ static void quirk_viaetbf(struct pci_dev *dev) { if ((pci_pci_problems&PCIPCI_VIAETBF) == 0) { dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_VIAETBF; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C597_0, quirk_viaetbf); static void quirk_vsfx(struct pci_dev *dev) { if ((pci_pci_problems&PCIPCI_VSFX) == 0) { dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_VSFX; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C576, quirk_vsfx); /* * Ali Magik requires workarounds to be used by the drivers * that DMA to AGP space. Latency must be set to 0xA and triton * workaround applied too * [Info kindly provided by ALi] */ static void quirk_alimagik(struct pci_dev *dev) { if ((pci_pci_problems&PCIPCI_ALIMAGIK) == 0) { dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_ALIMAGIK|PCIPCI_TRITON; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1647, quirk_alimagik); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1651, quirk_alimagik); /* * Natoma has some interesting boundary conditions with Zoran stuff * at least */ static void quirk_natoma(struct pci_dev *dev) { if ((pci_pci_problems&PCIPCI_NATOMA) == 0) { dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n"); pci_pci_problems |= PCIPCI_NATOMA; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_natoma); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443LX_0, quirk_natoma); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443LX_1, quirk_natoma); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_0, quirk_natoma); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_1, quirk_natoma); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_2, quirk_natoma); /* * This chip can cause PCI parity errors if config register 0xA0 is read * while DMAs are occurring. */ static void quirk_citrine(struct pci_dev *dev) { dev->cfg_size = 0xA0; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_CITRINE, quirk_citrine); /* * This chip can cause bus lockups if config addresses above 0x600 * are read or written. */ static void quirk_nfp6000(struct pci_dev *dev) { dev->cfg_size = 0x600; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP4000, quirk_nfp6000); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP6000, quirk_nfp6000); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP6000_VF, quirk_nfp6000); /* On IBM Crocodile ipr SAS adapters, expand BAR to system page size */ static void quirk_extend_bar_to_page(struct pci_dev *dev) { int i; for (i = 0; i < PCI_STD_RESOURCE_END; i++) { struct resource *r = &dev->resource[i]; if (r->flags & IORESOURCE_MEM && resource_size(r) < PAGE_SIZE) { r->end = PAGE_SIZE - 1; r->start = 0; r->flags |= IORESOURCE_UNSET; dev_info(&dev->dev, "expanded BAR %d to page size: %pR\n", i, r); } } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_IBM, 0x034a, quirk_extend_bar_to_page); /* * S3 868 and 968 chips report region size equal to 32M, but they decode 64M. * If it's needed, re-allocate the region. */ static void quirk_s3_64M(struct pci_dev *dev) { struct resource *r = &dev->resource[0]; if ((r->start & 0x3ffffff) || r->end != r->start + 0x3ffffff) { r->flags |= IORESOURCE_UNSET; r->start = 0; r->end = 0x3ffffff; } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_S3, PCI_DEVICE_ID_S3_868, quirk_s3_64M); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_S3, PCI_DEVICE_ID_S3_968, quirk_s3_64M); static void quirk_io(struct pci_dev *dev, int pos, unsigned size, const char *name) { u32 region; struct pci_bus_region bus_region; struct resource *res = dev->resource + pos; pci_read_config_dword(dev, PCI_BASE_ADDRESS_0 + (pos << 2), &region); if (!region) return; res->name = pci_name(dev); res->flags = region & ~PCI_BASE_ADDRESS_IO_MASK; res->flags |= (IORESOURCE_IO | IORESOURCE_PCI_FIXED | IORESOURCE_SIZEALIGN); region &= ~(size - 1); /* Convert from PCI bus to resource space */ bus_region.start = region; bus_region.end = region + size - 1; pcibios_bus_to_resource(dev->bus, res, &bus_region); dev_info(&dev->dev, FW_BUG "%s quirk: reg 0x%x: %pR\n", name, PCI_BASE_ADDRESS_0 + (pos << 2), res); } /* * Some CS5536 BIOSes (for example, the Soekris NET5501 board w/ comBIOS * ver. 1.33 20070103) don't set the correct ISA PCI region header info. * BAR0 should be 8 bytes; instead, it may be set to something like 8k * (which conflicts w/ BAR1's memory range). * * CS553x's ISA PCI BARs may also be read-only (ref: * https://bugzilla.kernel.org/show_bug.cgi?id=85991 - Comment #4 forward). */ static void quirk_cs5536_vsa(struct pci_dev *dev) { static char *name = "CS5536 ISA bridge"; if (pci_resource_len(dev, 0) != 8) { quirk_io(dev, 0, 8, name); /* SMB */ quirk_io(dev, 1, 256, name); /* GPIO */ quirk_io(dev, 2, 64, name); /* MFGPT */ dev_info(&dev->dev, "%s bug detected (incorrect header); workaround applied\n", name); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_ISA, quirk_cs5536_vsa); static void quirk_io_region(struct pci_dev *dev, int port, unsigned size, int nr, const char *name) { u16 region; struct pci_bus_region bus_region; struct resource *res = dev->resource + nr; pci_read_config_word(dev, port, &region); region &= ~(size - 1); if (!region) return; res->name = pci_name(dev); res->flags = IORESOURCE_IO; /* Convert from PCI bus to resource space */ bus_region.start = region; bus_region.end = region + size - 1; pcibios_bus_to_resource(dev->bus, res, &bus_region); if (!pci_claim_resource(dev, nr)) dev_info(&dev->dev, "quirk: %pR claimed by %s\n", res, name); } /* * ATI Northbridge setups MCE the processor if you even * read somewhere between 0x3b0->0x3bb or read 0x3d3 */ static void quirk_ati_exploding_mce(struct pci_dev *dev) { dev_info(&dev->dev, "ATI Northbridge, reserving I/O ports 0x3b0 to 0x3bb\n"); /* Mae rhaid i ni beidio ag edrych ar y lleoliadiau I/O hyn */ request_region(0x3b0, 0x0C, "RadeonIGP"); request_region(0x3d3, 0x01, "RadeonIGP"); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS100, quirk_ati_exploding_mce); /* * In the AMD NL platform, this device ([1022:7912]) has a class code of * PCI_CLASS_SERIAL_USB_XHCI (0x0c0330), which means the xhci driver will * claim it. * But the dwc3 driver is a more specific driver for this device, and we'd * prefer to use it instead of xhci. To prevent xhci from claiming the * device, change the class code to 0x0c03fe, which the PCI r3.0 spec * defines as "USB device (not host controller)". The dwc3 driver can then * claim it based on its Vendor and Device ID. */ static void quirk_amd_nl_class(struct pci_dev *pdev) { u32 class = pdev->class; /* Use "USB Device (not host controller)" class */ pdev->class = PCI_CLASS_SERIAL_USB_DEVICE; dev_info(&pdev->dev, "PCI class overridden (%#08x -> %#08x) so dwc3 driver can claim this instead of xhci\n", class, pdev->class); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_NL_USB, quirk_amd_nl_class); /* * Let's make the southbridge information explicit instead * of having to worry about people probing the ACPI areas, * for example.. (Yes, it happens, and if you read the wrong * ACPI register it will put the machine to sleep with no * way of waking it up again. Bummer). * * ALI M7101: Two IO regions pointed to by words at * 0xE0 (64 bytes of ACPI registers) * 0xE2 (32 bytes of SMB registers) */ static void quirk_ali7101_acpi(struct pci_dev *dev) { quirk_io_region(dev, 0xE0, 64, PCI_BRIDGE_RESOURCES, "ali7101 ACPI"); quirk_io_region(dev, 0xE2, 32, PCI_BRIDGE_RESOURCES+1, "ali7101 SMB"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M7101, quirk_ali7101_acpi); static void piix4_io_quirk(struct pci_dev *dev, const char *name, unsigned int port, unsigned int enable) { u32 devres; u32 mask, size, base; pci_read_config_dword(dev, port, &devres); if ((devres & enable) != enable) return; mask = (devres >> 16) & 15; base = devres & 0xffff; size = 16; for (;;) { unsigned bit = size >> 1; if ((bit & mask) == bit) break; size = bit; } /* * For now we only print it out. Eventually we'll want to * reserve it (at least if it's in the 0x1000+ range), but * let's get enough confirmation reports first. */ base &= -size; dev_info(&dev->dev, "%s PIO at %04x-%04x\n", name, base, base + size - 1); } static void piix4_mem_quirk(struct pci_dev *dev, const char *name, unsigned int port, unsigned int enable) { u32 devres; u32 mask, size, base; pci_read_config_dword(dev, port, &devres); if ((devres & enable) != enable) return; base = devres & 0xffff0000; mask = (devres & 0x3f) << 16; size = 128 << 16; for (;;) { unsigned bit = size >> 1; if ((bit & mask) == bit) break; size = bit; } /* * For now we only print it out. Eventually we'll want to * reserve it, but let's get enough confirmation reports first. */ base &= -size; dev_info(&dev->dev, "%s MMIO at %04x-%04x\n", name, base, base + size - 1); } /* * PIIX4 ACPI: Two IO regions pointed to by longwords at * 0x40 (64 bytes of ACPI registers) * 0x90 (16 bytes of SMB registers) * and a few strange programmable PIIX4 device resources. */ static void quirk_piix4_acpi(struct pci_dev *dev) { u32 res_a; quirk_io_region(dev, 0x40, 64, PCI_BRIDGE_RESOURCES, "PIIX4 ACPI"); quirk_io_region(dev, 0x90, 16, PCI_BRIDGE_RESOURCES+1, "PIIX4 SMB"); /* Device resource A has enables for some of the other ones */ pci_read_config_dword(dev, 0x5c, &res_a); piix4_io_quirk(dev, "PIIX4 devres B", 0x60, 3 << 21); piix4_io_quirk(dev, "PIIX4 devres C", 0x64, 3 << 21); /* Device resource D is just bitfields for static resources */ /* Device 12 enabled? */ if (res_a & (1 << 29)) { piix4_io_quirk(dev, "PIIX4 devres E", 0x68, 1 << 20); piix4_mem_quirk(dev, "PIIX4 devres F", 0x6c, 1 << 7); } /* Device 13 enabled? */ if (res_a & (1 << 30)) { piix4_io_quirk(dev, "PIIX4 devres G", 0x70, 1 << 20); piix4_mem_quirk(dev, "PIIX4 devres H", 0x74, 1 << 7); } piix4_io_quirk(dev, "PIIX4 devres I", 0x78, 1 << 20); piix4_io_quirk(dev, "PIIX4 devres J", 0x7c, 1 << 20); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3, quirk_piix4_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443MX_3, quirk_piix4_acpi); #define ICH_PMBASE 0x40 #define ICH_ACPI_CNTL 0x44 #define ICH4_ACPI_EN 0x10 #define ICH6_ACPI_EN 0x80 #define ICH4_GPIOBASE 0x58 #define ICH4_GPIO_CNTL 0x5c #define ICH4_GPIO_EN 0x10 #define ICH6_GPIOBASE 0x48 #define ICH6_GPIO_CNTL 0x4c #define ICH6_GPIO_EN 0x10 /* * ICH4, ICH4-M, ICH5, ICH5-M ACPI: Three IO regions pointed to by longwords at * 0x40 (128 bytes of ACPI, GPIO & TCO registers) * 0x58 (64 bytes of GPIO I/O space) */ static void quirk_ich4_lpc_acpi(struct pci_dev *dev) { u8 enable; /* * The check for PCIBIOS_MIN_IO is to ensure we won't create a conflict * with low legacy (and fixed) ports. We don't know the decoding * priority and can't tell whether the legacy device or the one created * here is really at that address. This happens on boards with broken * BIOSes. */ pci_read_config_byte(dev, ICH_ACPI_CNTL, &enable); if (enable & ICH4_ACPI_EN) quirk_io_region(dev, ICH_PMBASE, 128, PCI_BRIDGE_RESOURCES, "ICH4 ACPI/GPIO/TCO"); pci_read_config_byte(dev, ICH4_GPIO_CNTL, &enable); if (enable & ICH4_GPIO_EN) quirk_io_region(dev, ICH4_GPIOBASE, 64, PCI_BRIDGE_RESOURCES+1, "ICH4 GPIO"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_10, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, quirk_ich4_lpc_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_1, quirk_ich4_lpc_acpi); static void ich6_lpc_acpi_gpio(struct pci_dev *dev) { u8 enable; pci_read_config_byte(dev, ICH_ACPI_CNTL, &enable); if (enable & ICH6_ACPI_EN) quirk_io_region(dev, ICH_PMBASE, 128, PCI_BRIDGE_RESOURCES, "ICH6 ACPI/GPIO/TCO"); pci_read_config_byte(dev, ICH6_GPIO_CNTL, &enable); if (enable & ICH6_GPIO_EN) quirk_io_region(dev, ICH6_GPIOBASE, 64, PCI_BRIDGE_RESOURCES+1, "ICH6 GPIO"); } static void ich6_lpc_generic_decode(struct pci_dev *dev, unsigned reg, const char *name, int dynsize) { u32 val; u32 size, base; pci_read_config_dword(dev, reg, &val); /* Enabled? */ if (!(val & 1)) return; base = val & 0xfffc; if (dynsize) { /* * This is not correct. It is 16, 32 or 64 bytes depending on * register D31:F0:ADh bits 5:4. * * But this gets us at least _part_ of it. */ size = 16; } else { size = 128; } base &= ~(size-1); /* Just print it out for now. We should reserve it after more debugging */ dev_info(&dev->dev, "%s PIO at %04x-%04x\n", name, base, base+size-1); } static void quirk_ich6_lpc(struct pci_dev *dev) { /* Shared ACPI/GPIO decode with all ICH6+ */ ich6_lpc_acpi_gpio(dev); /* ICH6-specific generic IO decode */ ich6_lpc_generic_decode(dev, 0x84, "LPC Generic IO decode 1", 0); ich6_lpc_generic_decode(dev, 0x88, "LPC Generic IO decode 2", 1); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_0, quirk_ich6_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, quirk_ich6_lpc); static void ich7_lpc_generic_decode(struct pci_dev *dev, unsigned reg, const char *name) { u32 val; u32 mask, base; pci_read_config_dword(dev, reg, &val); /* Enabled? */ if (!(val & 1)) return; /* * IO base in bits 15:2, mask in bits 23:18, both * are dword-based */ base = val & 0xfffc; mask = (val >> 16) & 0xfc; mask |= 3; /* Just print it out for now. We should reserve it after more debugging */ dev_info(&dev->dev, "%s PIO at %04x (mask %04x)\n", name, base, mask); } /* ICH7-10 has the same common LPC generic IO decode registers */ static void quirk_ich7_lpc(struct pci_dev *dev) { /* We share the common ACPI/GPIO decode with ICH6 */ ich6_lpc_acpi_gpio(dev); /* And have 4 ICH7+ generic decodes */ ich7_lpc_generic_decode(dev, 0x84, "ICH7 LPC Generic IO decode 1"); ich7_lpc_generic_decode(dev, 0x88, "ICH7 LPC Generic IO decode 2"); ich7_lpc_generic_decode(dev, 0x8c, "ICH7 LPC Generic IO decode 3"); ich7_lpc_generic_decode(dev, 0x90, "ICH7 LPC Generic IO decode 4"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_0, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_1, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_31, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_0, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_2, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_3, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_1, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_4, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_2, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_4, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_7, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_8, quirk_ich7_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH10_1, quirk_ich7_lpc); /* * VIA ACPI: One IO region pointed to by longword at * 0x48 or 0x20 (256 bytes of ACPI registers) */ static void quirk_vt82c586_acpi(struct pci_dev *dev) { if (dev->revision & 0x10) quirk_io_region(dev, 0x48, 256, PCI_BRIDGE_RESOURCES, "vt82c586 ACPI"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_3, quirk_vt82c586_acpi); /* * VIA VT82C686 ACPI: Three IO region pointed to by (long)words at * 0x48 (256 bytes of ACPI registers) * 0x70 (128 bytes of hardware monitoring register) * 0x90 (16 bytes of SMB registers) */ static void quirk_vt82c686_acpi(struct pci_dev *dev) { quirk_vt82c586_acpi(dev); quirk_io_region(dev, 0x70, 128, PCI_BRIDGE_RESOURCES+1, "vt82c686 HW-mon"); quirk_io_region(dev, 0x90, 16, PCI_BRIDGE_RESOURCES+2, "vt82c686 SMB"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4, quirk_vt82c686_acpi); /* * VIA VT8235 ISA Bridge: Two IO regions pointed to by words at * 0x88 (128 bytes of power management registers) * 0xd0 (16 bytes of SMB registers) */ static void quirk_vt8235_acpi(struct pci_dev *dev) { quirk_io_region(dev, 0x88, 128, PCI_BRIDGE_RESOURCES, "vt8235 PM"); quirk_io_region(dev, 0xd0, 16, PCI_BRIDGE_RESOURCES+1, "vt8235 SMB"); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235, quirk_vt8235_acpi); /* * TI XIO2000a PCIe-PCI Bridge erroneously reports it supports fast back-to-back: * Disable fast back-to-back on the secondary bus segment */ static void quirk_xio2000a(struct pci_dev *dev) { struct pci_dev *pdev; u16 command; dev_warn(&dev->dev, "TI XIO2000a quirk detected; secondary bus fast back-to-back transfers disabled\n"); list_for_each_entry(pdev, &dev->subordinate->devices, bus_list) { pci_read_config_word(pdev, PCI_COMMAND, &command); if (command & PCI_COMMAND_FAST_BACK) pci_write_config_word(pdev, PCI_COMMAND, command & ~PCI_COMMAND_FAST_BACK); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_XIO2000A, quirk_xio2000a); #ifdef CONFIG_X86_IO_APIC #include <asm/io_apic.h> /* * VIA 686A/B: If an IO-APIC is active, we need to route all on-chip * devices to the external APIC. * * TODO: When we have device-specific interrupt routers, * this code will go away from quirks. */ static void quirk_via_ioapic(struct pci_dev *dev) { u8 tmp; if (nr_ioapics < 1) tmp = 0; /* nothing routed to external APIC */ else tmp = 0x1f; /* all known bits (4-0) routed to external APIC */ dev_info(&dev->dev, "%sbling VIA external APIC routing\n", tmp == 0 ? "Disa" : "Ena"); /* Offset 0x58: External APIC IRQ output control */ pci_write_config_byte(dev, 0x58, tmp); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_ioapic); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_ioapic); /* * VIA 8237: Some BIOSes don't set the 'Bypass APIC De-Assert Message' Bit. * This leads to doubled level interrupt rates. * Set this bit to get rid of cycle wastage. * Otherwise uncritical. */ static void quirk_via_vt8237_bypass_apic_deassert(struct pci_dev *dev) { u8 misc_control2; #define BYPASS_APIC_DEASSERT 8 pci_read_config_byte(dev, 0x5B, &misc_control2); if (!(misc_control2 & BYPASS_APIC_DEASSERT)) { dev_info(&dev->dev, "Bypassing VIA 8237 APIC De-Assert Message\n"); pci_write_config_byte(dev, 0x5B, misc_control2|BYPASS_APIC_DEASSERT); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_vt8237_bypass_apic_deassert); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_vt8237_bypass_apic_deassert); /* * The AMD io apic can hang the box when an apic irq is masked. * We check all revs >= B0 (yet not in the pre production!) as the bug * is currently marked NoFix * * We have multiple reports of hangs with this chipset that went away with * noapic specified. For the moment we assume it's the erratum. We may be wrong * of course. However the advice is demonstrably good even if so.. */ static void quirk_amd_ioapic(struct pci_dev *dev) { if (dev->revision >= 0x02) { dev_warn(&dev->dev, "I/O APIC: AMD Erratum #22 may be present. In the event of instability try\n"); dev_warn(&dev->dev, " : booting with the \"noapic\" option\n"); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_7410, quirk_amd_ioapic); #endif /* CONFIG_X86_IO_APIC */ #if defined(CONFIG_ARM64) && defined(CONFIG_PCI_ATS) static void quirk_cavium_sriov_rnm_link(struct pci_dev *dev) { /* Fix for improper SRIOV configuration on Cavium cn88xx RNM device */ if (dev->subsystem_device == 0xa118) dev->sriov->link = dev->devfn; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CAVIUM, 0xa018, quirk_cavium_sriov_rnm_link); #endif /* * Some settings of MMRBC can lead to data corruption so block changes. * See AMD 8131 HyperTransport PCI-X Tunnel Revision Guide */ static void quirk_amd_8131_mmrbc(struct pci_dev *dev) { if (dev->subordinate && dev->revision <= 0x12) { dev_info(&dev->dev, "AMD8131 rev %x detected; disabling PCI-X MMRBC\n", dev->revision); dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MMRBC; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_amd_8131_mmrbc); /* * FIXME: it is questionable that quirk_via_acpi * is needed. It shows up as an ISA bridge, and does not * support the PCI_INTERRUPT_LINE register at all. Therefore * it seems like setting the pci_dev's 'irq' to the * value of the ACPI SCI interrupt is only done for convenience. * -jgarzik */ static void quirk_via_acpi(struct pci_dev *d) { /* * VIA ACPI device: SCI IRQ line in PCI config byte 0x42 */ u8 irq; pci_read_config_byte(d, 0x42, &irq); irq &= 0xf; if (irq && (irq != 2)) d->irq = irq; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_3, quirk_via_acpi); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4, quirk_via_acpi); /* * VIA bridges which have VLink */ static int via_vlink_dev_lo = -1, via_vlink_dev_hi = 18; static void quirk_via_bridge(struct pci_dev *dev) { /* See what bridge we have and find the device ranges */ switch (dev->device) { case PCI_DEVICE_ID_VIA_82C686: /* The VT82C686 is special, it attaches to PCI and can have any device number. All its subdevices are functions of that single device. */ via_vlink_dev_lo = PCI_SLOT(dev->devfn); via_vlink_dev_hi = PCI_SLOT(dev->devfn); break; case PCI_DEVICE_ID_VIA_8237: case PCI_DEVICE_ID_VIA_8237A: via_vlink_dev_lo = 15; break; case PCI_DEVICE_ID_VIA_8235: via_vlink_dev_lo = 16; break; case PCI_DEVICE_ID_VIA_8231: case PCI_DEVICE_ID_VIA_8233_0: case PCI_DEVICE_ID_VIA_8233A: case PCI_DEVICE_ID_VIA_8233C_0: via_vlink_dev_lo = 17; break; } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233_0, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233A, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233C_0, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237A, quirk_via_bridge); /** * quirk_via_vlink - VIA VLink IRQ number update * @dev: PCI device * * If the device we are dealing with is on a PIC IRQ we need to * ensure that the IRQ line register which usually is not relevant * for PCI cards, is actually written so that interrupts get sent * to the right place. * We only do this on systems where a VIA south bridge was detected, * and only for VIA devices on the motherboard (see quirk_via_bridge * above). */ static void quirk_via_vlink(struct pci_dev *dev) { u8 irq, new_irq; /* Check if we have VLink at all */ if (via_vlink_dev_lo == -1) return; new_irq = dev->irq; /* Don't quirk interrupts outside the legacy IRQ range */ if (!new_irq || new_irq > 15) return; /* Internal device ? */ if (dev->bus->number != 0 || PCI_SLOT(dev->devfn) > via_vlink_dev_hi || PCI_SLOT(dev->devfn) < via_vlink_dev_lo) return; /* This is an internal VLink device on a PIC interrupt. The BIOS ought to have set this but may not have, so we redo it */ pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq); if (new_irq != irq) { dev_info(&dev->dev, "VIA VLink IRQ fixup, from %d to %d\n", irq, new_irq); udelay(15); /* unknown if delay really needed */ pci_write_config_byte(dev, PCI_INTERRUPT_LINE, new_irq); } } DECLARE_PCI_FIXUP_ENABLE(PCI_VENDOR_ID_VIA, PCI_ANY_ID, quirk_via_vlink); /* * VIA VT82C598 has its device ID settable and many BIOSes * set it to the ID of VT82C597 for backward compatibility. * We need to switch it off to be able to recognize the real * type of the chip. */ static void quirk_vt82c598_id(struct pci_dev *dev) { pci_write_config_byte(dev, 0xfc, 0); pci_read_config_word(dev, PCI_DEVICE_ID, &dev->device); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C597_0, quirk_vt82c598_id); /* * CardBus controllers have a legacy base address that enables them * to respond as i82365 pcmcia controllers. We don't want them to * do this even if the Linux CardBus driver is not loaded, because * the Linux i82365 driver does not (and should not) handle CardBus. */ static void quirk_cardbus_legacy(struct pci_dev *dev) { pci_write_config_dword(dev, PCI_CB_LEGACY_MODE_BASE, 0); } DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_CARDBUS, 8, quirk_cardbus_legacy); DECLARE_PCI_FIXUP_CLASS_RESUME_EARLY(PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_CARDBUS, 8, quirk_cardbus_legacy); /* * Following the PCI ordering rules is optional on the AMD762. I'm not * sure what the designers were smoking but let's not inhale... * * To be fair to AMD, it follows the spec by default, its BIOS people * who turn it off! */ static void quirk_amd_ordering(struct pci_dev *dev) { u32 pcic; pci_read_config_dword(dev, 0x4C, &pcic); if ((pcic & 6) != 6) { pcic |= 6; dev_warn(&dev->dev, "BIOS failed to enable PCI standards compliance; fixing this error\n"); pci_write_config_dword(dev, 0x4C, pcic); pci_read_config_dword(dev, 0x84, &pcic); pcic |= (1 << 23); /* Required in this mode */ pci_write_config_dword(dev, 0x84, pcic); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C, quirk_amd_ordering); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C, quirk_amd_ordering); /* * DreamWorks provided workaround for Dunord I-3000 problem * * This card decodes and responds to addresses not apparently * assigned to it. We force a larger allocation to ensure that * nothing gets put too close to it. */ static void quirk_dunord(struct pci_dev *dev) { struct resource *r = &dev->resource[1]; r->flags |= IORESOURCE_UNSET; r->start = 0; r->end = 0xffffff; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_DUNORD, PCI_DEVICE_ID_DUNORD_I3000, quirk_dunord); /* * i82380FB mobile docking controller: its PCI-to-PCI bridge * is subtractive decoding (transparent), and does indicate this * in the ProgIf. Unfortunately, the ProgIf value is wrong - 0x80 * instead of 0x01. */ static void quirk_transparent_bridge(struct pci_dev *dev) { dev->transparent = 1; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82380FB, quirk_transparent_bridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TOSHIBA, 0x605, quirk_transparent_bridge); /* * Common misconfiguration of the MediaGX/Geode PCI master that will * reduce PCI bandwidth from 70MB/s to 25MB/s. See the GXM/GXLV/GX1 * datasheets found at http://www.national.com/analog for info on what * these bits do. <christer@weinigel.se> */ static void quirk_mediagx_master(struct pci_dev *dev) { u8 reg; pci_read_config_byte(dev, 0x41, &reg); if (reg & 2) { reg &= ~2; dev_info(&dev->dev, "Fixup for MediaGX/Geode Slave Disconnect Boundary (0x41=0x%02x)\n", reg); pci_write_config_byte(dev, 0x41, reg); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_PCI_MASTER, quirk_mediagx_master); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_PCI_MASTER, quirk_mediagx_master); /* * Ensure C0 rev restreaming is off. This is normally done by * the BIOS but in the odd case it is not the results are corruption * hence the presence of a Linux check */ static void quirk_disable_pxb(struct pci_dev *pdev) { u16 config; if (pdev->revision != 0x04) /* Only C0 requires this */ return; pci_read_config_word(pdev, 0x40, &config); if (config & (1<<6)) { config &= ~(1<<6); pci_write_config_word(pdev, 0x40, config); dev_info(&pdev->dev, "C0 revision 450NX. Disabling PCI restreaming\n"); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82454NX, quirk_disable_pxb); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82454NX, quirk_disable_pxb); static void quirk_amd_ide_mode(struct pci_dev *pdev) { /* set SBX00/Hudson-2 SATA in IDE mode to AHCI mode */ u8 tmp; pci_read_config_byte(pdev, PCI_CLASS_DEVICE, &tmp); if (tmp == 0x01) { pci_read_config_byte(pdev, 0x40, &tmp); pci_write_config_byte(pdev, 0x40, tmp|1); pci_write_config_byte(pdev, 0x9, 1); pci_write_config_byte(pdev, 0xa, 6); pci_write_config_byte(pdev, 0x40, tmp); pdev->class = PCI_CLASS_STORAGE_SATA_AHCI; dev_info(&pdev->dev, "set SATA to AHCI mode\n"); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP600_SATA, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP600_SATA, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP700_SATA, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP700_SATA, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_HUDSON2_SATA_IDE, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_HUDSON2_SATA_IDE, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, 0x7900, quirk_amd_ide_mode); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, 0x7900, quirk_amd_ide_mode); /* * Serverworks CSB5 IDE does not fully support native mode */ static void quirk_svwks_csb5ide(struct pci_dev *pdev) { u8 prog; pci_read_config_byte(pdev, PCI_CLASS_PROG, &prog); if (prog & 5) { prog &= ~5; pdev->class &= ~5; pci_write_config_byte(pdev, PCI_CLASS_PROG, prog); /* PCI layer will sort out resources */ } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_CSB5IDE, quirk_svwks_csb5ide); /* * Intel 82801CAM ICH3-M datasheet says IDE modes must be the same */ static void quirk_ide_samemode(struct pci_dev *pdev) { u8 prog; pci_read_config_byte(pdev, PCI_CLASS_PROG, &prog); if (((prog & 1) && !(prog & 4)) || ((prog & 4) && !(prog & 1))) { dev_info(&pdev->dev, "IDE mode mismatch; forcing legacy mode\n"); prog &= ~5; pdev->class &= ~5; pci_write_config_byte(pdev, PCI_CLASS_PROG, prog); } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_10, quirk_ide_samemode); /* * Some ATA devices break if put into D3 */ static void quirk_no_ata_d3(struct pci_dev *pdev) { pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; } /* Quirk the legacy ATA devices only. The AHCI ones are ok */ DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_SERVERWORKS, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3); DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_ATI, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3); /* ALi loses some register settings that we cannot then restore */ DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_AL, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3); /* VIA comes back fine but we need to keep it alive or ACPI GTM failures occur when mode detecting */ DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_VIA, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3); /* This was originally an Alpha specific thing, but it really fits here. * The i82375 PCI/EISA bridge appears as non-classified. Fix that. */ static void quirk_eisa_bridge(struct pci_dev *dev) { dev->class = PCI_CLASS_BRIDGE_EISA << 8; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82375, quirk_eisa_bridge); /* * On ASUS P4B boards, the SMBus PCI Device within the ICH2/4 southbridge * is not activated. The myth is that Asus said that they do not want the * users to be irritated by just another PCI Device in the Win98 device * manager. (see the file prog/hotplug/README.p4b in the lm_sensors * package 2.7.0 for details) * * The SMBus PCI Device can be activated by setting a bit in the ICH LPC * bridge. Unfortunately, this device has no subvendor/subdevice ID. So it * becomes necessary to do this tweak in two steps -- the chosen trigger * is either the Host bridge (preferred) or on-board VGA controller. * * Note that we used to unhide the SMBus that way on Toshiba laptops * (Satellite A40 and Tecra M2) but then found that the thermal management * was done by SMM code, which could cause unsynchronized concurrent * accesses to the SMBus registers, with potentially bad effects. Thus you * should be very careful when adding new entries: if SMM is accessing the * Intel SMBus, this is a very good reason to leave it hidden. * * Likewise, many recent laptops use ACPI for thermal management. If the * ACPI DSDT code accesses the SMBus, then Linux should not access it * natively, and keeping the SMBus hidden is the right thing to do. If you * are about to add an entry in the table below, please first disassemble * the DSDT and double-check that there is no code accessing the SMBus. */ static int asus_hides_smbus; static void asus_hides_smbus_hostbridge(struct pci_dev *dev) { if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_ASUSTEK)) { if (dev->device == PCI_DEVICE_ID_INTEL_82845_HB) switch (dev->subsystem_device) { case 0x8025: /* P4B-LX */ case 0x8070: /* P4B */ case 0x8088: /* P4B533 */ case 0x1626: /* L3C notebook */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82845G_HB) switch (dev->subsystem_device) { case 0x80b1: /* P4GE-V */ case 0x80b2: /* P4PE */ case 0x8093: /* P4B533-V */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82850_HB) switch (dev->subsystem_device) { case 0x8030: /* P4T533 */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_7205_0) switch (dev->subsystem_device) { case 0x8070: /* P4G8X Deluxe */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_E7501_MCH) switch (dev->subsystem_device) { case 0x80c9: /* PU-DLS */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82855GM_HB) switch (dev->subsystem_device) { case 0x1751: /* M2N notebook */ case 0x1821: /* M5N notebook */ case 0x1897: /* A6L notebook */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB) switch (dev->subsystem_device) { case 0x184b: /* W1N notebook */ case 0x186a: /* M6Ne notebook */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82865_HB) switch (dev->subsystem_device) { case 0x80f2: /* P4P800-X */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82915GM_HB) switch (dev->subsystem_device) { case 0x1882: /* M6V notebook */ case 0x1977: /* A6VA notebook */ asus_hides_smbus = 1; } } else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_HP)) { if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB) switch (dev->subsystem_device) { case 0x088C: /* HP Compaq nc8000 */ case 0x0890: /* HP Compaq nc6000 */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82865_HB) switch (dev->subsystem_device) { case 0x12bc: /* HP D330L */ case 0x12bd: /* HP D530 */ case 0x006a: /* HP Compaq nx9500 */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82875_HB) switch (dev->subsystem_device) { case 0x12bf: /* HP xw4100 */ asus_hides_smbus = 1; } } else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_SAMSUNG)) { if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB) switch (dev->subsystem_device) { case 0xC00C: /* Samsung P35 notebook */ asus_hides_smbus = 1; } } else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_COMPAQ)) { if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB) switch (dev->subsystem_device) { case 0x0058: /* Compaq Evo N620c */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82810_IG3) switch (dev->subsystem_device) { case 0xB16C: /* Compaq Deskpro EP 401963-001 (PCA# 010174) */ /* Motherboard doesn't have Host bridge * subvendor/subdevice IDs, therefore checking * its on-board VGA controller */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82801DB_2) switch (dev->subsystem_device) { case 0x00b8: /* Compaq Evo D510 CMT */ case 0x00b9: /* Compaq Evo D510 SFF */ case 0x00ba: /* Compaq Evo D510 USDT */ /* Motherboard doesn't have Host bridge * subvendor/subdevice IDs and on-board VGA * controller is disabled if an AGP card is * inserted, therefore checking USB UHCI * Controller #1 */ asus_hides_smbus = 1; } else if (dev->device == PCI_DEVICE_ID_INTEL_82815_CGC) switch (dev->subsystem_device) { case 0x001A: /* Compaq Deskpro EN SSF P667 815E */ /* Motherboard doesn't have host bridge * subvendor/subdevice IDs, therefore checking * its on-board VGA controller */ asus_hides_smbus = 1; } } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82845_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82845G_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82850_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82865_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82875_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_7205_0, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7501_MCH, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82855PM_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82855GM_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82915GM_HB, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82810_IG3, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_2, asus_hides_smbus_hostbridge); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82815_CGC, asus_hides_smbus_hostbridge); static void asus_hides_smbus_lpc(struct pci_dev *dev) { u16 val; if (likely(!asus_hides_smbus)) return; pci_read_config_word(dev, 0xF2, &val); if (val & 0x8) { pci_write_config_word(dev, 0xF2, val & (~0x8)); pci_read_config_word(dev, 0xF2, &val); if (val & 0x8) dev_info(&dev->dev, "i801 SMBus device continues to play 'hide and seek'! 0x%x\n", val); else dev_info(&dev->dev, "Enabled i801 SMBus device\n"); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, asus_hides_smbus_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, asus_hides_smbus_lpc); /* It appears we just have one such device. If not, we have a warning */ static void __iomem *asus_rcba_base; static void asus_hides_smbus_lpc_ich6_suspend(struct pci_dev *dev) { u32 rcba; if (likely(!asus_hides_smbus)) return; WARN_ON(asus_rcba_base); pci_read_config_dword(dev, 0xF0, &rcba); /* use bits 31:14, 16 kB aligned */ asus_rcba_base = ioremap_nocache(rcba & 0xFFFFC000, 0x4000); if (asus_rcba_base == NULL) return; } static void asus_hides_smbus_lpc_ich6_resume_early(struct pci_dev *dev) { u32 val; if (likely(!asus_hides_smbus || !asus_rcba_base)) return; /* read the Function Disable register, dword mode only */ val = readl(asus_rcba_base + 0x3418); writel(val & 0xFFFFFFF7, asus_rcba_base + 0x3418); /* enable the SMBus device */ } static void asus_hides_smbus_lpc_ich6_resume(struct pci_dev *dev) { if (likely(!asus_hides_smbus || !asus_rcba_base)) return; iounmap(asus_rcba_base); asus_rcba_base = NULL; dev_info(&dev->dev, "Enabled ICH6/i801 SMBus device\n"); } static void asus_hides_smbus_lpc_ich6(struct pci_dev *dev) { asus_hides_smbus_lpc_ich6_suspend(dev); asus_hides_smbus_lpc_ich6_resume_early(dev); asus_hides_smbus_lpc_ich6_resume(dev); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6); DECLARE_PCI_FIXUP_SUSPEND(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_suspend); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_resume); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_resume_early); /* * SiS 96x south bridge: BIOS typically hides SMBus device... */ static void quirk_sis_96x_smbus(struct pci_dev *dev) { u8 val = 0; pci_read_config_byte(dev, 0x77, &val); if (val & 0x10) { dev_info(&dev->dev, "Enabling SiS 96x SMBus\n"); pci_write_config_byte(dev, 0x77, val & ~0x10); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_961, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_962, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_963, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_LPC, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_961, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_962, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_963, quirk_sis_96x_smbus); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_LPC, quirk_sis_96x_smbus); /* * ... This is further complicated by the fact that some SiS96x south * bridges pretend to be 85C503/5513 instead. In that case see if we * spotted a compatible north bridge to make sure. * (pci_find_device doesn't work yet) * * We can also enable the sis96x bit in the discovery register.. */ #define SIS_DETECT_REGISTER 0x40 static void quirk_sis_503(struct pci_dev *dev) { u8 reg; u16 devid; pci_read_config_byte(dev, SIS_DETECT_REGISTER, &reg); pci_write_config_byte(dev, SIS_DETECT_REGISTER, reg | (1 << 6)); pci_read_config_word(dev, PCI_DEVICE_ID, &devid); if (((devid & 0xfff0) != 0x0960) && (devid != 0x0018)) { pci_write_config_byte(dev, SIS_DETECT_REGISTER, reg); return; } /* * Ok, it now shows up as a 96x.. run the 96x quirk by * hand in case it has already been processed. * (depends on link order, which is apparently not guaranteed) */ dev->device = devid; quirk_sis_96x_smbus(dev); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503, quirk_sis_503); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503, quirk_sis_503); /* * On ASUS A8V and A8V Deluxe boards, the onboard AC97 audio controller * and MC97 modem controller are disabled when a second PCI soundcard is * present. This patch, tweaking the VT8237 ISA bridge, enables them. * -- bjd */ static void asus_hides_ac97_lpc(struct pci_dev *dev) { u8 val; int asus_hides_ac97 = 0; if (likely(dev->subsystem_vendor == PCI_VENDOR_ID_ASUSTEK)) { if (dev->device == PCI_DEVICE_ID_VIA_8237) asus_hides_ac97 = 1; } if (!asus_hides_ac97) return; pci_read_config_byte(dev, 0x50, &val); if (val & 0xc0) { pci_write_config_byte(dev, 0x50, val & (~0xc0)); pci_read_config_byte(dev, 0x50, &val); if (val & 0xc0) dev_info(&dev->dev, "Onboard AC97/MC97 devices continue to play 'hide and seek'! 0x%x\n", val); else dev_info(&dev->dev, "Enabled onboard AC97/MC97 devices\n"); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, asus_hides_ac97_lpc); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, asus_hides_ac97_lpc); #if defined(CONFIG_ATA) || defined(CONFIG_ATA_MODULE) /* * If we are using libata we can drive this chip properly but must * do this early on to make the additional device appear during * the PCI scanning. */ static void quirk_jmicron_ata(struct pci_dev *pdev) { u32 conf1, conf5, class; u8 hdr; /* Only poke fn 0 */ if (PCI_FUNC(pdev->devfn)) return; pci_read_config_dword(pdev, 0x40, &conf1); pci_read_config_dword(pdev, 0x80, &conf5); conf1 &= ~0x00CFF302; /* Clear bit 1, 8, 9, 12-19, 22, 23 */ conf5 &= ~(1 << 24); /* Clear bit 24 */ switch (pdev->device) { case PCI_DEVICE_ID_JMICRON_JMB360: /* SATA single port */ case PCI_DEVICE_ID_JMICRON_JMB362: /* SATA dual ports */ case PCI_DEVICE_ID_JMICRON_JMB364: /* SATA dual ports */ /* The controller should be in single function ahci mode */ conf1 |= 0x0002A100; /* Set 8, 13, 15, 17 */ break; case PCI_DEVICE_ID_JMICRON_JMB365: case PCI_DEVICE_ID_JMICRON_JMB366: /* Redirect IDE second PATA port to the right spot */ conf5 |= (1 << 24); /* Fall through */ case PCI_DEVICE_ID_JMICRON_JMB361: case PCI_DEVICE_ID_JMICRON_JMB363: case PCI_DEVICE_ID_JMICRON_JMB369: /* Enable dual function mode, AHCI on fn 0, IDE fn1 */ /* Set the class codes correctly and then direct IDE 0 */ conf1 |= 0x00C2A1B3; /* Set 0, 1, 4, 5, 7, 8, 13, 15, 17, 22, 23 */ break; case PCI_DEVICE_ID_JMICRON_JMB368: /* The controller should be in single function IDE mode */ conf1 |= 0x00C00000; /* Set 22, 23 */ break; } pci_write_config_dword(pdev, 0x40, conf1); pci_write_config_dword(pdev, 0x80, conf5); /* Update pdev accordingly */ pci_read_config_byte(pdev, PCI_HEADER_TYPE, &hdr); pdev->hdr_type = hdr & 0x7f; pdev->multifunction = !!(hdr & 0x80); pci_read_config_dword(pdev, PCI_CLASS_REVISION, &class); pdev->class = class >> 8; } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB360, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB361, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB362, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB363, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB364, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB365, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB366, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB368, quirk_jmicron_ata); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB369, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB360, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB361, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB362, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB363, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB364, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB365, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB366, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB368, quirk_jmicron_ata); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB369, quirk_jmicron_ata); #endif static void quirk_jmicron_async_suspend(struct pci_dev *dev) { if (dev->multifunction) { device_disable_async_suspend(&dev->dev); dev_info(&dev->dev, "async suspend disabled to avoid multi-function power-on ordering issue\n"); } } DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_JMICRON, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_jmicron_async_suspend); DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_JMICRON, PCI_ANY_ID, PCI_CLASS_STORAGE_SATA_AHCI, 0, quirk_jmicron_async_suspend); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_JMICRON, 0x2362, quirk_jmicron_async_suspend); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_JMICRON, 0x236f, quirk_jmicron_async_suspend); #ifdef CONFIG_X86_IO_APIC static void quirk_alder_ioapic(struct pci_dev *pdev) { int i; if ((pdev->class >> 8) != 0xff00) return; /* the first BAR is the location of the IO APIC...we must * not touch this (and it's already covered by the fixmap), so * forcibly insert it into the resource tree */ if (pci_resource_start(pdev, 0) && pci_resource_len(pdev, 0)) insert_resource(&iomem_resource, &pdev->resource[0]); /* The next five BARs all seem to be rubbish, so just clean * them out */ for (i = 1; i < 6; i++) memset(&pdev->resource[i], 0, sizeof(pdev->resource[i])); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EESSC, quirk_alder_ioapic); #endif static void quirk_pcie_mch(struct pci_dev *pdev) { pdev->no_msi = 1; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7520_MCH, quirk_pcie_mch); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7320_MCH, quirk_pcie_mch); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7525_MCH, quirk_pcie_mch); /* * It's possible for the MSI to get corrupted if shpc and acpi * are used together on certain PXH-based systems. */ static void quirk_pcie_pxh(struct pci_dev *dev) { dev->no_msi = 1; dev_warn(&dev->dev, "PXH quirk detected; SHPC device MSI disabled\n"); } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHD_0, quirk_pcie_pxh); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHD_1, quirk_pcie_pxh); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_pcie_pxh); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_pcie_pxh); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_pcie_pxh); /* * Some Intel PCI Express chipsets have trouble with downstream * device power management. */ static void quirk_intel_pcie_pm(struct pci_dev *dev) { pci_pm_d3_delay = 120; dev->no_d1d2 = 1; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e2, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e3, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e4, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e5, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e6, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e7, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f7, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f8, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f9, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25fa, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2601, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2602, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2603, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2604, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2605, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2606, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2607, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2608, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2609, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x260a, quirk_intel_pcie_pm); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x260b, quirk_intel_pcie_pm); #ifdef CONFIG_X86_IO_APIC /* * Boot interrupts on some chipsets cannot be turned off. For these chipsets, * remap the original interrupt in the linux kernel to the boot interrupt, so * that a PCI device's interrupt handler is installed on the boot interrupt * line instead. */ static void quirk_reroute_to_boot_interrupts_intel(struct pci_dev *dev) { if (noioapicquirk || noioapicreroute) return; dev->irq_reroute_variant = INTEL_IRQ_REROUTE_VARIANT; dev_info(&dev->dev, "rerouting interrupts for [%04x:%04x]\n", dev->vendor, dev->device); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_1, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB2_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_1, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_1, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB2_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_0, quirk_reroute_to_boot_interrupts_intel); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_1, quirk_reroute_to_boot_interrupts_intel); /* * On some chipsets we can disable the generation of legacy INTx boot * interrupts. */ /* * IO-APIC1 on 6300ESB generates boot interrupts, see intel order no * 300641-004US, section 5.7.3. */ #define INTEL_6300_IOAPIC_ABAR 0x40 #define INTEL_6300_DISABLE_BOOT_IRQ (1<<14) static void quirk_disable_intel_boot_interrupt(struct pci_dev *dev) { u16 pci_config_word; if (noioapicquirk) return; pci_read_config_word(dev, INTEL_6300_IOAPIC_ABAR, &pci_config_word); pci_config_word |= INTEL_6300_DISABLE_BOOT_IRQ; pci_write_config_word(dev, INTEL_6300_IOAPIC_ABAR, pci_config_word); dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n", dev->vendor, dev->device); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_10, quirk_disable_intel_boot_interrupt); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_10, quirk_disable_intel_boot_interrupt); /* * disable boot interrupts on HT-1000 */ #define BC_HT1000_FEATURE_REG 0x64 #define BC_HT1000_PIC_REGS_ENABLE (1<<0) #define BC_HT1000_MAP_IDX 0xC00 #define BC_HT1000_MAP_DATA 0xC01 static void quirk_disable_broadcom_boot_interrupt(struct pci_dev *dev) { u32 pci_config_dword; u8 irq; if (noioapicquirk) return; pci_read_config_dword(dev, BC_HT1000_FEATURE_REG, &pci_config_dword); pci_write_config_dword(dev, BC_HT1000_FEATURE_REG, pci_config_dword | BC_HT1000_PIC_REGS_ENABLE); for (irq = 0x10; irq < 0x10 + 32; irq++) { outb(irq, BC_HT1000_MAP_IDX); outb(0x00, BC_HT1000_MAP_DATA); } pci_write_config_dword(dev, BC_HT1000_FEATURE_REG, pci_config_dword); dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n", dev->vendor, dev->device); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000SB, quirk_disable_broadcom_boot_interrupt); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000SB, quirk_disable_broadcom_boot_interrupt); /* * disable boot interrupts on AMD and ATI chipsets */ /* * NOIOAMODE needs to be disabled to disable "boot interrupts". For AMD 8131 * rev. A0 and B0, NOIOAMODE needs to be disabled anyway to fix IO-APIC mode * (due to an erratum). */ #define AMD_813X_MISC 0x40 #define AMD_813X_NOIOAMODE (1<<0) #define AMD_813X_REV_B1 0x12 #define AMD_813X_REV_B2 0x13 static void quirk_disable_amd_813x_boot_interrupt(struct pci_dev *dev) { u32 pci_config_dword; if (noioapicquirk) return; if ((dev->revision == AMD_813X_REV_B1) || (dev->revision == AMD_813X_REV_B2)) return; pci_read_config_dword(dev, AMD_813X_MISC, &pci_config_dword); pci_config_dword &= ~AMD_813X_NOIOAMODE; pci_write_config_dword(dev, AMD_813X_MISC, pci_config_dword); dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n", dev->vendor, dev->device); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_amd_813x_boot_interrupt); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_amd_813x_boot_interrupt); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, quirk_disable_amd_813x_boot_interrupt); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, quirk_disable_amd_813x_boot_interrupt); #define AMD_8111_PCI_IRQ_ROUTING 0x56 static void quirk_disable_amd_8111_boot_interrupt(struct pci_dev *dev) { u16 pci_config_word; if (noioapicquirk) return; pci_read_config_word(dev, AMD_8111_PCI_IRQ_ROUTING, &pci_config_word); if (!pci_config_word) { dev_info(&dev->dev, "boot interrupts on device [%04x:%04x] already disabled\n", dev->vendor, dev->device); return; } pci_write_config_word(dev, AMD_8111_PCI_IRQ_ROUTING, 0); dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n", dev->vendor, dev->device); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS, quirk_disable_amd_8111_boot_interrupt); DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS, quirk_disable_amd_8111_boot_interrupt); #endif /* CONFIG_X86_IO_APIC */ /* * Toshiba TC86C001 IDE controller reports the standard 8-byte BAR0 size * but the PIO transfers won't work if BAR0 falls at the odd 8 bytes. * Re-allocate the region if needed... */ static void quirk_tc86c001_ide(struct pci_dev *dev) { struct resource *r = &dev->resource[0]; if (r->start & 0x8) { r->flags |= IORESOURCE_UNSET; r->start = 0; r->end = 0xf; } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TOSHIBA_2, PCI_DEVICE_ID_TOSHIBA_TC86C001_IDE, quirk_tc86c001_ide); /* * PLX PCI 9050 PCI Target bridge controller has an errata that prevents the * local configuration registers accessible via BAR0 (memory) or BAR1 (i/o) * being read correctly if bit 7 of the base address is set. * The BAR0 or BAR1 region may be disabled (size 0) or enabled (size 128). * Re-allocate the regions to a 256-byte boundary if necessary. */ static void quirk_plx_pci9050(struct pci_dev *dev) { unsigned int bar; /* Fixed in revision 2 (PCI 9052). */ if (dev->revision >= 2) return; for (bar = 0; bar <= 1; bar++) if (pci_resource_len(dev, bar) == 0x80 && (pci_resource_start(dev, bar) & 0x80)) { struct resource *r = &dev->resource[bar]; dev_info(&dev->dev, "Re-allocating PLX PCI 9050 BAR %u to length 256 to avoid bit 7 bug\n", bar); r->flags |= IORESOURCE_UNSET; r->start = 0; r->end = 0xff; } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050, quirk_plx_pci9050); /* * The following Meilhaus (vendor ID 0x1402) device IDs (amongst others) * may be using the PLX PCI 9050: 0x0630, 0x0940, 0x0950, 0x0960, 0x100b, * 0x1400, 0x140a, 0x140b, 0x14e0, 0x14ea, 0x14eb, 0x1604, 0x1608, 0x160c, * 0x168f, 0x2000, 0x2600, 0x3000, 0x810a, 0x810b. * * Currently, device IDs 0x2000 and 0x2600 are used by the Comedi "me_daq" * driver. */ DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2000, quirk_plx_pci9050); DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2600, quirk_plx_pci9050); static void quirk_netmos(struct pci_dev *dev) { unsigned int num_parallel = (dev->subsystem_device & 0xf0) >> 4; unsigned int num_serial = dev->subsystem_device & 0xf; /* * These Netmos parts are multiport serial devices with optional * parallel ports. Even when parallel ports are present, they * are identified as class SERIAL, which means the serial driver * will claim them. To prevent this, mark them as class OTHER. * These combo devices should be claimed by parport_serial. * * The subdevice ID is of the form 0x00PS, where <P> is the number * of parallel ports and <S> is the number of serial ports. */ switch (dev->device) { case PCI_DEVICE_ID_NETMOS_9835: /* Well, this rule doesn't hold for the following 9835 device */ if (dev->subsystem_vendor == PCI_VENDOR_ID_IBM && dev->subsystem_device == 0x0299) return; case PCI_DEVICE_ID_NETMOS_9735: case PCI_DEVICE_ID_NETMOS_9745: case PCI_DEVICE_ID_NETMOS_9845: case PCI_DEVICE_ID_NETMOS_9855: if (num_parallel) { dev_info(&dev->dev, "Netmos %04x (%u parallel, %u serial); changing class SERIAL to OTHER (use parport_serial)\n", dev->device, num_parallel, num_serial); dev->class = (PCI_CLASS_COMMUNICATION_OTHER << 8) | (dev->class & 0xff); } } } DECLARE_PCI_FIXUP_CLASS_HEADER(PCI_VENDOR_ID_NETMOS, PCI_ANY_ID, PCI_CLASS_COMMUNICATION_SERIAL, 8, quirk_netmos); /* * Quirk non-zero PCI functions to route VPD access through function 0 for * devices that share VPD resources between functions. The functions are * expected to be identical devices. */ static void quirk_f0_vpd_link(struct pci_dev *dev) { struct pci_dev *f0; if (!PCI_FUNC(dev->devfn)) return; f0 = pci_get_slot(dev->bus, PCI_DEVFN(PCI_SLOT(dev->devfn), 0)); if (!f0) return; if (f0->vpd && dev->class == f0->class && dev->vendor == f0->vendor && dev->device == f0->device) dev->dev_flags |= PCI_DEV_FLAGS_VPD_REF_F0; pci_dev_put(f0); } DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_INTEL, PCI_ANY_ID, PCI_CLASS_NETWORK_ETHERNET, 8, quirk_f0_vpd_link); static void quirk_e100_interrupt(struct pci_dev *dev) { u16 command, pmcsr; u8 __iomem *csr; u8 cmd_hi; switch (dev->device) { /* PCI IDs taken from drivers/net/e100.c */ case 0x1029: case 0x1030 ... 0x1034: case 0x1038 ... 0x103E: case 0x1050 ... 0x1057: case 0x1059: case 0x1064 ... 0x106B: case 0x1091 ... 0x1095: case 0x1209: case 0x1229: case 0x2449: case 0x2459: case 0x245D: case 0x27DC: break; default: return; } /* * Some firmware hands off the e100 with interrupts enabled, * which can cause a flood of interrupts if packets are * received before the driver attaches to the device. So * disable all e100 interrupts here. The driver will * re-enable them when it's ready. */ pci_read_config_word(dev, PCI_COMMAND, &command); if (!(command & PCI_COMMAND_MEMORY) || !pci_resource_start(dev, 0)) return; /* * Check that the device is in the D0 power state. If it's not, * there is no point to look any further. */ if (dev->pm_cap) { pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr); if ((pmcsr & PCI_PM_CTRL_STATE_MASK) != PCI_D0) return; } /* Convert from PCI bus to resource space. */ csr = ioremap(pci_resource_start(dev, 0), 8); if (!csr) { dev_warn(&dev->dev, "Can't map e100 registers\n"); return; } cmd_hi = readb(csr + 3); if (cmd_hi == 0) { dev_warn(&dev->dev, "Firmware left e100 interrupts enabled; disabling\n"); writeb(1, csr + 3); } iounmap(csr); } DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_INTEL, PCI_ANY_ID, PCI_CLASS_NETWORK_ETHERNET, 8, quirk_e100_interrupt); /* * The 82575 and 82598 may experience data corruption issues when transitioning * out of L0S. To prevent this we need to disable L0S on the pci-e link */ static void quirk_disable_aspm_l0s(struct pci_dev *dev) { dev_info(&dev->dev, "Disabling L0s\n"); pci_disable_link_state(dev, PCIE_LINK_STATE_L0S); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10a7, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10a9, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10b6, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c6, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c7, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c8, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10d6, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10db, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10dd, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10e1, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10ec, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10f1, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10f4, quirk_disable_aspm_l0s); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1508, quirk_disable_aspm_l0s); static void fixup_rev1_53c810(struct pci_dev *dev) { u32 class = dev->class; /* * rev 1 ncr53c810 chips don't set the class at all which means * they don't get their resources remapped. Fix that here. */ if (class) return; dev->class = PCI_CLASS_STORAGE_SCSI << 8; dev_info(&dev->dev, "NCR 53c810 rev 1 PCI class overridden (%#08x -> %#08x)\n", class, dev->class); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NCR, PCI_DEVICE_ID_NCR_53C810, fixup_rev1_53c810); /* Enable 1k I/O space granularity on the Intel P64H2 */ static void quirk_p64h2_1k_io(struct pci_dev *dev) { u16 en1k; pci_read_config_word(dev, 0x40, &en1k); if (en1k & 0x200) { dev_info(&dev->dev, "Enable I/O Space to 1KB granularity\n"); dev->io_window_1k = 1; } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1460, quirk_p64h2_1k_io); /* Under some circumstances, AER is not linked with extended capabilities. * Force it to be linked by setting the corresponding control bit in the * config space. */ static void quirk_nvidia_ck804_pcie_aer_ext_cap(struct pci_dev *dev) { uint8_t b; if (pci_read_config_byte(dev, 0xf41, &b) == 0) { if (!(b & 0x20)) { pci_write_config_byte(dev, 0xf41, b | 0x20); dev_info(&dev->dev, "Linking AER extended capability\n"); } } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE, quirk_nvidia_ck804_pcie_aer_ext_cap); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE, quirk_nvidia_ck804_pcie_aer_ext_cap); static void quirk_via_cx700_pci_parking_caching(struct pci_dev *dev) { /* * Disable PCI Bus Parking and PCI Master read caching on CX700 * which causes unspecified timing errors with a VT6212L on the PCI * bus leading to USB2.0 packet loss. * * This quirk is only enabled if a second (on the external PCI bus) * VT6212L is found -- the CX700 core itself also contains a USB * host controller with the same PCI ID as the VT6212L. */ /* Count VT6212L instances */ struct pci_dev *p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235_USB_2, NULL); uint8_t b; /* p should contain the first (internal) VT6212L -- see if we have an external one by searching again */ p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235_USB_2, p); if (!p) return; pci_dev_put(p); if (pci_read_config_byte(dev, 0x76, &b) == 0) { if (b & 0x40) { /* Turn off PCI Bus Parking */ pci_write_config_byte(dev, 0x76, b ^ 0x40); dev_info(&dev->dev, "Disabling VIA CX700 PCI parking\n"); } } if (pci_read_config_byte(dev, 0x72, &b) == 0) { if (b != 0) { /* Turn off PCI Master read caching */ pci_write_config_byte(dev, 0x72, 0x0); /* Set PCI Master Bus time-out to "1x16 PCLK" */ pci_write_config_byte(dev, 0x75, 0x1); /* Disable "Read FIFO Timer" */ pci_write_config_byte(dev, 0x77, 0x0); dev_info(&dev->dev, "Disabling VIA CX700 PCI caching\n"); } } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, 0x324e, quirk_via_cx700_pci_parking_caching); /* * If a device follows the VPD format spec, the PCI core will not read or * write past the VPD End Tag. But some vendors do not follow the VPD * format spec, so we can't tell how much data is safe to access. Devices * may behave unpredictably if we access too much. Blacklist these devices * so we don't touch VPD at all. */ static void quirk_blacklist_vpd(struct pci_dev *dev) { if (dev->vpd) { dev->vpd->len = 0; dev_warn(&dev->dev, FW_BUG "disabling VPD access (can't determine size of non-standard VPD format)\n"); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0060, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x007c, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0413, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0078, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0079, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0073, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0071, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005b, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x002f, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005d, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005f, quirk_blacklist_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, PCI_ANY_ID, quirk_blacklist_vpd); /* * For Broadcom 5706, 5708, 5709 rev. A nics, any read beyond the * VPD end tag will hang the device. This problem was initially * observed when a vpd entry was created in sysfs * ('/sys/bus/pci/devices/<id>/vpd'). A read to this sysfs entry * will dump 32k of data. Reading a full 32k will cause an access * beyond the VPD end tag causing the device to hang. Once the device * is hung, the bnx2 driver will not be able to reset the device. * We believe that it is legal to read beyond the end tag and * therefore the solution is to limit the read/write length. */ static void quirk_brcm_570x_limit_vpd(struct pci_dev *dev) { /* * Only disable the VPD capability for 5706, 5706S, 5708, * 5708S and 5709 rev. A */ if ((dev->device == PCI_DEVICE_ID_NX2_5706) || (dev->device == PCI_DEVICE_ID_NX2_5706S) || (dev->device == PCI_DEVICE_ID_NX2_5708) || (dev->device == PCI_DEVICE_ID_NX2_5708S) || ((dev->device == PCI_DEVICE_ID_NX2_5709) && (dev->revision & 0xf0) == 0x0)) { if (dev->vpd) dev->vpd->len = 0x80; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, quirk_brcm_570x_limit_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706S, quirk_brcm_570x_limit_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708, quirk_brcm_570x_limit_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708S, quirk_brcm_570x_limit_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709, quirk_brcm_570x_limit_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709S, quirk_brcm_570x_limit_vpd); static void quirk_brcm_5719_limit_mrrs(struct pci_dev *dev) { u32 rev; pci_read_config_dword(dev, 0xf4, &rev); /* Only CAP the MRRS if the device is a 5719 A0 */ if (rev == 0x05719000) { int readrq = pcie_get_readrq(dev); if (readrq > 2048) pcie_set_readrq(dev, 2048); } } DECLARE_PCI_FIXUP_ENABLE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5719, quirk_brcm_5719_limit_mrrs); /* Originally in EDAC sources for i82875P: * Intel tells BIOS developers to hide device 6 which * configures the overflow device access containing * the DRBs - this is where we expose device 6. * http://www.x86-secret.com/articles/tweak/pat/patsecrets-2.htm */ static void quirk_unhide_mch_dev6(struct pci_dev *dev) { u8 reg; if (pci_read_config_byte(dev, 0xF4, &reg) == 0 && !(reg & 0x02)) { dev_info(&dev->dev, "Enabling MCH 'Overflow' Device\n"); pci_write_config_byte(dev, 0xF4, reg | 0x02); } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82865_HB, quirk_unhide_mch_dev6); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82875_HB, quirk_unhide_mch_dev6); #ifdef CONFIG_TILEPRO /* * The Tilera TILEmpower tilepro platform needs to set the link speed * to 2.5GT(Giga-Transfers)/s (Gen 1). The default link speed * setting is 5GT/s (Gen 2). 0x98 is the Link Control2 PCIe * capability register of the PEX8624 PCIe switch. The switch * supports link speed auto negotiation, but falsely sets * the link speed to 5GT/s. */ static void quirk_tile_plx_gen1(struct pci_dev *dev) { if (tile_plx_gen1) { pci_write_config_dword(dev, 0x98, 0x1); mdelay(50); } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_PLX, 0x8624, quirk_tile_plx_gen1); #endif /* CONFIG_TILEPRO */ #ifdef CONFIG_PCI_MSI /* Some chipsets do not support MSI. We cannot easily rely on setting * PCI_BUS_FLAGS_NO_MSI in its bus flags because there are actually * some other buses controlled by the chipset even if Linux is not * aware of it. Instead of setting the flag on all buses in the * machine, simply disable MSI globally. */ static void quirk_disable_all_msi(struct pci_dev *dev) { pci_no_msi(); dev_warn(&dev->dev, "MSI quirk detected; MSI disabled\n"); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_GCNB_LE, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS400_200, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS480, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3336, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3351, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3364, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8380_0, quirk_disable_all_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, 0x0761, quirk_disable_all_msi); /* Disable MSI on chipsets that are known to not support it */ static void quirk_disable_msi(struct pci_dev *dev) { if (dev->subordinate) { dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n"); dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, 0xa238, quirk_disable_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x5a3f, quirk_disable_msi); /* * The APC bridge device in AMD 780 family northbridges has some random * OEM subsystem ID in its vendor ID register (erratum 18), so instead * we use the possible vendor/device IDs of the host bridge for the * declared quirk, and search for the APC bridge by slot number. */ static void quirk_amd_780_apc_msi(struct pci_dev *host_bridge) { struct pci_dev *apc_bridge; apc_bridge = pci_get_slot(host_bridge->bus, PCI_DEVFN(1, 0)); if (apc_bridge) { if (apc_bridge->device == 0x9602) quirk_disable_msi(apc_bridge); pci_dev_put(apc_bridge); } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, 0x9600, quirk_amd_780_apc_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, 0x9601, quirk_amd_780_apc_msi); /* Go through the list of Hypertransport capabilities and * return 1 if a HT MSI capability is found and enabled */ static int msi_ht_cap_enabled(struct pci_dev *dev) { int pos, ttl = PCI_FIND_CAP_TTL; pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING); while (pos && ttl--) { u8 flags; if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS, &flags) == 0) { dev_info(&dev->dev, "Found %s HT MSI Mapping\n", flags & HT_MSI_FLAGS_ENABLE ? "enabled" : "disabled"); return (flags & HT_MSI_FLAGS_ENABLE) != 0; } pos = pci_find_next_ht_capability(dev, pos, HT_CAPTYPE_MSI_MAPPING); } return 0; } /* Check the hypertransport MSI mapping to know whether MSI is enabled or not */ static void quirk_msi_ht_cap(struct pci_dev *dev) { if (dev->subordinate && !msi_ht_cap_enabled(dev)) { dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n"); dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT2000_PCIE, quirk_msi_ht_cap); /* The nVidia CK804 chipset may have 2 HT MSI mappings. * MSI are supported if the MSI capability set in any of these mappings. */ static void quirk_nvidia_ck804_msi_ht_cap(struct pci_dev *dev) { struct pci_dev *pdev; if (!dev->subordinate) return; /* check HT MSI cap on this chipset and the root one. * a single one having MSI is enough to be sure that MSI are supported. */ pdev = pci_get_slot(dev->bus, 0); if (!pdev) return; if (!msi_ht_cap_enabled(dev) && !msi_ht_cap_enabled(pdev)) { dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n"); dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI; } pci_dev_put(pdev); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE, quirk_nvidia_ck804_msi_ht_cap); /* Force enable MSI mapping capability on HT bridges */ static void ht_enable_msi_mapping(struct pci_dev *dev) { int pos, ttl = PCI_FIND_CAP_TTL; pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING); while (pos && ttl--) { u8 flags; if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS, &flags) == 0) { dev_info(&dev->dev, "Enabling HT MSI Mapping\n"); pci_write_config_byte(dev, pos + HT_MSI_FLAGS, flags | HT_MSI_FLAGS_ENABLE); } pos = pci_find_next_ht_capability(dev, pos, HT_CAPTYPE_MSI_MAPPING); } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000_PXB, ht_enable_msi_mapping); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, ht_enable_msi_mapping); /* The P5N32-SLI motherboards from Asus have a problem with msi * for the MCP55 NIC. It is not yet determined whether the msi problem * also affects other devices. As for now, turn off msi for this device. */ static void nvenet_msi_disable(struct pci_dev *dev) { const char *board_name = dmi_get_system_info(DMI_BOARD_NAME); if (board_name && (strstr(board_name, "P5N32-SLI PREMIUM") || strstr(board_name, "P5N32-E SLI"))) { dev_info(&dev->dev, "Disabling msi for MCP55 NIC on P5N32-SLI\n"); dev->no_msi = 1; } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_NVENET_15, nvenet_msi_disable); /* * Some versions of the MCP55 bridge from Nvidia have a legacy IRQ routing * config register. This register controls the routing of legacy * interrupts from devices that route through the MCP55. If this register * is misprogrammed, interrupts are only sent to the BSP, unlike * conventional systems where the IRQ is broadcast to all online CPUs. Not * having this register set properly prevents kdump from booting up * properly, so let's make sure that we have it set correctly. * Note that this is an undocumented register. */ static void nvbridge_check_legacy_irq_routing(struct pci_dev *dev) { u32 cfg; if (!pci_find_capability(dev, PCI_CAP_ID_HT)) return; pci_read_config_dword(dev, 0x74, &cfg); if (cfg & ((1 << 2) | (1 << 15))) { printk(KERN_INFO "Rewriting irq routing register on MCP55\n"); cfg &= ~((1 << 2) | (1 << 15)); pci_write_config_dword(dev, 0x74, cfg); } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_MCP55_BRIDGE_V0, nvbridge_check_legacy_irq_routing); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_MCP55_BRIDGE_V4, nvbridge_check_legacy_irq_routing); static int ht_check_msi_mapping(struct pci_dev *dev) { int pos, ttl = PCI_FIND_CAP_TTL; int found = 0; /* check if there is HT MSI cap or enabled on this device */ pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING); while (pos && ttl--) { u8 flags; if (found < 1) found = 1; if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS, &flags) == 0) { if (flags & HT_MSI_FLAGS_ENABLE) { if (found < 2) { found = 2; break; } } } pos = pci_find_next_ht_capability(dev, pos, HT_CAPTYPE_MSI_MAPPING); } return found; } static int host_bridge_with_leaf(struct pci_dev *host_bridge) { struct pci_dev *dev; int pos; int i, dev_no; int found = 0; dev_no = host_bridge->devfn >> 3; for (i = dev_no + 1; i < 0x20; i++) { dev = pci_get_slot(host_bridge->bus, PCI_DEVFN(i, 0)); if (!dev) continue; /* found next host bridge ?*/ pos = pci_find_ht_capability(dev, HT_CAPTYPE_SLAVE); if (pos != 0) { pci_dev_put(dev); break; } if (ht_check_msi_mapping(dev)) { found = 1; pci_dev_put(dev); break; } pci_dev_put(dev); } return found; } #define PCI_HT_CAP_SLAVE_CTRL0 4 /* link control */ #define PCI_HT_CAP_SLAVE_CTRL1 8 /* link control to */ static int is_end_of_ht_chain(struct pci_dev *dev) { int pos, ctrl_off; int end = 0; u16 flags, ctrl; pos = pci_find_ht_capability(dev, HT_CAPTYPE_SLAVE); if (!pos) goto out; pci_read_config_word(dev, pos + PCI_CAP_FLAGS, &flags); ctrl_off = ((flags >> 10) & 1) ? PCI_HT_CAP_SLAVE_CTRL0 : PCI_HT_CAP_SLAVE_CTRL1; pci_read_config_word(dev, pos + ctrl_off, &ctrl); if (ctrl & (1 << 6)) end = 1; out: return end; } static void nv_ht_enable_msi_mapping(struct pci_dev *dev) { struct pci_dev *host_bridge; int pos; int i, dev_no; int found = 0; dev_no = dev->devfn >> 3; for (i = dev_no; i >= 0; i--) { host_bridge = pci_get_slot(dev->bus, PCI_DEVFN(i, 0)); if (!host_bridge) continue; pos = pci_find_ht_capability(host_bridge, HT_CAPTYPE_SLAVE); if (pos != 0) { found = 1; break; } pci_dev_put(host_bridge); } if (!found) return; /* don't enable end_device/host_bridge with leaf directly here */ if (host_bridge == dev && is_end_of_ht_chain(host_bridge) && host_bridge_with_leaf(host_bridge)) goto out; /* root did that ! */ if (msi_ht_cap_enabled(host_bridge)) goto out; ht_enable_msi_mapping(dev); out: pci_dev_put(host_bridge); } static void ht_disable_msi_mapping(struct pci_dev *dev) { int pos, ttl = PCI_FIND_CAP_TTL; pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING); while (pos && ttl--) { u8 flags; if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS, &flags) == 0) { dev_info(&dev->dev, "Disabling HT MSI Mapping\n"); pci_write_config_byte(dev, pos + HT_MSI_FLAGS, flags & ~HT_MSI_FLAGS_ENABLE); } pos = pci_find_next_ht_capability(dev, pos, HT_CAPTYPE_MSI_MAPPING); } } static void __nv_msi_ht_cap_quirk(struct pci_dev *dev, int all) { struct pci_dev *host_bridge; int pos; int found; if (!pci_msi_enabled()) return; /* check if there is HT MSI cap or enabled on this device */ found = ht_check_msi_mapping(dev); /* no HT MSI CAP */ if (found == 0) return; /* * HT MSI mapping should be disabled on devices that are below * a non-Hypertransport host bridge. Locate the host bridge... */ host_bridge = pci_get_bus_and_slot(0, PCI_DEVFN(0, 0)); if (host_bridge == NULL) { dev_warn(&dev->dev, "nv_msi_ht_cap_quirk didn't locate host bridge\n"); return; } pos = pci_find_ht_capability(host_bridge, HT_CAPTYPE_SLAVE); if (pos != 0) { /* Host bridge is to HT */ if (found == 1) { /* it is not enabled, try to enable it */ if (all) ht_enable_msi_mapping(dev); else nv_ht_enable_msi_mapping(dev); } goto out; } /* HT MSI is not enabled */ if (found == 1) goto out; /* Host bridge is not to HT, disable HT MSI mapping on this device */ ht_disable_msi_mapping(dev); out: pci_dev_put(host_bridge); } static void nv_msi_ht_cap_quirk_all(struct pci_dev *dev) { return __nv_msi_ht_cap_quirk(dev, 1); } static void nv_msi_ht_cap_quirk_leaf(struct pci_dev *dev) { return __nv_msi_ht_cap_quirk(dev, 0); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID, nv_msi_ht_cap_quirk_leaf); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID, nv_msi_ht_cap_quirk_leaf); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_ANY_ID, nv_msi_ht_cap_quirk_all); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AL, PCI_ANY_ID, nv_msi_ht_cap_quirk_all); static void quirk_msi_intx_disable_bug(struct pci_dev *dev) { dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG; } static void quirk_msi_intx_disable_ati_bug(struct pci_dev *dev) { struct pci_dev *p; /* SB700 MSI issue will be fixed at HW level from revision A21, * we need check PCI REVISION ID of SMBus controller to get SB700 * revision. */ p = pci_get_device(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_SBX00_SMBUS, NULL); if (!p) return; if ((p->revision < 0x3B) && (p->revision >= 0x30)) dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG; pci_dev_put(p); } static void quirk_msi_intx_disable_qca_bug(struct pci_dev *dev) { /* AR816X/AR817X/E210X MSI is fixed at HW level from revision 0x18 */ if (dev->revision < 0x18) { dev_info(&dev->dev, "set MSI_INTX_DISABLE_BUG flag\n"); dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG; } } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780S, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714S, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715S, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4390, quirk_msi_intx_disable_ati_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4391, quirk_msi_intx_disable_ati_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4392, quirk_msi_intx_disable_ati_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4393, quirk_msi_intx_disable_ati_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4394, quirk_msi_intx_disable_ati_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4373, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4374, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4375, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1062, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1063, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x2060, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x2062, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1073, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1083, quirk_msi_intx_disable_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1090, quirk_msi_intx_disable_qca_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1091, quirk_msi_intx_disable_qca_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x10a0, quirk_msi_intx_disable_qca_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x10a1, quirk_msi_intx_disable_qca_bug); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0xe091, quirk_msi_intx_disable_qca_bug); #endif /* CONFIG_PCI_MSI */ /* Allow manual resource allocation for PCI hotplug bridges * via pci=hpmemsize=nnM and pci=hpiosize=nnM parameters. For * some PCI-PCI hotplug bridges, like PLX 6254 (former HINT HB6), * kernel fails to allocate resources when hotplug device is * inserted and PCI bus is rescanned. */ static void quirk_hotplug_bridge(struct pci_dev *dev) { dev->is_hotplug_bridge = 1; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_HINT, 0x0020, quirk_hotplug_bridge); /* * This is a quirk for the Ricoh MMC controller found as a part of * some mulifunction chips. * This is very similar and based on the ricoh_mmc driver written by * Philip Langdale. Thank you for these magic sequences. * * These chips implement the four main memory card controllers (SD, MMC, MS, xD) * and one or both of cardbus or firewire. * * It happens that they implement SD and MMC * support as separate controllers (and PCI functions). The linux SDHCI * driver supports MMC cards but the chip detects MMC cards in hardware * and directs them to the MMC controller - so the SDHCI driver never sees * them. * * To get around this, we must disable the useless MMC controller. * At that point, the SDHCI controller will start seeing them * It seems to be the case that the relevant PCI registers to deactivate the * MMC controller live on PCI function 0, which might be the cardbus controller * or the firewire controller, depending on the particular chip in question * * This has to be done early, because as soon as we disable the MMC controller * other pci functions shift up one level, e.g. function #2 becomes function * #1, and this will confuse the pci core. */ #ifdef CONFIG_MMC_RICOH_MMC static void ricoh_mmc_fixup_rl5c476(struct pci_dev *dev) { /* disable via cardbus interface */ u8 write_enable; u8 write_target; u8 disable; /* disable must be done via function #0 */ if (PCI_FUNC(dev->devfn)) return; pci_read_config_byte(dev, 0xB7, &disable); if (disable & 0x02) return; pci_read_config_byte(dev, 0x8E, &write_enable); pci_write_config_byte(dev, 0x8E, 0xAA); pci_read_config_byte(dev, 0x8D, &write_target); pci_write_config_byte(dev, 0x8D, 0xB7); pci_write_config_byte(dev, 0xB7, disable | 0x02); pci_write_config_byte(dev, 0x8E, write_enable); pci_write_config_byte(dev, 0x8D, write_target); dev_notice(&dev->dev, "proprietary Ricoh MMC controller disabled (via cardbus function)\n"); dev_notice(&dev->dev, "MMC cards are now supported by standard SDHCI controller\n"); } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C476, ricoh_mmc_fixup_rl5c476); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C476, ricoh_mmc_fixup_rl5c476); static void ricoh_mmc_fixup_r5c832(struct pci_dev *dev) { /* disable via firewire interface */ u8 write_enable; u8 disable; /* disable must be done via function #0 */ if (PCI_FUNC(dev->devfn)) return; /* * RICOH 0xe822 and 0xe823 SD/MMC card readers fail to recognize * certain types of SD/MMC cards. Lowering the SD base * clock frequency from 200Mhz to 50Mhz fixes this issue. * * 0x150 - SD2.0 mode enable for changing base clock * frequency to 50Mhz * 0xe1 - Base clock frequency * 0x32 - 50Mhz new clock frequency * 0xf9 - Key register for 0x150 * 0xfc - key register for 0xe1 */ if (dev->device == PCI_DEVICE_ID_RICOH_R5CE822 || dev->device == PCI_DEVICE_ID_RICOH_R5CE823) { pci_write_config_byte(dev, 0xf9, 0xfc); pci_write_config_byte(dev, 0x150, 0x10); pci_write_config_byte(dev, 0xf9, 0x00); pci_write_config_byte(dev, 0xfc, 0x01); pci_write_config_byte(dev, 0xe1, 0x32); pci_write_config_byte(dev, 0xfc, 0x00); dev_notice(&dev->dev, "MMC controller base frequency changed to 50Mhz.\n"); } pci_read_config_byte(dev, 0xCB, &disable); if (disable & 0x02) return; pci_read_config_byte(dev, 0xCA, &write_enable); pci_write_config_byte(dev, 0xCA, 0x57); pci_write_config_byte(dev, 0xCB, disable | 0x02); pci_write_config_byte(dev, 0xCA, write_enable); dev_notice(&dev->dev, "proprietary Ricoh MMC controller disabled (via firewire function)\n"); dev_notice(&dev->dev, "MMC cards are now supported by standard SDHCI controller\n"); } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5C832, ricoh_mmc_fixup_r5c832); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5C832, ricoh_mmc_fixup_r5c832); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE822, ricoh_mmc_fixup_r5c832); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE822, ricoh_mmc_fixup_r5c832); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE823, ricoh_mmc_fixup_r5c832); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE823, ricoh_mmc_fixup_r5c832); #endif /*CONFIG_MMC_RICOH_MMC*/ #ifdef CONFIG_DMAR_TABLE #define VTUNCERRMSK_REG 0x1ac #define VTD_MSK_SPEC_ERRORS (1 << 31) /* * This is a quirk for masking vt-d spec defined errors to platform error * handling logic. With out this, platforms using Intel 7500, 5500 chipsets * (and the derivative chipsets like X58 etc) seem to generate NMI/SMI (based * on the RAS config settings of the platform) when a vt-d fault happens. * The resulting SMI caused the system to hang. * * VT-d spec related errors are already handled by the VT-d OS code, so no * need to report the same error through other channels. */ static void vtd_mask_spec_errors(struct pci_dev *dev) { u32 word; pci_read_config_dword(dev, VTUNCERRMSK_REG, &word); pci_write_config_dword(dev, VTUNCERRMSK_REG, word | VTD_MSK_SPEC_ERRORS); } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x342e, vtd_mask_spec_errors); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x3c28, vtd_mask_spec_errors); #endif static void fixup_ti816x_class(struct pci_dev *dev) { u32 class = dev->class; /* TI 816x devices do not have class code set when in PCIe boot mode */ dev->class = PCI_CLASS_MULTIMEDIA_VIDEO << 8; dev_info(&dev->dev, "PCI class overridden (%#08x -> %#08x)\n", class, dev->class); } DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_TI, 0xb800, PCI_CLASS_NOT_DEFINED, 8, fixup_ti816x_class); /* Some PCIe devices do not work reliably with the claimed maximum * payload size supported. */ static void fixup_mpss_256(struct pci_dev *dev) { dev->pcie_mpss = 1; /* 256 bytes */ } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE, PCI_DEVICE_ID_SOLARFLARE_SFC4000A_0, fixup_mpss_256); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE, PCI_DEVICE_ID_SOLARFLARE_SFC4000A_1, fixup_mpss_256); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE, PCI_DEVICE_ID_SOLARFLARE_SFC4000B, fixup_mpss_256); /* Intel 5000 and 5100 Memory controllers have an errata with read completion * coalescing (which is enabled by default on some BIOSes) and MPS of 256B. * Since there is no way of knowing what the PCIE MPS on each fabric will be * until all of the devices are discovered and buses walked, read completion * coalescing must be disabled. Unfortunately, it cannot be re-enabled because * it is possible to hotplug a device with MPS of 256B. */ static void quirk_intel_mc_errata(struct pci_dev *dev) { int err; u16 rcc; if (pcie_bus_config == PCIE_BUS_TUNE_OFF || pcie_bus_config == PCIE_BUS_DEFAULT) return; /* Intel errata specifies bits to change but does not say what they are. * Keeping them magical until such time as the registers and values can * be explained. */ err = pci_read_config_word(dev, 0x48, &rcc); if (err) { dev_err(&dev->dev, "Error attempting to read the read completion coalescing register\n"); return; } if (!(rcc & (1 << 10))) return; rcc &= ~(1 << 10); err = pci_write_config_word(dev, 0x48, rcc); if (err) { dev_err(&dev->dev, "Error attempting to write the read completion coalescing register\n"); return; } pr_info_once("Read completion coalescing disabled due to hardware errata relating to 256B MPS\n"); } /* Intel 5000 series memory controllers and ports 2-7 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25c0, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d0, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d4, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d8, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e2, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e3, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e4, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e5, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e6, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e7, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f7, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f8, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f9, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25fa, quirk_intel_mc_errata); /* Intel 5100 series memory controllers and ports 2-7 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65c0, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e2, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e3, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e4, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e5, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e6, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e7, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f7, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f8, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f9, quirk_intel_mc_errata); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65fa, quirk_intel_mc_errata); /* * Ivytown NTB BAR sizes are misreported by the hardware due to an erratum. To * work around this, query the size it should be configured to by the device and * modify the resource end to correspond to this new size. */ static void quirk_intel_ntb(struct pci_dev *dev) { int rc; u8 val; rc = pci_read_config_byte(dev, 0x00D0, &val); if (rc) return; dev->resource[2].end = dev->resource[2].start + ((u64) 1 << val) - 1; rc = pci_read_config_byte(dev, 0x00D1, &val); if (rc) return; dev->resource[4].end = dev->resource[4].start + ((u64) 1 << val) - 1; } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0e08, quirk_intel_ntb); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0e0d, quirk_intel_ntb); static ktime_t fixup_debug_start(struct pci_dev *dev, void (*fn)(struct pci_dev *dev)) { ktime_t calltime = 0; dev_dbg(&dev->dev, "calling %pF\n", fn); if (initcall_debug) { pr_debug("calling %pF @ %i for %s\n", fn, task_pid_nr(current), dev_name(&dev->dev)); calltime = ktime_get(); } return calltime; } static void fixup_debug_report(struct pci_dev *dev, ktime_t calltime, void (*fn)(struct pci_dev *dev)) { ktime_t delta, rettime; unsigned long long duration; if (initcall_debug) { rettime = ktime_get(); delta = ktime_sub(rettime, calltime); duration = (unsigned long long) ktime_to_ns(delta) >> 10; pr_debug("pci fixup %pF returned after %lld usecs for %s\n", fn, duration, dev_name(&dev->dev)); } } /* * Some BIOS implementations leave the Intel GPU interrupts enabled, * even though no one is handling them (f.e. i915 driver is never loaded). * Additionally the interrupt destination is not set up properly * and the interrupt ends up -somewhere-. * * These spurious interrupts are "sticky" and the kernel disables * the (shared) interrupt line after 100.000+ generated interrupts. * * Fix it by disabling the still enabled interrupts. * This resolves crashes often seen on monitor unplug. */ #define I915_DEIER_REG 0x4400c static void disable_igfx_irq(struct pci_dev *dev) { void __iomem *regs = pci_iomap(dev, 0, 0); if (regs == NULL) { dev_warn(&dev->dev, "igfx quirk: Can't iomap PCI device\n"); return; } /* Check if any interrupt line is still enabled */ if (readl(regs + I915_DEIER_REG) != 0) { dev_warn(&dev->dev, "BIOS left Intel GPU interrupts enabled; disabling\n"); writel(0, regs + I915_DEIER_REG); } pci_iounmap(dev, regs); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0102, disable_igfx_irq); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x010a, disable_igfx_irq); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0152, disable_igfx_irq); /* * PCI devices which are on Intel chips can skip the 10ms delay * before entering D3 mode. */ static void quirk_remove_d3_delay(struct pci_dev *dev) { dev->d3_delay = 0; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0c00, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0412, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0c0c, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c31, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c3a, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c3d, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c2d, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c20, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c18, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c1c, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c26, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c4e, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c02, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c22, quirk_remove_d3_delay); /* Intel Cherrytrail devices do not need 10ms d3_delay */ DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2280, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b0, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b8, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22d8, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22dc, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b5, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b7, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2298, quirk_remove_d3_delay); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x229c, quirk_remove_d3_delay); /* * Some devices may pass our check in pci_intx_mask_supported() if * PCI_COMMAND_INTX_DISABLE works though they actually do not properly * support this feature. */ static void quirk_broken_intx_masking(struct pci_dev *dev) { dev->broken_intx_masking = 1; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x0030, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(0x1814, 0x0601, /* Ralink RT2800 802.11n PCI */ quirk_broken_intx_masking); /* * Realtek RTL8169 PCI Gigabit Ethernet Controller (rev 10) * Subsystem: Realtek RTL8169/8110 Family PCI Gigabit Ethernet NIC * * RTL8110SC - Fails under PCI device assignment using DisINTx masking. */ DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_REALTEK, 0x8169, quirk_broken_intx_masking); /* * Intel i40e (XL710/X710) 10/20/40GbE NICs all have broken INTx masking, * DisINTx can be set but the interrupt status bit is non-functional. */ DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1572, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1574, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1580, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1581, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1583, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1584, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1585, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1586, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1587, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1588, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1589, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d0, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d1, quirk_broken_intx_masking); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d2, quirk_broken_intx_masking); static u16 mellanox_broken_intx_devs[] = { PCI_DEVICE_ID_MELLANOX_HERMON_SDR, PCI_DEVICE_ID_MELLANOX_HERMON_DDR, PCI_DEVICE_ID_MELLANOX_HERMON_QDR, PCI_DEVICE_ID_MELLANOX_HERMON_DDR_GEN2, PCI_DEVICE_ID_MELLANOX_HERMON_QDR_GEN2, PCI_DEVICE_ID_MELLANOX_HERMON_EN, PCI_DEVICE_ID_MELLANOX_HERMON_EN_GEN2, PCI_DEVICE_ID_MELLANOX_CONNECTX_EN, PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_T_GEN2, PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_GEN2, PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_5_GEN2, PCI_DEVICE_ID_MELLANOX_CONNECTX2, PCI_DEVICE_ID_MELLANOX_CONNECTX3, PCI_DEVICE_ID_MELLANOX_CONNECTX3_PRO, }; #define CONNECTX_4_CURR_MAX_MINOR 99 #define CONNECTX_4_INTX_SUPPORT_MINOR 14 /* * Check ConnectX-4/LX FW version to see if it supports legacy interrupts. * If so, don't mark it as broken. * FW minor > 99 means older FW version format and no INTx masking support. * FW minor < 14 means new FW version format and no INTx masking support. */ static void mellanox_check_broken_intx_masking(struct pci_dev *pdev) { __be32 __iomem *fw_ver; u16 fw_major; u16 fw_minor; u16 fw_subminor; u32 fw_maj_min; u32 fw_sub_min; int i; for (i = 0; i < ARRAY_SIZE(mellanox_broken_intx_devs); i++) { if (pdev->device == mellanox_broken_intx_devs[i]) { pdev->broken_intx_masking = 1; return; } } /* Getting here means Connect-IB cards and up. Connect-IB has no INTx * support so shouldn't be checked further */ if (pdev->device == PCI_DEVICE_ID_MELLANOX_CONNECTIB) return; if (pdev->device != PCI_DEVICE_ID_MELLANOX_CONNECTX4 && pdev->device != PCI_DEVICE_ID_MELLANOX_CONNECTX4_LX) return; /* For ConnectX-4 and ConnectX-4LX, need to check FW support */ if (pci_enable_device_mem(pdev)) { dev_warn(&pdev->dev, "Can't enable device memory\n"); return; } fw_ver = ioremap(pci_resource_start(pdev, 0), 4); if (!fw_ver) { dev_warn(&pdev->dev, "Can't map ConnectX-4 initialization segment\n"); goto out; } /* Reading from resource space should be 32b aligned */ fw_maj_min = ioread32be(fw_ver); fw_sub_min = ioread32be(fw_ver + 1); fw_major = fw_maj_min & 0xffff; fw_minor = fw_maj_min >> 16; fw_subminor = fw_sub_min & 0xffff; if (fw_minor > CONNECTX_4_CURR_MAX_MINOR || fw_minor < CONNECTX_4_INTX_SUPPORT_MINOR) { dev_warn(&pdev->dev, "ConnectX-4: FW %u.%u.%u doesn't support INTx masking, disabling. Please upgrade FW to %d.14.1100 and up for INTx support\n", fw_major, fw_minor, fw_subminor, pdev->device == PCI_DEVICE_ID_MELLANOX_CONNECTX4 ? 12 : 14); pdev->broken_intx_masking = 1; } iounmap(fw_ver); out: pci_disable_device(pdev); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_ANY_ID, mellanox_check_broken_intx_masking); static void quirk_no_bus_reset(struct pci_dev *dev) { dev->dev_flags |= PCI_DEV_FLAGS_NO_BUS_RESET; } /* * Some Atheros AR9xxx and QCA988x chips do not behave after a bus reset. * The device will throw a Link Down error on AER-capable systems and * regardless of AER, config space of the device is never accessible again * and typically causes the system to hang or reset when access is attempted. * http://www.spinics.net/lists/linux-pci/msg34797.html */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0030, quirk_no_bus_reset); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0032, quirk_no_bus_reset); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x003c, quirk_no_bus_reset); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0033, quirk_no_bus_reset); static void quirk_no_pm_reset(struct pci_dev *dev) { /* * We can't do a bus reset on root bus devices, but an ineffective * PM reset may be better than nothing. */ if (!pci_is_root_bus(dev->bus)) dev->dev_flags |= PCI_DEV_FLAGS_NO_PM_RESET; } /* * Some AMD/ATI GPUS (HD8570 - Oland) report that a D3hot->D0 transition * causes a reset (i.e., they advertise NoSoftRst-). This transition seems * to have no effect on the device: it retains the framebuffer contents and * monitor sync. Advertising this support makes other layers, like VFIO, * assume pci_reset_function() is viable for this device. Mark it as * unavailable to skip it when testing reset methods. */ DECLARE_PCI_FIXUP_CLASS_HEADER(PCI_VENDOR_ID_ATI, PCI_ANY_ID, PCI_CLASS_DISPLAY_VGA, 8, quirk_no_pm_reset); /* * Thunderbolt controllers with broken MSI hotplug signaling: * Entire 1st generation (Light Ridge, Eagle Ridge, Light Peak) and part * of the 2nd generation (Cactus Ridge 4C up to revision 1, Port Ridge). */ static void quirk_thunderbolt_hotplug_msi(struct pci_dev *pdev) { if (pdev->is_hotplug_bridge && (pdev->device != PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C || pdev->revision <= 1)) pdev->no_msi = 1; } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LIGHT_RIDGE, quirk_thunderbolt_hotplug_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EAGLE_RIDGE, quirk_thunderbolt_hotplug_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LIGHT_PEAK, quirk_thunderbolt_hotplug_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C, quirk_thunderbolt_hotplug_msi); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PORT_RIDGE, quirk_thunderbolt_hotplug_msi); static void quirk_chelsio_extend_vpd(struct pci_dev *dev) { pci_set_vpd_size(dev, 8192); } DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x20, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x21, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x22, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x23, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x24, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x25, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x26, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x30, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x31, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x32, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x35, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x36, quirk_chelsio_extend_vpd); DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x37, quirk_chelsio_extend_vpd); #ifdef CONFIG_ACPI /* * Apple: Shutdown Cactus Ridge Thunderbolt controller. * * On Apple hardware the Cactus Ridge Thunderbolt controller needs to be * shutdown before suspend. Otherwise the native host interface (NHI) will not * be present after resume if a device was plugged in before suspend. * * The thunderbolt controller consists of a pcie switch with downstream * bridges leading to the NHI and to the tunnel pci bridges. * * This quirk cuts power to the whole chip. Therefore we have to apply it * during suspend_noirq of the upstream bridge. * * Power is automagically restored before resume. No action is needed. */ static void quirk_apple_poweroff_thunderbolt(struct pci_dev *dev) { acpi_handle bridge, SXIO, SXFP, SXLV; if (!dmi_match(DMI_BOARD_VENDOR, "Apple Inc.")) return; if (pci_pcie_type(dev) != PCI_EXP_TYPE_UPSTREAM) return; bridge = ACPI_HANDLE(&dev->dev); if (!bridge) return; /* * SXIO and SXLV are present only on machines requiring this quirk. * TB bridges in external devices might have the same device id as those * on the host, but they will not have the associated ACPI methods. This * implicitly checks that we are at the right bridge. */ if (ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXIO", &SXIO)) || ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXFP", &SXFP)) || ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXLV", &SXLV))) return; dev_info(&dev->dev, "quirk: cutting power to thunderbolt controller...\n"); /* magic sequence */ acpi_execute_simple_method(SXIO, NULL, 1); acpi_execute_simple_method(SXFP, NULL, 0); msleep(300); acpi_execute_simple_method(SXLV, NULL, 0); acpi_execute_simple_method(SXIO, NULL, 0); acpi_execute_simple_method(SXLV, NULL, 0); } DECLARE_PCI_FIXUP_SUSPEND_LATE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C, quirk_apple_poweroff_thunderbolt); /* * Apple: Wait for the thunderbolt controller to reestablish pci tunnels. * * During suspend the thunderbolt controller is reset and all pci * tunnels are lost. The NHI driver will try to reestablish all tunnels * during resume. We have to manually wait for the NHI since there is * no parent child relationship between the NHI and the tunneled * bridges. */ static void quirk_apple_wait_for_thunderbolt(struct pci_dev *dev) { struct pci_dev *sibling = NULL; struct pci_dev *nhi = NULL; if (!dmi_match(DMI_BOARD_VENDOR, "Apple Inc.")) return; if (pci_pcie_type(dev) != PCI_EXP_TYPE_DOWNSTREAM) return; /* * Find the NHI and confirm that we are a bridge on the tb host * controller and not on a tb endpoint. */ sibling = pci_get_slot(dev->bus, 0x0); if (sibling == dev) goto out; /* we are the downstream bridge to the NHI */ if (!sibling || !sibling->subordinate) goto out; nhi = pci_get_slot(sibling->subordinate, 0x0); if (!nhi) goto out; if (nhi->vendor != PCI_VENDOR_ID_INTEL || (nhi->device != PCI_DEVICE_ID_INTEL_LIGHT_RIDGE && nhi->device != PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C && nhi->device != PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_NHI && nhi->device != PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_NHI) || nhi->class != PCI_CLASS_SYSTEM_OTHER << 8) goto out; dev_info(&dev->dev, "quirk: waiting for thunderbolt to reestablish PCI tunnels...\n"); device_pm_wait_for_dev(&dev->dev, &nhi->dev); out: pci_dev_put(nhi); pci_dev_put(sibling); } DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LIGHT_RIDGE, quirk_apple_wait_for_thunderbolt); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C, quirk_apple_wait_for_thunderbolt); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE, quirk_apple_wait_for_thunderbolt); DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE, quirk_apple_wait_for_thunderbolt); #endif static void pci_do_fixups(struct pci_dev *dev, struct pci_fixup *f, struct pci_fixup *end) { ktime_t calltime; for (; f < end; f++) if ((f->class == (u32) (dev->class >> f->class_shift) || f->class == (u32) PCI_ANY_ID) && (f->vendor == dev->vendor || f->vendor == (u16) PCI_ANY_ID) && (f->device == dev->device || f->device == (u16) PCI_ANY_ID)) { calltime = fixup_debug_start(dev, f->hook); f->hook(dev); fixup_debug_report(dev, calltime, f->hook); } } extern struct pci_fixup __start_pci_fixups_early[]; extern struct pci_fixup __end_pci_fixups_early[]; extern struct pci_fixup __start_pci_fixups_header[]; extern struct pci_fixup __end_pci_fixups_header[]; extern struct pci_fixup __start_pci_fixups_final[]; extern struct pci_fixup __end_pci_fixups_final[]; extern struct pci_fixup __start_pci_fixups_enable[]; extern struct pci_fixup __end_pci_fixups_enable[]; extern struct pci_fixup __start_pci_fixups_resume[]; extern struct pci_fixup __end_pci_fixups_resume[]; extern struct pci_fixup __start_pci_fixups_resume_early[]; extern struct pci_fixup __end_pci_fixups_resume_early[]; extern struct pci_fixup __start_pci_fixups_suspend[]; extern struct pci_fixup __end_pci_fixups_suspend[]; extern struct pci_fixup __start_pci_fixups_suspend_late[]; extern struct pci_fixup __end_pci_fixups_suspend_late[]; static bool pci_apply_fixup_final_quirks; void pci_fixup_device(enum pci_fixup_pass pass, struct pci_dev *dev) { struct pci_fixup *start, *end; switch (pass) { case pci_fixup_early: start = __start_pci_fixups_early; end = __end_pci_fixups_early; break; case pci_fixup_header: start = __start_pci_fixups_header; end = __end_pci_fixups_header; break; case pci_fixup_final: if (!pci_apply_fixup_final_quirks) return; start = __start_pci_fixups_final; end = __end_pci_fixups_final; break; case pci_fixup_enable: start = __start_pci_fixups_enable; end = __end_pci_fixups_enable; break; case pci_fixup_resume: start = __start_pci_fixups_resume; end = __end_pci_fixups_resume; break; case pci_fixup_resume_early: start = __start_pci_fixups_resume_early; end = __end_pci_fixups_resume_early; break; case pci_fixup_suspend: start = __start_pci_fixups_suspend; end = __end_pci_fixups_suspend; break; case pci_fixup_suspend_late: start = __start_pci_fixups_suspend_late; end = __end_pci_fixups_suspend_late; break; default: /* stupid compiler warning, you would think with an enum... */ return; } pci_do_fixups(dev, start, end); } EXPORT_SYMBOL(pci_fixup_device); static int __init pci_apply_final_quirks(void) { struct pci_dev *dev = NULL; u8 cls = 0; u8 tmp; if (pci_cache_line_size) printk(KERN_DEBUG "PCI: CLS %u bytes\n", pci_cache_line_size << 2); pci_apply_fixup_final_quirks = true; for_each_pci_dev(dev) { pci_fixup_device(pci_fixup_final, dev); /* * If arch hasn't set it explicitly yet, use the CLS * value shared by all PCI devices. If there's a * mismatch, fall back to the default value. */ if (!pci_cache_line_size) { pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &tmp); if (!cls) cls = tmp; if (!tmp || cls == tmp) continue; printk(KERN_DEBUG "PCI: CLS mismatch (%u != %u), using %u bytes\n", cls << 2, tmp << 2, pci_dfl_cache_line_size << 2); pci_cache_line_size = pci_dfl_cache_line_size; } } if (!pci_cache_line_size) { printk(KERN_DEBUG "PCI: CLS %u bytes, default %u\n", cls << 2, pci_dfl_cache_line_size << 2); pci_cache_line_size = cls ? cls : pci_dfl_cache_line_size; } return 0; } fs_initcall_sync(pci_apply_final_quirks); /* * Following are device-specific reset methods which can be used to * reset a single function if other methods (e.g. FLR, PM D0->D3) are * not available. */ static int reset_intel_82599_sfp_virtfn(struct pci_dev *dev, int probe) { /* * http://www.intel.com/content/dam/doc/datasheet/82599-10-gbe-controller-datasheet.pdf * * The 82599 supports FLR on VFs, but FLR support is reported only * in the PF DEVCAP (sec 9.3.10.4), not in the VF DEVCAP (sec 9.5). * Therefore, we can't use pcie_flr(), which checks the VF DEVCAP. */ if (probe) return 0; if (!pci_wait_for_pending_transaction(dev)) dev_err(&dev->dev, "transaction is not cleared; proceeding with reset anyway\n"); pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR); msleep(100); return 0; } #define SOUTH_CHICKEN2 0xc2004 #define PCH_PP_STATUS 0xc7200 #define PCH_PP_CONTROL 0xc7204 #define MSG_CTL 0x45010 #define NSDE_PWR_STATE 0xd0100 #define IGD_OPERATION_TIMEOUT 10000 /* set timeout 10 seconds */ static int reset_ivb_igd(struct pci_dev *dev, int probe) { void __iomem *mmio_base; unsigned long timeout; u32 val; if (probe) return 0; mmio_base = pci_iomap(dev, 0, 0); if (!mmio_base) return -ENOMEM; iowrite32(0x00000002, mmio_base + MSG_CTL); /* * Clobbering SOUTH_CHICKEN2 register is fine only if the next * driver loaded sets the right bits. However, this's a reset and * the bits have been set by i915 previously, so we clobber * SOUTH_CHICKEN2 register directly here. */ iowrite32(0x00000005, mmio_base + SOUTH_CHICKEN2); val = ioread32(mmio_base + PCH_PP_CONTROL) & 0xfffffffe; iowrite32(val, mmio_base + PCH_PP_CONTROL); timeout = jiffies + msecs_to_jiffies(IGD_OPERATION_TIMEOUT); do { val = ioread32(mmio_base + PCH_PP_STATUS); if ((val & 0xb0000000) == 0) goto reset_complete; msleep(10); } while (time_before(jiffies, timeout)); dev_warn(&dev->dev, "timeout during reset\n"); reset_complete: iowrite32(0x00000002, mmio_base + NSDE_PWR_STATE); pci_iounmap(dev, mmio_base); return 0; } /* * Device-specific reset method for Chelsio T4-based adapters. */ static int reset_chelsio_generic_dev(struct pci_dev *dev, int probe) { u16 old_command; u16 msix_flags; /* * If this isn't a Chelsio T4-based device, return -ENOTTY indicating * that we have no device-specific reset method. */ if ((dev->device & 0xf000) != 0x4000) return -ENOTTY; /* * If this is the "probe" phase, return 0 indicating that we can * reset this device. */ if (probe) return 0; /* * T4 can wedge if there are DMAs in flight within the chip and Bus * Master has been disabled. We need to have it on till the Function * Level Reset completes. (BUS_MASTER is disabled in * pci_reset_function()). */ pci_read_config_word(dev, PCI_COMMAND, &old_command); pci_write_config_word(dev, PCI_COMMAND, old_command | PCI_COMMAND_MASTER); /* * Perform the actual device function reset, saving and restoring * configuration information around the reset. */ pci_save_state(dev); /* * T4 also suffers a Head-Of-Line blocking problem if MSI-X interrupts * are disabled when an MSI-X interrupt message needs to be delivered. * So we briefly re-enable MSI-X interrupts for the duration of the * FLR. The pci_restore_state() below will restore the original * MSI-X state. */ pci_read_config_word(dev, dev->msix_cap+PCI_MSIX_FLAGS, &msix_flags); if ((msix_flags & PCI_MSIX_FLAGS_ENABLE) == 0) pci_write_config_word(dev, dev->msix_cap+PCI_MSIX_FLAGS, msix_flags | PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL); /* * Start of pcie_flr() code sequence. This reset code is a copy of * the guts of pcie_flr() because that's not an exported function. */ if (!pci_wait_for_pending_transaction(dev)) dev_err(&dev->dev, "transaction is not cleared; proceeding with reset anyway\n"); pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR); msleep(100); /* * End of pcie_flr() code sequence. */ /* * Restore the configuration information (BAR values, etc.) including * the original PCI Configuration Space Command word, and return * success. */ pci_restore_state(dev); pci_write_config_word(dev, PCI_COMMAND, old_command); return 0; } #define PCI_DEVICE_ID_INTEL_82599_SFP_VF 0x10ed #define PCI_DEVICE_ID_INTEL_IVB_M_VGA 0x0156 #define PCI_DEVICE_ID_INTEL_IVB_M2_VGA 0x0166 static const struct pci_dev_reset_methods pci_dev_reset_methods[] = { { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82599_SFP_VF, reset_intel_82599_sfp_virtfn }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_IVB_M_VGA, reset_ivb_igd }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_IVB_M2_VGA, reset_ivb_igd }, { PCI_VENDOR_ID_CHELSIO, PCI_ANY_ID, reset_chelsio_generic_dev }, { 0 } }; /* * These device-specific reset methods are here rather than in a driver * because when a host assigns a device to a guest VM, the host may need * to reset the device but probably doesn't have a driver for it. */ int pci_dev_specific_reset(struct pci_dev *dev, int probe) { const struct pci_dev_reset_methods *i; for (i = pci_dev_reset_methods; i->reset; i++) { if ((i->vendor == dev->vendor || i->vendor == (u16)PCI_ANY_ID) && (i->device == dev->device || i->device == (u16)PCI_ANY_ID)) return i->reset(dev, probe); } return -ENOTTY; } static void quirk_dma_func0_alias(struct pci_dev *dev) { if (PCI_FUNC(dev->devfn) != 0) pci_add_dma_alias(dev, PCI_DEVFN(PCI_SLOT(dev->devfn), 0)); } /* * https://bugzilla.redhat.com/show_bug.cgi?id=605888 * * Some Ricoh devices use function 0 as the PCIe requester ID for DMA. */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_RICOH, 0xe832, quirk_dma_func0_alias); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_RICOH, 0xe476, quirk_dma_func0_alias); static void quirk_dma_func1_alias(struct pci_dev *dev) { if (PCI_FUNC(dev->devfn) != 1) pci_add_dma_alias(dev, PCI_DEVFN(PCI_SLOT(dev->devfn), 1)); } /* * Marvell 88SE9123 uses function 1 as the requester ID for DMA. In some * SKUs function 1 is present and is a legacy IDE controller, in other * SKUs this function is not present, making this a ghost requester. * https://bugzilla.kernel.org/show_bug.cgi?id=42679 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9120, quirk_dma_func1_alias); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9123, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c14 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9130, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c47 + c57 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9172, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c59 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x917a, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c78 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9182, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c46 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x91a0, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c49 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9230, quirk_dma_func1_alias); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TTI, 0x0642, quirk_dma_func1_alias); /* https://bugs.gentoo.org/show_bug.cgi?id=497630 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB388_ESD, quirk_dma_func1_alias); /* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c117 */ DECLARE_PCI_FIXUP_HEADER(0x1c28, /* Lite-On */ 0x0122, /* Plextor M6E (Marvell 88SS9183)*/ quirk_dma_func1_alias); /* * Some devices DMA with the wrong devfn, not just the wrong function. * quirk_fixed_dma_alias() uses this table to create fixed aliases, where * the alias is "fixed" and independent of the device devfn. * * For example, the Adaptec 3405 is a PCIe card with an Intel 80333 I/O * processor. To software, this appears as a PCIe-to-PCI/X bridge with a * single device on the secondary bus. In reality, the single exposed * device at 0e.0 is the Address Translation Unit (ATU) of the controller * that provides a bridge to the internal bus of the I/O processor. The * controller supports private devices, which can be hidden from PCI config * space. In the case of the Adaptec 3405, a private device at 01.0 * appears to be the DMA engine, which therefore needs to become a DMA * alias for the device. */ static const struct pci_device_id fixed_dma_alias_tbl[] = { { PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x0285, PCI_VENDOR_ID_ADAPTEC2, 0x02bb), /* Adaptec 3405 */ .driver_data = PCI_DEVFN(1, 0) }, { PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x0285, PCI_VENDOR_ID_ADAPTEC2, 0x02bc), /* Adaptec 3805 */ .driver_data = PCI_DEVFN(1, 0) }, { 0 } }; static void quirk_fixed_dma_alias(struct pci_dev *dev) { const struct pci_device_id *id; id = pci_match_id(fixed_dma_alias_tbl, dev); if (id) pci_add_dma_alias(dev, id->driver_data); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ADAPTEC2, 0x0285, quirk_fixed_dma_alias); /* * A few PCIe-to-PCI bridges fail to expose a PCIe capability, resulting in * using the wrong DMA alias for the device. Some of these devices can be * used as either forward or reverse bridges, so we need to test whether the * device is operating in the correct mode. We could probably apply this * quirk to PCI_ANY_ID, but for now we'll just use known offenders. The test * is for a non-root, non-PCIe bridge where the upstream device is PCIe and * is not a PCIe-to-PCI bridge, then @pdev is actually a PCIe-to-PCI bridge. */ static void quirk_use_pcie_bridge_dma_alias(struct pci_dev *pdev) { if (!pci_is_root_bus(pdev->bus) && pdev->hdr_type == PCI_HEADER_TYPE_BRIDGE && !pci_is_pcie(pdev) && pci_is_pcie(pdev->bus->self) && pci_pcie_type(pdev->bus->self) != PCI_EXP_TYPE_PCI_BRIDGE) pdev->dev_flags |= PCI_DEV_FLAG_PCIE_BRIDGE_ALIAS; } /* ASM1083/1085, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c46 */ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ASMEDIA, 0x1080, quirk_use_pcie_bridge_dma_alias); /* Tundra 8113, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c43 */ DECLARE_PCI_FIXUP_HEADER(0x10e3, 0x8113, quirk_use_pcie_bridge_dma_alias); /* ITE 8892, https://bugzilla.kernel.org/show_bug.cgi?id=73551 */ DECLARE_PCI_FIXUP_HEADER(0x1283, 0x8892, quirk_use_pcie_bridge_dma_alias); /* Intel 82801, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c49 */ DECLARE_PCI_FIXUP_HEADER(0x8086, 0x244e, quirk_use_pcie_bridge_dma_alias); /* * MIC x200 NTB forwards PCIe traffic using multiple alien RIDs. They have to * be added as aliases to the DMA device in order to allow buffer access * when IOMMU is enabled. Following devfns have to match RIT-LUT table * programmed in the EEPROM. */ static void quirk_mic_x200_dma_alias(struct pci_dev *pdev) { pci_add_dma_alias(pdev, PCI_DEVFN(0x10, 0x0)); pci_add_dma_alias(pdev, PCI_DEVFN(0x11, 0x0)); pci_add_dma_alias(pdev, PCI_DEVFN(0x12, 0x3)); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2260, quirk_mic_x200_dma_alias); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2264, quirk_mic_x200_dma_alias); /* * Intersil/Techwell TW686[4589]-based video capture cards have an empty (zero) * class code. Fix it. */ static void quirk_tw686x_class(struct pci_dev *pdev) { u32 class = pdev->class; /* Use "Multimedia controller" class */ pdev->class = (PCI_CLASS_MULTIMEDIA_OTHER << 8) | 0x01; dev_info(&pdev->dev, "TW686x PCI class overridden (%#08x -> %#08x)\n", class, pdev->class); } DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6864, PCI_CLASS_NOT_DEFINED, 8, quirk_tw686x_class); DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6865, PCI_CLASS_NOT_DEFINED, 8, quirk_tw686x_class); DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6868, PCI_CLASS_NOT_DEFINED, 8, quirk_tw686x_class); DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6869, PCI_CLASS_NOT_DEFINED, 8, quirk_tw686x_class); /* * Per PCIe r3.0, sec 2.2.9, "Completion headers must supply the same * values for the Attribute as were supplied in the header of the * corresponding Request, except as explicitly allowed when IDO is used." * * If a non-compliant device generates a completion with a different * attribute than the request, the receiver may accept it (which itself * seems non-compliant based on sec 2.3.2), or it may handle it as a * Malformed TLP or an Unexpected Completion, which will probably lead to a * device access timeout. * * If the non-compliant device generates completions with zero attributes * (instead of copying the attributes from the request), we can work around * this by disabling the "Relaxed Ordering" and "No Snoop" attributes in * upstream devices so they always generate requests with zero attributes. * * This affects other devices under the same Root Port, but since these * attributes are performance hints, there should be no functional problem. * * Note that Configuration Space accesses are never supposed to have TLP * Attributes, so we're safe waiting till after any Configuration Space * accesses to do the Root Port fixup. */ static void quirk_disable_root_port_attributes(struct pci_dev *pdev) { struct pci_dev *root_port = pci_find_pcie_root_port(pdev); if (!root_port) { dev_warn(&pdev->dev, "PCIe Completion erratum may cause device errors\n"); return; } dev_info(&root_port->dev, "Disabling No Snoop/Relaxed Ordering Attributes to avoid PCIe Completion erratum in %s\n", dev_name(&pdev->dev)); pcie_capability_clear_and_set_word(root_port, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN, 0); } /* * The Chelsio T5 chip fails to copy TLP Attributes from a Request to the * Completion it generates. */ static void quirk_chelsio_T5_disable_root_port_attributes(struct pci_dev *pdev) { /* * This mask/compare operation selects for Physical Function 4 on a * T5. We only need to fix up the Root Port once for any of the * PFs. PF[0..3] have PCI Device IDs of 0x50xx, but PF4 is uniquely * 0x54xx so we use that one, */ if ((pdev->device & 0xff00) == 0x5400) quirk_disable_root_port_attributes(pdev); } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_CHELSIO, PCI_ANY_ID, quirk_chelsio_T5_disable_root_port_attributes); /* * AMD has indicated that the devices below do not support peer-to-peer * in any system where they are found in the southbridge with an AMD * IOMMU in the system. Multifunction devices that do not support * peer-to-peer between functions can claim to support a subset of ACS. * Such devices effectively enable request redirect (RR) and completion * redirect (CR) since all transactions are redirected to the upstream * root complex. * * http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/94086 * http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/94102 * http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/99402 * * 1002:4385 SBx00 SMBus Controller * 1002:439c SB7x0/SB8x0/SB9x0 IDE Controller * 1002:4383 SBx00 Azalia (Intel HDA) * 1002:439d SB7x0/SB8x0/SB9x0 LPC host controller * 1002:4384 SBx00 PCI to PCI Bridge * 1002:4399 SB7x0/SB8x0/SB9x0 USB OHCI2 Controller * * https://bugzilla.kernel.org/show_bug.cgi?id=81841#c15 * * 1022:780f [AMD] FCH PCI Bridge * 1022:7809 [AMD] FCH USB OHCI Controller */ static int pci_quirk_amd_sb_acs(struct pci_dev *dev, u16 acs_flags) { #ifdef CONFIG_ACPI struct acpi_table_header *header = NULL; acpi_status status; /* Targeting multifunction devices on the SB (appears on root bus) */ if (!dev->multifunction || !pci_is_root_bus(dev->bus)) return -ENODEV; /* The IVRS table describes the AMD IOMMU */ status = acpi_get_table("IVRS", 0, &header); if (ACPI_FAILURE(status)) return -ENODEV; /* Filter out flags not applicable to multifunction */ acs_flags &= (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC | PCI_ACS_DT); return acs_flags & ~(PCI_ACS_RR | PCI_ACS_CR) ? 0 : 1; #else return -ENODEV; #endif } static int pci_quirk_cavium_acs(struct pci_dev *dev, u16 acs_flags) { /* * Cavium devices matching this quirk do not perform peer-to-peer * with other functions, allowing masking out these bits as if they * were unimplemented in the ACS capability. */ acs_flags &= ~(PCI_ACS_SV | PCI_ACS_TB | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_DT); return acs_flags ? 0 : 1; } /* * Many Intel PCH root ports do provide ACS-like features to disable peer * transactions and validate bus numbers in requests, but do not provide an * actual PCIe ACS capability. This is the list of device IDs known to fall * into that category as provided by Intel in Red Hat bugzilla 1037684. */ static const u16 pci_quirk_intel_pch_acs_ids[] = { /* Ibexpeak PCH */ 0x3b42, 0x3b43, 0x3b44, 0x3b45, 0x3b46, 0x3b47, 0x3b48, 0x3b49, 0x3b4a, 0x3b4b, 0x3b4c, 0x3b4d, 0x3b4e, 0x3b4f, 0x3b50, 0x3b51, /* Cougarpoint PCH */ 0x1c10, 0x1c11, 0x1c12, 0x1c13, 0x1c14, 0x1c15, 0x1c16, 0x1c17, 0x1c18, 0x1c19, 0x1c1a, 0x1c1b, 0x1c1c, 0x1c1d, 0x1c1e, 0x1c1f, /* Pantherpoint PCH */ 0x1e10, 0x1e11, 0x1e12, 0x1e13, 0x1e14, 0x1e15, 0x1e16, 0x1e17, 0x1e18, 0x1e19, 0x1e1a, 0x1e1b, 0x1e1c, 0x1e1d, 0x1e1e, 0x1e1f, /* Lynxpoint-H PCH */ 0x8c10, 0x8c11, 0x8c12, 0x8c13, 0x8c14, 0x8c15, 0x8c16, 0x8c17, 0x8c18, 0x8c19, 0x8c1a, 0x8c1b, 0x8c1c, 0x8c1d, 0x8c1e, 0x8c1f, /* Lynxpoint-LP PCH */ 0x9c10, 0x9c11, 0x9c12, 0x9c13, 0x9c14, 0x9c15, 0x9c16, 0x9c17, 0x9c18, 0x9c19, 0x9c1a, 0x9c1b, /* Wildcat PCH */ 0x9c90, 0x9c91, 0x9c92, 0x9c93, 0x9c94, 0x9c95, 0x9c96, 0x9c97, 0x9c98, 0x9c99, 0x9c9a, 0x9c9b, /* Patsburg (X79) PCH */ 0x1d10, 0x1d12, 0x1d14, 0x1d16, 0x1d18, 0x1d1a, 0x1d1c, 0x1d1e, /* Wellsburg (X99) PCH */ 0x8d10, 0x8d11, 0x8d12, 0x8d13, 0x8d14, 0x8d15, 0x8d16, 0x8d17, 0x8d18, 0x8d19, 0x8d1a, 0x8d1b, 0x8d1c, 0x8d1d, 0x8d1e, /* Lynx Point (9 series) PCH */ 0x8c90, 0x8c92, 0x8c94, 0x8c96, 0x8c98, 0x8c9a, 0x8c9c, 0x8c9e, }; static bool pci_quirk_intel_pch_acs_match(struct pci_dev *dev) { int i; /* Filter out a few obvious non-matches first */ if (!pci_is_pcie(dev) || pci_pcie_type(dev) != PCI_EXP_TYPE_ROOT_PORT) return false; for (i = 0; i < ARRAY_SIZE(pci_quirk_intel_pch_acs_ids); i++) if (pci_quirk_intel_pch_acs_ids[i] == dev->device) return true; return false; } #define INTEL_PCH_ACS_FLAGS (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_SV) static int pci_quirk_intel_pch_acs(struct pci_dev *dev, u16 acs_flags) { u16 flags = dev->dev_flags & PCI_DEV_FLAGS_ACS_ENABLED_QUIRK ? INTEL_PCH_ACS_FLAGS : 0; if (!pci_quirk_intel_pch_acs_match(dev)) return -ENOTTY; return acs_flags & ~flags ? 0 : 1; } /* * Sunrise Point PCH root ports implement ACS, but unfortunately as shown in * the datasheet (Intel 100 Series Chipset Family PCH Datasheet, Vol. 2, * 12.1.46, 12.1.47)[1] this chipset uses dwords for the ACS capability and * control registers whereas the PCIe spec packs them into words (Rev 3.0, * 7.16 ACS Extended Capability). The bit definitions are correct, but the * control register is at offset 8 instead of 6 and we should probably use * dword accesses to them. This applies to the following PCI Device IDs, as * found in volume 1 of the datasheet[2]: * * 0xa110-0xa11f Sunrise Point-H PCI Express Root Port #{0-16} * 0xa167-0xa16a Sunrise Point-H PCI Express Root Port #{17-20} * * N.B. This doesn't fix what lspci shows. * * [1] http://www.intel.com/content/www/us/en/chipsets/100-series-chipset-datasheet-vol-2.html * [2] http://www.intel.com/content/www/us/en/chipsets/100-series-chipset-datasheet-vol-1.html */ static bool pci_quirk_intel_spt_pch_acs_match(struct pci_dev *dev) { return pci_is_pcie(dev) && pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT && ((dev->device & ~0xf) == 0xa110 || (dev->device >= 0xa167 && dev->device <= 0xa16a)); } #define INTEL_SPT_ACS_CTRL (PCI_ACS_CAP + 4) static int pci_quirk_intel_spt_pch_acs(struct pci_dev *dev, u16 acs_flags) { int pos; u32 cap, ctrl; if (!pci_quirk_intel_spt_pch_acs_match(dev)) return -ENOTTY; pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS); if (!pos) return -ENOTTY; /* see pci_acs_flags_enabled() */ pci_read_config_dword(dev, pos + PCI_ACS_CAP, &cap); acs_flags &= (cap | PCI_ACS_EC); pci_read_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, &ctrl); return acs_flags & ~ctrl ? 0 : 1; } static int pci_quirk_mf_endpoint_acs(struct pci_dev *dev, u16 acs_flags) { /* * SV, TB, and UF are not relevant to multifunction endpoints. * * Multifunction devices are only required to implement RR, CR, and DT * in their ACS capability if they support peer-to-peer transactions. * Devices matching this quirk have been verified by the vendor to not * perform peer-to-peer with other functions, allowing us to mask out * these bits as if they were unimplemented in the ACS capability. */ acs_flags &= ~(PCI_ACS_SV | PCI_ACS_TB | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_DT); return acs_flags ? 0 : 1; } static const struct pci_dev_acs_enabled { u16 vendor; u16 device; int (*acs_enabled)(struct pci_dev *dev, u16 acs_flags); } pci_dev_acs_enabled[] = { { PCI_VENDOR_ID_ATI, 0x4385, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_ATI, 0x439c, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_ATI, 0x4383, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_ATI, 0x439d, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_ATI, 0x4384, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_ATI, 0x4399, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_AMD, 0x780f, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_AMD, 0x7809, pci_quirk_amd_sb_acs }, { PCI_VENDOR_ID_SOLARFLARE, 0x0903, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_SOLARFLARE, 0x0923, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_SOLARFLARE, 0x0A03, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10C6, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10DB, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10DD, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10E1, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10F1, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10F7, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10F8, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10F9, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10FA, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10FB, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10FC, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1507, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1514, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x151C, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1529, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x152A, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x154D, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x154F, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1551, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1558, pci_quirk_mf_endpoint_acs }, /* 82580 */ { PCI_VENDOR_ID_INTEL, 0x1509, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x150E, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x150F, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1510, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1511, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1516, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1527, pci_quirk_mf_endpoint_acs }, /* 82576 */ { PCI_VENDOR_ID_INTEL, 0x10C9, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10E6, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10E7, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10E8, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x150A, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x150D, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1518, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1526, pci_quirk_mf_endpoint_acs }, /* 82575 */ { PCI_VENDOR_ID_INTEL, 0x10A7, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10A9, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10D6, pci_quirk_mf_endpoint_acs }, /* I350 */ { PCI_VENDOR_ID_INTEL, 0x1521, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1522, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1523, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1524, pci_quirk_mf_endpoint_acs }, /* 82571 (Quads omitted due to non-ACS switch) */ { PCI_VENDOR_ID_INTEL, 0x105E, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x105F, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x1060, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x10D9, pci_quirk_mf_endpoint_acs }, /* I219 */ { PCI_VENDOR_ID_INTEL, 0x15b7, pci_quirk_mf_endpoint_acs }, { PCI_VENDOR_ID_INTEL, 0x15b8, pci_quirk_mf_endpoint_acs }, /* Intel PCH root ports */ { PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_intel_pch_acs }, { PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_intel_spt_pch_acs }, { 0x19a2, 0x710, pci_quirk_mf_endpoint_acs }, /* Emulex BE3-R */ { 0x10df, 0x720, pci_quirk_mf_endpoint_acs }, /* Emulex Skyhawk-R */ /* Cavium ThunderX */ { PCI_VENDOR_ID_CAVIUM, PCI_ANY_ID, pci_quirk_cavium_acs }, { 0 } }; int pci_dev_specific_acs_enabled(struct pci_dev *dev, u16 acs_flags) { const struct pci_dev_acs_enabled *i; int ret; /* * Allow devices that do not expose standard PCIe ACS capabilities * or control to indicate their support here. Multi-function express * devices which do not allow internal peer-to-peer between functions, * but do not implement PCIe ACS may wish to return true here. */ for (i = pci_dev_acs_enabled; i->acs_enabled; i++) { if ((i->vendor == dev->vendor || i->vendor == (u16)PCI_ANY_ID) && (i->device == dev->device || i->device == (u16)PCI_ANY_ID)) { ret = i->acs_enabled(dev, acs_flags); if (ret >= 0) return ret; } } return -ENOTTY; } /* Config space offset of Root Complex Base Address register */ #define INTEL_LPC_RCBA_REG 0xf0 /* 31:14 RCBA address */ #define INTEL_LPC_RCBA_MASK 0xffffc000 /* RCBA Enable */ #define INTEL_LPC_RCBA_ENABLE (1 << 0) /* Backbone Scratch Pad Register */ #define INTEL_BSPR_REG 0x1104 /* Backbone Peer Non-Posted Disable */ #define INTEL_BSPR_REG_BPNPD (1 << 8) /* Backbone Peer Posted Disable */ #define INTEL_BSPR_REG_BPPD (1 << 9) /* Upstream Peer Decode Configuration Register */ #define INTEL_UPDCR_REG 0x1114 /* 5:0 Peer Decode Enable bits */ #define INTEL_UPDCR_REG_MASK 0x3f static int pci_quirk_enable_intel_lpc_acs(struct pci_dev *dev) { u32 rcba, bspr, updcr; void __iomem *rcba_mem; /* * Read the RCBA register from the LPC (D31:F0). PCH root ports * are D28:F* and therefore get probed before LPC, thus we can't * use pci_get_slot/pci_read_config_dword here. */ pci_bus_read_config_dword(dev->bus, PCI_DEVFN(31, 0), INTEL_LPC_RCBA_REG, &rcba); if (!(rcba & INTEL_LPC_RCBA_ENABLE)) return -EINVAL; rcba_mem = ioremap_nocache(rcba & INTEL_LPC_RCBA_MASK, PAGE_ALIGN(INTEL_UPDCR_REG)); if (!rcba_mem) return -ENOMEM; /* * The BSPR can disallow peer cycles, but it's set by soft strap and * therefore read-only. If both posted and non-posted peer cycles are * disallowed, we're ok. If either are allowed, then we need to use * the UPDCR to disable peer decodes for each port. This provides the * PCIe ACS equivalent of PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF */ bspr = readl(rcba_mem + INTEL_BSPR_REG); bspr &= INTEL_BSPR_REG_BPNPD | INTEL_BSPR_REG_BPPD; if (bspr != (INTEL_BSPR_REG_BPNPD | INTEL_BSPR_REG_BPPD)) { updcr = readl(rcba_mem + INTEL_UPDCR_REG); if (updcr & INTEL_UPDCR_REG_MASK) { dev_info(&dev->dev, "Disabling UPDCR peer decodes\n"); updcr &= ~INTEL_UPDCR_REG_MASK; writel(updcr, rcba_mem + INTEL_UPDCR_REG); } } iounmap(rcba_mem); return 0; } /* Miscellaneous Port Configuration register */ #define INTEL_MPC_REG 0xd8 /* MPC: Invalid Receive Bus Number Check Enable */ #define INTEL_MPC_REG_IRBNCE (1 << 26) static void pci_quirk_enable_intel_rp_mpc_acs(struct pci_dev *dev) { u32 mpc; /* * When enabled, the IRBNCE bit of the MPC register enables the * equivalent of PCI ACS Source Validation (PCI_ACS_SV), which * ensures that requester IDs fall within the bus number range * of the bridge. Enable if not already. */ pci_read_config_dword(dev, INTEL_MPC_REG, &mpc); if (!(mpc & INTEL_MPC_REG_IRBNCE)) { dev_info(&dev->dev, "Enabling MPC IRBNCE\n"); mpc |= INTEL_MPC_REG_IRBNCE; pci_write_config_word(dev, INTEL_MPC_REG, mpc); } } static int pci_quirk_enable_intel_pch_acs(struct pci_dev *dev) { if (!pci_quirk_intel_pch_acs_match(dev)) return -ENOTTY; if (pci_quirk_enable_intel_lpc_acs(dev)) { dev_warn(&dev->dev, "Failed to enable Intel PCH ACS quirk\n"); return 0; } pci_quirk_enable_intel_rp_mpc_acs(dev); dev->dev_flags |= PCI_DEV_FLAGS_ACS_ENABLED_QUIRK; dev_info(&dev->dev, "Intel PCH root port ACS workaround enabled\n"); return 0; } static int pci_quirk_enable_intel_spt_pch_acs(struct pci_dev *dev) { int pos; u32 cap, ctrl; if (!pci_quirk_intel_spt_pch_acs_match(dev)) return -ENOTTY; pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS); if (!pos) return -ENOTTY; pci_read_config_dword(dev, pos + PCI_ACS_CAP, &cap); pci_read_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, &ctrl); ctrl |= (cap & PCI_ACS_SV); ctrl |= (cap & PCI_ACS_RR); ctrl |= (cap & PCI_ACS_CR); ctrl |= (cap & PCI_ACS_UF); pci_write_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, ctrl); dev_info(&dev->dev, "Intel SPT PCH root port ACS workaround enabled\n"); return 0; } static const struct pci_dev_enable_acs { u16 vendor; u16 device; int (*enable_acs)(struct pci_dev *dev); } pci_dev_enable_acs[] = { { PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_enable_intel_pch_acs }, { PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_enable_intel_spt_pch_acs }, { 0 } }; int pci_dev_specific_enable_acs(struct pci_dev *dev) { const struct pci_dev_enable_acs *i; int ret; for (i = pci_dev_enable_acs; i->enable_acs; i++) { if ((i->vendor == dev->vendor || i->vendor == (u16)PCI_ANY_ID) && (i->device == dev->device || i->device == (u16)PCI_ANY_ID)) { ret = i->enable_acs(dev); if (ret >= 0) return ret; } } return -ENOTTY; } /* * The PCI capabilities list for Intel DH895xCC VFs (device id 0x0443) with * QuickAssist Technology (QAT) is prematurely terminated in hardware. The * Next Capability pointer in the MSI Capability Structure should point to * the PCIe Capability Structure but is incorrectly hardwired as 0 terminating * the list. */ static void quirk_intel_qat_vf_cap(struct pci_dev *pdev) { int pos, i = 0; u8 next_cap; u16 reg16, *cap; struct pci_cap_saved_state *state; /* Bail if the hardware bug is fixed */ if (pdev->pcie_cap || pci_find_capability(pdev, PCI_CAP_ID_EXP)) return; /* Bail if MSI Capability Structure is not found for some reason */ pos = pci_find_capability(pdev, PCI_CAP_ID_MSI); if (!pos) return; /* * Bail if Next Capability pointer in the MSI Capability Structure * is not the expected incorrect 0x00. */ pci_read_config_byte(pdev, pos + 1, &next_cap); if (next_cap) return; /* * PCIe Capability Structure is expected to be at 0x50 and should * terminate the list (Next Capability pointer is 0x00). Verify * Capability Id and Next Capability pointer is as expected. * Open-code some of set_pcie_port_type() and pci_cfg_space_size_ext() * to correctly set kernel data structures which have already been * set incorrectly due to the hardware bug. */ pos = 0x50; pci_read_config_word(pdev, pos, &reg16); if (reg16 == (0x0000 | PCI_CAP_ID_EXP)) { u32 status; #ifndef PCI_EXP_SAVE_REGS #define PCI_EXP_SAVE_REGS 7 #endif int size = PCI_EXP_SAVE_REGS * sizeof(u16); pdev->pcie_cap = pos; pci_read_config_word(pdev, pos + PCI_EXP_FLAGS, &reg16); pdev->pcie_flags_reg = reg16; pci_read_config_word(pdev, pos + PCI_EXP_DEVCAP, &reg16); pdev->pcie_mpss = reg16 & PCI_EXP_DEVCAP_PAYLOAD; pdev->cfg_size = PCI_CFG_SPACE_EXP_SIZE; if (pci_read_config_dword(pdev, PCI_CFG_SPACE_SIZE, &status) != PCIBIOS_SUCCESSFUL || (status == 0xffffffff)) pdev->cfg_size = PCI_CFG_SPACE_SIZE; if (pci_find_saved_cap(pdev, PCI_CAP_ID_EXP)) return; /* * Save PCIE cap */ state = kzalloc(sizeof(*state) + size, GFP_KERNEL); if (!state) return; state->cap.cap_nr = PCI_CAP_ID_EXP; state->cap.cap_extended = 0; state->cap.size = size; cap = (u16 *)&state->cap.data[0]; pcie_capability_read_word(pdev, PCI_EXP_DEVCTL, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_RTCTL, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_DEVCTL2, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_LNKCTL2, &cap[i++]); pcie_capability_read_word(pdev, PCI_EXP_SLTCTL2, &cap[i++]); hlist_add_head(&state->next, &pdev->saved_cap_space); } } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x443, quirk_intel_qat_vf_cap); /* * VMD-enabled root ports will change the source ID for all messages * to the VMD device. Rather than doing device matching with the source * ID, the AER driver should traverse the child device tree, reading * AER registers to find the faulting device. */ static void quirk_no_aersid(struct pci_dev *pdev) { /* VMD Domain */ if (pdev->bus->sysdata && pci_domain_nr(pdev->bus) >= 0x10000) pdev->bus->bus_flags |= PCI_BUS_FLAGS_NO_AERSID; } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2030, quirk_no_aersid); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2031, quirk_no_aersid); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2032, quirk_no_aersid); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2033, quirk_no_aersid);
Java
package ch.dritz.remedy2redmine; import java.io.File; import java.io.IOException; import ch.dritz.common.Config; import ch.dritz.remedy2redmine.modules.SyncModule; /** * Main class for Remedy2Redmine * @author D.Ritz */ public class Main { private static void usage(String msg) { if (msg != null) System.out.println("ERROR: " + msg); System.out.println("Remedy2Redmine " + Version.getVersion()); System.out.println("Usage: Remedy2Redmine <config.properties> <command> [<command specific args>]"); System.out.println(" <command> : one of (sync)"); System.out.println(" <mode specific args> for each mode:"); System.out.println(" - sync: none"); System.out.println("OR: Remedy2Redmine -version"); System.exit(1); } /** * main() entry point * @param args * @throws IOException */ public static void main(String[] args) throws Exception { if (args.length == 1 && "-version".equals(args[0])) { System.out.println("Remedy2Redmine " + Version.getVersion()); return; } if (args.length < 2) usage("Not enough arguments"); File configFile = new File(args[0]); String command = args[1]; Config config = new Config(); config.loadFromFile(configFile); if ("sync".equals(command)) { File syncConfig = new File(configFile.getParentFile(), config.getString("sync.config", "sync.properties")); config.loadFromFile(syncConfig); SyncModule sync = new SyncModule(config); try { sync.start(); } finally { sync.shutdown(); } } else { usage("Unknown command"); } } }
Java
<?php /*------------------------------------------------------------------------ # com_universal_ajaxlivesearch - Universal AJAX Live Search # ------------------------------------------------------------------------ # author Janos Biro # copyright Copyright (C) 2011 Offlajn.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.offlajn.com -------------------------------------------------------------------------*/ // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); require_once(dirname(__FILE__).DS.'image.php'); class OfflajnImageCaching { // BEGIN class OfflajnImageCaching var $cacheDir; var $cacheUrl; function OfflajnImageCaching() { $path = JPATH_SITE.DS.'images'.DS.'ajaxsearch'.DS; if(!is_dir($path)){ mkdir($path);} $this->cacheDir = $path; $this->cacheUrl = JURI::root().'images/ajaxsearch/'; } /* ------------------------------------------------------------------------------ Image methods start */ function generateImage($product_full_image, $w, $h, $product_name, $transparent=true){ if( substr( $product_full_image, 0, 4) == "http" ) { $p = "/".str_replace(array("http","/"),array("http(s{0,1})","\\/"), JURI::base())."/"; $url = preg_replace($p ,JPATH_SITE.DS, $product_full_image); }else{ $product_full_image = str_replace('%20',' ',$product_full_image); if (@is_file(JPATH_SITE.DS.$product_full_image)){ $url = JPATH_SITE.DS.$product_full_image; }elseif(@is_file(IMAGEPATH.'product/'.$product_full_image)){ // VM $url = IMAGEPATH.'product/'.$product_full_image; }elseif(@is_file($product_full_image)){ // VM $url = $product_full_image; }else{ return; } } $cacheName = $this->generateImageCacheName(array($url, $w, $h)); if(!$this->checkImageCache($cacheName)){ if(!$this->createImage($url, $this->cacheDir.$cacheName, $w, $h, $transparent)){ return ''; } } $url = $this->cacheUrl.$cacheName; return "<img width='".$w."' height='".$h."' alt='".$product_name."' src='".$url."' />"; } function createImage($in, $out, $w, $h, $transparent){ $img = null; $img = new OfflajnAJAXImageTool($in); if($img->res === false){ return false; } $img->convertToPng(); if ($transparent) $img->resize($w, $h); else $img->resize2($w, $h); $img->write($out); $img->destroy(); return true; } function checkImageCache($cacheName){ return is_file($this->cacheDir.$cacheName); } function generateImageCacheName($pieces){ return md5(implode('-', $pieces)).'.png'; } /* Image methods end ------------------------------------------------------------------------------ */ } // END class OfflajnImageCaching ?>
Java
package com.gilecode.langlocker; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.gilecode.langlocker"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { super(); } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext * ) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext * ) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given plug-in * relative path * * @param path * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
Java
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: BasePublisherService.php 81439 2012-05-07 23:59:14Z chris.nutting $ */ /** * @package OpenX * @author Andriy Petlyovanyy <apetlyovanyy@lohika.com> * */ // Require Publisher Service Implementation require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php'; /** * Base Publisher Service * */ class BasePublisherService { /** * Reference to Publisher Service implementation. * * @var PublisherServiceImpl $_oPublisherServiceImp */ var $_oPublisherServiceImp; /** * This method initialises Service implementation object field. * */ function BasePublisherService() { $this->_oPublisherServiceImp = new PublisherServiceImpl(); } } ?>
Java
/*************************************************************************** qgsgeometryduplicatenodescheck.cpp --------------------- begin : September 2015 copyright : (C) 2014 by Sandro Mani / Sourcepole AG email : smani at sourcepole dot ch *************************************************************************** * * * 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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsgeometryduplicatenodescheck.h" #include "qgsgeometryutils.h" #include "../utils/qgsfeaturepool.h" void QgsGeometryDuplicateNodesCheck::collectErrors( QList<QgsGeometryCheckError *> &errors, QStringList &/*messages*/, QAtomicInt *progressCounter, const QgsFeatureIds &ids ) const { const QgsFeatureIds &featureIds = ids.isEmpty() ? mFeaturePool->getFeatureIds() : ids; Q_FOREACH ( QgsFeatureId featureid, featureIds ) { if ( progressCounter ) progressCounter->fetchAndAddRelaxed( 1 ); QgsFeature feature; if ( !mFeaturePool->get( featureid, feature ) ) { continue; } QgsGeometry featureGeom = feature.geometry(); QgsAbstractGeometry *geom = featureGeom.geometry(); for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart ) { for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing ) { int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, iPart, iRing ); if ( nVerts < 2 ) continue; for ( int iVert = nVerts - 1, jVert = 0; jVert < nVerts; iVert = jVert++ ) { QgsPoint pi = geom->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); QgsPoint pj = geom->vertexAt( QgsVertexId( iPart, iRing, jVert ) ); if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) < QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() ) { errors.append( new QgsGeometryCheckError( this, featureid, pj, QgsVertexId( iPart, iRing, jVert ) ) ); } } } } } } void QgsGeometryDuplicateNodesCheck::fixError( QgsGeometryCheckError *error, int method, int /*mergeAttributeIndex*/, Changes &changes ) const { QgsFeature feature; if ( !mFeaturePool->get( error->featureId(), feature ) ) { error->setObsolete(); return; } QgsGeometry featureGeom = feature.geometry(); QgsAbstractGeometry *geom = featureGeom.geometry(); QgsVertexId vidx = error->vidx(); // Check if point still exists if ( !vidx.isValid( geom ) ) { error->setObsolete(); return; } // Check if error still applies int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, vidx.part, vidx.ring ); if ( nVerts == 0 ) { error->setObsolete(); return; } QgsPoint pi = geom->vertexAt( QgsVertexId( vidx.part, vidx.ring, ( vidx.vertex + nVerts - 1 ) % nVerts ) ); QgsPoint pj = geom->vertexAt( error->vidx() ); if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) >= QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() ) { error->setObsolete(); return; } // Fix error if ( method == NoChange ) { error->setFixed( method ); } else if ( method == RemoveDuplicates ) { if ( !QgsGeometryCheckerUtils::canDeleteVertex( geom, vidx.part, vidx.ring ) ) { error->setFixFailed( tr( "Resulting geometry is degenerate" ) ); } else if ( !geom->deleteVertex( error->vidx() ) ) { error->setFixFailed( tr( "Failed to delete vertex" ) ); } else { feature.setGeometry( featureGeom ); mFeaturePool->updateFeature( feature ); error->setFixed( method ); changes[error->featureId()].append( Change( ChangeNode, ChangeRemoved, error->vidx() ) ); } } else { error->setFixFailed( tr( "Unknown method" ) ); } } QStringList QgsGeometryDuplicateNodesCheck::getResolutionMethods() const { static QStringList methods = QStringList() << tr( "Delete duplicate node" ) << tr( "No action" ); return methods; }
Java
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Mecab = require('mecab-async'); var mecab = new Mecab(); var MarkovChain = function () { function MarkovChain(text) { _classCallCheck(this, MarkovChain); this.text = text; this.result = null; this.dictionary = {}; this.output = 'output'; } _createClass(MarkovChain, [{ key: 'start', value: function start(sentence, callback) { this.parse(sentence, callback); } }, { key: 'parse', value: function parse(sentence, callback) { var _this = this; mecab.parse(this.text, function (err, result) { _this.dictionary = _this.makeDic(result); _this.makeSentence(_this.dictionary, sentence); callback(_this.output); }); } }, { key: 'makeDic', value: function makeDic(items) { var tmp = ['@']; var dic = {}; for (var i in items) { var t = items[i]; var word = t[0]; word = word.replace(/\s*/, ''); if (word == '' || word == 'EOS') continue; tmp.push(word); if (tmp.length < 3) continue; if (tmp.length > 3) tmp.splice(0, 1); this.setWord3(dic, tmp); if (word == '。') { tmp = ['@']; continue; } } return dic; } }, { key: 'setWord3', value: function setWord3(p, s3) { var w1 = s3[0]; var w2 = s3[1]; var w3 = s3[2]; if (p[w1] == undefined) p[w1] = {}; if (p[w1][w2] == undefined) p[w1][w2] = {}; if (p[w1][w2][w3] == undefined) p[w1][w2][w3] = 0; p[w1][w2][w3]++; } }, { key: 'makeSentence', value: function makeSentence(dic, sentence) { for (var i = 0; i < sentence; i++) { var ret = []; var top = dic['@']; if (!top) continue; var w1 = this.choiceWord(top); var w2 = this.choiceWord(top[w1]); ret.push(w1); ret.push(w2); for (;;) { var w3 = this.choiceWord(dic[w1][w2]); ret.push(w3); if (w3 == '。') break; w1 = w2, w2 = w3; } this.output = ret.join(''); return this.output; } } }, { key: 'objKeys', value: function objKeys(obj) { var r = []; for (var i in obj) { r.push(i); } return r; } }, { key: 'choiceWord', value: function choiceWord(obj) { var ks = this.objKeys(obj); var i = this.rnd(ks.length); return ks[i]; } }, { key: 'rnd', value: function rnd(num) { return Math.floor(Math.random() * num); } }]); return MarkovChain; }(); module.exports = MarkovChain;
Java
{% include 'overall_header.html' %} <h2>{{ lang('ABOUTUS') }}</h2> <div class="panel aboutus"> <div class="inner"> <div class="content"> {{ ABOUTUS_OUTPUT }} </div> {% if TERMS_OF_USE or PRIVACY %} {% if TERMS_OF_USE and PRIVACY %} <h2>{{ lang('TERMS_USE') }} {{ lang('ABOUTUS_AND') }} {{ lang('PRIVACY') }}</h2> <p>{{ lang('DESCRIPTION_PRIVACY_TERMS_OF_USE') }} <a href="{{ U_TERMS_USE }}">{{ lang('TERMS_USE') }}</a> {{ lang('ABOUTUS_AND') }} <a href="{{ U_PRIVACY }}">{{ lang('PRIVACY') }}</a></p> {% elseif PRIVACY %} <h2>{{ lang('PRIVACY') }}</h2> <p>{{ lang('DESCRIPTION_PRIVACY') }} <a href="{{ U_PRIVACY }}">{{ lang('PRIVACY') }}</a></p> {% elseif TERMS_OF_USE %} <h2>{{ lang('TERMS_USE') }}</h2> <p>{{ lang('DESCRIPTION_TERMS_OF_USE') }} <a href="{{ U_TERMS_USE }}">{{ lang('TERMS_USE') }}</a></p> {% endif %} {% endif %} </div> </div> {% include 'overall_footer.html' %}
Java
#include<stdio.h> int main() { int *p,i; int a[10]={12,23,56,1,65,67,87,34,6,23}; p=a; for(i=0;i<10;i++) { printf("%d ",(p+i)); } return 0; }
Java
package org.iatoki.judgels.jerahmeel.user.item; public final class UserItem { private final String userJid; private final String itemJid; private final UserItemStatus status; public UserItem(String userJid, String itemJid, UserItemStatus status) { this.userJid = userJid; this.itemJid = itemJid; this.status = status; } public String getUserJid() { return userJid; } public String getItemJid() { return itemJid; } public UserItemStatus getStatus() { return status; } }
Java
We would like to propose a manuscript submission to the *Methods* section of Ecology Letters, discussing the use of Partially Observed Markov Decision Processes (POMDP) in ecological research questions. Markov Decision Process (MDP) methods have a long history in ecology, particularly in natural resource management such as fisheries or forestry, and in behavioral ecology (where they are commonly called SDP problems, referring to the stochastic dynamic programming method used to solve them.) POMDPs have seen limited application owing to the complexity of solving them and the lack of appropriate software to do so. Recent breakthroughs in the robotics & artificial intelligence community have made POMDPs for large problems tractable, opening the door to a wide array of ecological problems previously considered intractable in an optimal control framework. Our proposed methods paper would present a high quality R package we have developed over several years which leverages a recently developed algorithm for solving POMDP problems. We would illustrate the use of the package on both a classic decision problem from fisheries and in extending a recent Ecology Letters paper of ecosystem services (Dee et al, 2017; which received ESA's Innovation in Sustainability Science award) to account for imperfect observations. We believe that these examples coupled with the user friendly R package would catalyze significant breakthroughs in this critical and timely area of conservation decision making. Authors qualifications: Carl Boettiger, is a theoretical ecologist & assistant professor at UC Berkeley's department Environmental Science, Policy, and Management. Jeroen Ooms is a well-recognized professional software developer with rOpenSci; several of his packages are downloaded over 100,000 times each week. Milad Memarzadeh is a post-doc in Civil & Environmental engineering at UC Berkeley with a PhD from Carnegie Mellon in POMDP methods.
Java
/* * Read flash partition table from command line * * Copyright © 2002 SYSGO Real-Time Solutions GmbH * Copyright © 2002-2010 David Woodhouse <dwmw2@infradead.org> * * 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 2 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * The format for the command line is as follows: * * mtdparts=<mtddef>[;<mtddef] * <mtddef> := <mtd-id>:<partdef>[,<partdef>] * where <mtd-id> is the name from the "cat /proc/mtd" command * <partdef> := <size>[@offset][<name>][ro][lk] * <mtd-id> := unique name used in mapping driver/device (mtd->name) * <size> := standard linux memsize OR "-" to denote all remaining space * <name> := '(' NAME ')' * * Examples: * * 1 NOR Flash, with 1 single writable partition: * edb7312-nor:- * * 1 NOR Flash with 2 partitions, 1 NAND with one * edb7312-nor:256k(ARMboot)ro,-(root);edb7312-nand:-(home) */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/bootmem.h> /* error message prefix */ #define ERRP "mtd: " /* debug macro */ #if 0 #define dbg(x) do { printk("DEBUG-CMDLINE-PART: "); printk x; } while(0) #else #define dbg(x) #endif /* special size referring to all the remaining space in a partition */ #define SIZE_REMAINING UINT_MAX #define OFFSET_CONTINUOUS UINT_MAX struct cmdline_mtd_partition { struct cmdline_mtd_partition *next; char *mtd_id; int num_parts; struct mtd_partition *parts; }; /* mtdpart_setup() parses into here */ static struct cmdline_mtd_partition *partitions; /* the command line passed to mtdpart_setupd() */ static char *cmdline; static int cmdline_parsed = 0; /* * Parse one partition definition for an MTD. Since there can be many * comma separated partition definitions, this function calls itself * recursively until no more partition definitions are found. Nice side * effect: the memory to keep the mtd_partition structs and the names * is allocated upon the last definition being found. At that point the * syntax has been verified ok. */ static struct mtd_partition * newpart(char *s, char **retptr, int *num_parts, int this_part, unsigned char **extra_mem_ptr, int extra_mem_size) { struct mtd_partition *parts; unsigned long size; unsigned long offset = OFFSET_CONTINUOUS; char *name; int name_len; unsigned char *extra_mem; char delim; unsigned int mask_flags; /* fetch the partition size */ if (*s == '-') { /* assign all remaining space to this partition */ size = SIZE_REMAINING; s++; } else { size = memparse(s, &s); if (size < PAGE_SIZE) { printk(KERN_ERR ERRP "partition size too small (%lx)\n", size); return NULL; } } /* fetch partition name and flags */ mask_flags = 0; /* this is going to be a regular partition */ delim = 0; /* check for offset */ if (*s == '@') { s++; offset = memparse(s, &s); } /* now look for name */ if (*s == '(') { delim = ')'; } if (delim) { char *p; name = ++s; p = strchr(name, delim); if (!p) { printk(KERN_ERR ERRP "no closing %c found in partition name\n", delim); return NULL; } name_len = p - name; s = p + 1; } else { name = NULL; name_len = 13; /* Partition_000 */ } /* record name length for memory allocation later */ extra_mem_size += name_len + 1; /* test for options */ if (strncmp(s, "ro", 2) == 0) { mask_flags |= MTD_WRITEABLE; s += 2; } /* if lk is found do NOT unlock the MTD partition*/ if (strncmp(s, "lk", 2) == 0) { mask_flags |= MTD_POWERUP_LOCK; s += 2; } /* test if more partitions are following */ if (*s == ',') { if (size == SIZE_REMAINING) { printk(KERN_ERR ERRP "no partitions allowed after a fill-up partition\n"); return NULL; } /* more partitions follow, parse them */ parts = newpart(s + 1, &s, num_parts, this_part + 1, &extra_mem, extra_mem_size); if (!parts) return NULL; } else { /* this is the last partition: allocate space for all */ int alloc_size; *num_parts = this_part + 1; alloc_size = *num_parts * sizeof(struct mtd_partition) + extra_mem_size; parts = kzalloc(alloc_size, GFP_KERNEL); if (!parts) { printk(KERN_ERR ERRP "out of memory\n"); return NULL; } extra_mem = (unsigned char *)(parts + *num_parts); } /* enter this partition (offset will be calculated later if it is zero at this point) */ parts[this_part].size = size; parts[this_part].offset = offset; parts[this_part].mask_flags = mask_flags; if (name) { strlcpy((char *)extra_mem, name, name_len + 1); } else { sprintf((char *)extra_mem, "Partition_%03d", this_part); } parts[this_part].name = (char *)extra_mem; extra_mem += name_len + 1; dbg(("partition %d: name <%s>, offset %llx, size %llx, mask flags %x\n", this_part, parts[this_part].name, parts[this_part].offset, parts[this_part].size, parts[this_part].mask_flags)); /* return (updated) pointer to extra_mem memory */ if (extra_mem_ptr) *extra_mem_ptr = extra_mem; /* return (updated) pointer command line string */ *retptr = s; /* return partition table */ return parts; } /* * Parse the command line. */ static int mtdpart_setup_real(char *s) { cmdline_parsed = 1; for( ; s != NULL; ) { struct cmdline_mtd_partition *this_mtd; struct mtd_partition *parts; int mtd_id_len; int num_parts; char *p, *mtd_id; mtd_id = s; /* fetch <mtd-id> */ if (!(p = strchr(s, ':'))) { printk(KERN_ERR ERRP "no mtd-id\n"); return 0; } mtd_id_len = p - mtd_id; dbg(("parsing <%s>\n", p+1)); /* * parse one mtd. have it reserve memory for the * struct cmdline_mtd_partition and the mtd-id string. */ parts = newpart(p + 1, /* cmdline */ &s, /* out: updated cmdline ptr */ &num_parts, /* out: number of parts */ 0, /* first partition */ (unsigned char**)&this_mtd, /* out: extra mem */ mtd_id_len + 1 + sizeof(*this_mtd) + sizeof(void*)-1 /*alignment*/); if(!parts) { /* * An error occurred. We're either: * a) out of memory, or * b) in the middle of the partition spec * Either way, this mtd is hosed and we're * unlikely to succeed in parsing any more */ return 0; } /* align this_mtd */ this_mtd = (struct cmdline_mtd_partition *) ALIGN((unsigned long)this_mtd, sizeof(void*)); /* enter results */ this_mtd->parts = parts; this_mtd->num_parts = num_parts; this_mtd->mtd_id = (char*)(this_mtd + 1); strlcpy(this_mtd->mtd_id, mtd_id, mtd_id_len + 1); /* link into chain */ this_mtd->next = partitions; partitions = this_mtd; dbg(("mtdid=<%s> num_parts=<%d>\n", this_mtd->mtd_id, this_mtd->num_parts)); /* EOS - we're done */ if (*s == 0) break; /* does another spec follow? */ if (*s != ';') { printk(KERN_ERR ERRP "bad character after partition (%c)\n", *s); return 0; } s++; } return 1; } /* * Main function to be called from the MTD mapping driver/device to * obtain the partitioning information. At this point the command line * arguments will actually be parsed and turned to struct mtd_partition * information. It returns partitions for the requested mtd device, or * the first one in the chain if a NULL mtd_id is passed in. */ static int parse_cmdline_partitions(struct mtd_info *master, struct mtd_partition **pparts, unsigned long origin) { unsigned long offset; int i; struct cmdline_mtd_partition *part; const char *mtd_id = master->name; /* parse command line */ if (!cmdline_parsed) mtdpart_setup_real(cmdline); for(part = partitions; part; part = part->next) { if ((!mtd_id) || (!strcmp(part->mtd_id, mtd_id))) { for(i = 0, offset = 0; i < part->num_parts; i++) { if (part->parts[i].offset == OFFSET_CONTINUOUS) part->parts[i].offset = offset; else offset = part->parts[i].offset; if (part->parts[i].size == SIZE_REMAINING) part->parts[i].size = master->size - offset; if (offset + part->parts[i].size > master->size) { printk(KERN_WARNING ERRP "%s: partitioning exceeds flash size, truncating\n", part->mtd_id); part->parts[i].size = master->size - offset; part->num_parts = i; } offset += part->parts[i].size; } *pparts = kmemdup(part->parts, sizeof(*part->parts) * part->num_parts, GFP_KERNEL); if (!*pparts) return -ENOMEM; return part->num_parts; } } return 0; } /* * This is the handler for our kernel parameter, called from * main.c::checksetup(). Note that we can not yet kmalloc() anything, * so we only save the commandline for later processing. * * This function needs to be visible for bootloaders. */ static int mtdpart_setup(char *s) { cmdline = s; return 1; } __setup("mtdparts=", mtdpart_setup); static struct mtd_part_parser cmdline_parser = { .owner = THIS_MODULE, .parse_fn = parse_cmdline_partitions, .name = "cmdlinepart", }; static int __init cmdline_parser_init(void) { return register_mtd_parser(&cmdline_parser); } module_init(cmdline_parser_init); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Marius Groeger <mag@sysgo.de>"); MODULE_DESCRIPTION("Command line configuration of MTD partitions");
Java
package FusionInventory::Agent::SNMP::MibSupport::Brocade; use strict; use warnings; use parent 'FusionInventory::Agent::SNMP::MibSupportTemplate'; use FusionInventory::Agent::Tools; use FusionInventory::Agent::Tools::SNMP; use constant brocade => '.1.3.6.1.4.1.1991' ; use constant serial => brocade .'.1.1.1.1.2.0' ; use constant fw_pri => brocade . '.1.1.2.1.11.0' ; our $mibSupport = [ { name => "brocade-switch", sysobjectid => getRegexpOidMatch(brocade) } ]; sub getSerial { my ($self) = @_; return $self->get(serial); } sub getFirmware { my ($self) = @_; return $self->get(fw_pri); } 1; __END__ =head1 NAME Inventory module for Brocade Switches =head1 DESCRIPTION The module enhances Brocade Switches devices support.
Java
#ifndef SC_BOOST_MPL_BOOL_HPP_INCLUDED #define SC_BOOST_MPL_BOOL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /Users/acg/CVSROOT/systemc-2.3/src/sysc/packages/boost/mpl/bool.hpp,v $ // $Date: 2009/10/14 19:11:02 $ // $Revision: 1.2 $ #include <sysc/packages/boost/mpl/bool_fwd.hpp> #include <sysc/packages/boost/mpl/integral_c_tag.hpp> #include <sysc/packages/boost/mpl/aux_/config/static_constant.hpp> SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN template< bool C_ > struct bool_ { SC_BOOST_STATIC_CONSTANT(bool, value = C_); typedef integral_c_tag tag; typedef bool_ type; typedef bool value_type; operator bool() const { return this->value; } }; #if !defined(SC_BOOST_NO_INCLASS_MEMBER_INITIALIZATION) template< bool C_ > bool const bool_<C_>::value; #endif SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE #endif // SC_BOOST_MPL_BOOL_HPP_INCLUDED
Java
#ifndef TPPROTO_COMMANDPARAMETER_H #define TPPROTO_COMMANDPARAMETER_H /* CommandParameter Classes * * Copyright (C) 2008 Aaron Mavrinac and the Thousand Parsec Project * * 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /*! \file \brief Declares CommandParameter classes and the CommandParamType enum. */ #include <string> #include <stdint.h> namespace TPProto{ enum CommandParamType{ cpT_Invalid = -1, cpT_String = 0, cpT_Integer = 1, cpT_Max }; class Buffer; /*! \brief Baseclass for holding a parameter for a Command. */ class CommandParameter{ public: CommandParameter(); CommandParameter(const CommandParameter &rhs); virtual ~CommandParameter(); virtual void packBuffer(Buffer* buf) = 0; virtual bool unpackBuffer(Buffer* buf) = 0; virtual CommandParameter* clone() = 0; virtual bool setValueFromString(const std::string &nval) = 0; std::string getName(); std::string getDescription(); void setName(const std::string &nn); void setDescription(const std::string &nd); private: std::string name; std::string description; }; /*! \brief Holds a string CommandParameter. */ class StringCommandParameter : public CommandParameter{ public: StringCommandParameter(); StringCommandParameter(const StringCommandParameter &rhs); ~StringCommandParameter(); void packBuffer(Buffer* buf); bool unpackBuffer(Buffer* buf); CommandParameter* clone(); bool setValueFromString(const std::string &nval); unsigned int getMaxLength(); std::string getString(); void setString(const std::string &nval); private: unsigned int maxlength; std::string value; }; /*! \brief A CommandParameter that holds an integer. */ class IntegerCommandParameter : public CommandParameter{ public: IntegerCommandParameter(); IntegerCommandParameter(const IntegerCommandParameter &rhs); ~IntegerCommandParameter(); void packBuffer(Buffer* buf); bool unpackBuffer(Buffer* buf); CommandParameter* clone(); bool setValueFromString(const std::string &nval); uint32_t getValue() const; void setValue(uint32_t nval); private: uint32_t value; }; } #endif
Java
require 'test_helper' class CompetencePeriodTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
Java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2. * * 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. * * Test that the file is open for read acces when the applications specify * the value of O_RDWR. * * Step: * 1. Create a file a shared memory object using shm_open(). * 2. Write in the file referenced by the file descriptor return by * shm_open(). * 3. Reopen the file with shm_open() and O_RDWR set. * 4. Read in the file. * The test pass if it read what it was previously written. */ /* ftruncate was formerly an XOPEN extension. We define _XOPEN_SOURCE here to avoid warning if the implementation does not program ftruncate as a base interface */ #define _XOPEN_SOURCE 600 #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include "posixtest.h" #define BUF_SIZE 8 #define SHM_NAME "posixtest_14-2" int main() { int fd; char str[BUF_SIZE] = "qwerty"; char *buf; fd = shm_open(SHM_NAME, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR); if (fd == -1) { perror("An error occurs when calling shm_open()"); return PTS_UNRESOLVED; } if (ftruncate(fd, BUF_SIZE) != 0) { perror("An error occurs when calling ftruncate()"); return PTS_UNRESOLVED; } buf = mmap(NULL, BUF_SIZE, PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { perror("An error occurs when calling mmap()"); return PTS_UNRESOLVED; } strcpy(buf, str); fd = shm_open(SHM_NAME, O_RDWR, S_IRUSR|S_IWUSR); if (fd == -1) { perror("An error occurs when calling shm_open()"); return PTS_UNRESOLVED; } buf = mmap(NULL, BUF_SIZE, PROT_READ, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { perror("An error occurs when calling mmap()"); return PTS_UNRESOLVED; } shm_unlink(SHM_NAME); if (strcmp(buf, str) == 0) { printf("Test PASSED\n"); return PTS_PASS; } printf("Test FAILED\n"); return PTS_FAIL; }
Java
/*************************************************************************** * Copyright (C) 2012 by David Edmundson <kde@davidedmundson.co.uk> * * * * 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 2 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 * ***************************************************************************/ #include "message-view.h" #include "adium-theme-view.h" #include "adium-theme-status-info.h" #include <KTp/message-processor.h> #include <KDebug> #include <KIconLoader> #include <QLabel> #include <QResizeEvent> #include <KTp/Logger/log-manager.h> #include <KTp/Logger/pending-logger-logs.h> #include <TelepathyQt/Account> MessageView::MessageView(QWidget *parent) : AdiumThemeView(parent), m_infoLabel(new QLabel(this)) { loadSettings(); QFont font = m_infoLabel->font(); font.setBold(true); m_infoLabel->setFont(font); m_infoLabel->setAlignment(Qt::AlignCenter); connect(this, SIGNAL(loadFinished(bool)), SLOT(processStoredEvents())); } void MessageView::loadLog(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const Tp::ContactPtr &contact, const QDate &date, const QPair< QDate, QDate > &nearestDates) { if (account.isNull() || !entity.isValid()) { //note contact can be null showInfoMessage(i18n("Unknown or invalid contact")); return; } m_infoLabel->hide(); m_account = account; // FIXME: Workaround for a bug, probably in QGlib which causes that // m_entity = m_entity results in invalid m_entity->m_class being null if (m_entity != entity) { m_entity = entity; } m_contact = m_contact.dynamicCast<Tp::Contact>(contact); m_date = date; m_prev = nearestDates.first; m_next = nearestDates.second; if (entity.entityType() == Tp::HandleTypeRoom) { load(AdiumThemeView::GroupChat); } else { load(AdiumThemeView::SingleUserChat); } Tp::Avatar avatar = m_account->avatar(); if (!avatar.avatarData.isEmpty()) { m_accountAvatar = QString(QLatin1String("data:%1;base64,%2")). arg(avatar.MIMEType.isEmpty() ? QLatin1String("image/*") : avatar.MIMEType). arg(QString::fromLatin1(m_account->avatar().avatarData.toBase64().data())); } KTp::LogManager *logManager = KTp::LogManager::instance(); KTp::PendingLoggerLogs *pendingLogs = logManager->queryLogs(m_account, m_entity, m_date); connect(pendingLogs, SIGNAL(finished(KTp::PendingLoggerOperation*)), SLOT(onEventsLoaded(KTp::PendingLoggerOperation*))); } void MessageView::showInfoMessage(const QString& message) { m_infoLabel->setText(message); m_infoLabel->show(); m_infoLabel->raise(); m_infoLabel->setGeometry(0, 0, width(), height()); } void MessageView::resizeEvent(QResizeEvent* e) { m_infoLabel->setGeometry(0, 0, e->size().width(), e->size().height()); QWebView::resizeEvent(e); } void MessageView::setHighlightText(const QString &text) { m_highlightedText = text; } void MessageView::clearHighlightText() { setHighlightText(QString()); } void MessageView::onEventsLoaded(KTp::PendingLoggerOperation *po) { KTp::PendingLoggerLogs *pl = qobject_cast<KTp::PendingLoggerLogs*>(po); m_events << pl->logs(); /* Wait with initialization for the first event so that we can know when the chat session started */ AdiumThemeHeaderInfo headerInfo; headerInfo.setDestinationDisplayName(m_contact.isNull() ? m_entity.alias() : m_contact->alias()); headerInfo.setChatName(m_contact.isNull() ? m_entity.alias() : m_contact->alias()); headerInfo.setGroupChat(m_entity.entityType() == Tp::HandleTypeRoom); headerInfo.setSourceName(m_account->displayName()); headerInfo.setIncomingIconPath(m_contact.isNull() ? QString() : m_contact->avatarData().fileName); headerInfo.setService(m_account->serviceName()); // check iconPath docs for minus sign in -KIconLoader::SizeMedium headerInfo.setServiceIconPath(KIconLoader::global()->iconPath(m_account->iconName(), -KIconLoader::SizeMedium)); if (pl->logs().count() > 0) { headerInfo.setTimeOpened(pl->logs().first().time()); } initialise(headerInfo); } bool logMessageOlderThan(const KTp::LogMessage &e1, const KTp::LogMessage &e2) { return e1.time() < e2.time(); } bool logMessageNewerThan(const KTp::LogMessage &e1, const KTp::LogMessage &e2) { return e1.time() > e2.time(); } void MessageView::processStoredEvents() { AdiumThemeStatusInfo prevConversation; if (m_prev.isValid()) { prevConversation = AdiumThemeStatusInfo(AdiumThemeMessageInfo::HistoryStatus); prevConversation.setMessage(QString(QLatin1String("<a href=\"#x-prevConversation\">&lt;&lt;&lt; %1</a>")).arg(i18n("Older conversation"))); prevConversation.setTime(QDateTime(m_prev)); } AdiumThemeStatusInfo nextConversation; if (m_next.isValid()) { nextConversation = AdiumThemeStatusInfo(AdiumThemeMessageInfo::HistoryStatus); nextConversation.setMessage(QString(QLatin1String("<a href=\"#x-nextConversation\">%1 &gt;&gt;&gt;</a>")).arg(i18n("Newer conversation"))); nextConversation.setTime(QDateTime(m_next)); } if (m_sortMode == MessageView::SortOldestTop) { if (m_prev.isValid()) { addAdiumStatusMessage(nextConversation); } qSort(m_events.begin(), m_events.end(), logMessageOlderThan); } else if (m_sortMode == MessageView::SortNewestTop) { if (m_next.isValid()) { addAdiumStatusMessage(prevConversation); } qSort(m_events.begin(), m_events.end(), logMessageNewerThan); } if (m_events.isEmpty()) { showInfoMessage(i18n("There are no logs for this day")); } while (!m_events.isEmpty()) { const KTp::LogMessage msg = m_events.takeFirst(); KTp::MessageContext ctx(m_account, Tp::TextChannelPtr()); KTp::Message message = KTp::MessageProcessor::instance()->processIncomingMessage(msg, ctx); addMessage(message); } if (m_sortMode == MessageView::SortOldestTop && m_next.isValid()) { addAdiumStatusMessage(prevConversation); } else if (m_sortMode == MessageView::SortNewestTop && m_prev.isValid()) { addAdiumStatusMessage(nextConversation); } /* Can't highlight the text directly, we need to wait for the JavaScript in * AdiumThemeView to include the log messages into DOM. */ QTimer::singleShot(100, this, SLOT(doHighlightText())); } void MessageView::onLinkClicked(const QUrl &link) { // Don't emit the signal directly, KWebView does not like when we reload the // page from an event handler (and then chain up) and we can't guarantee // that everyone will use QueuedConnection when connecting to // conversationSwitchRequested() slot if (link.fragment() == QLatin1String("x-nextConversation")) { // Q_EMIT conversationSwitchRequested(m_next) QMetaObject::invokeMethod(this, "conversationSwitchRequested", Qt::QueuedConnection, Q_ARG(QDate, m_next)); return; } if (link.fragment() == QLatin1String("x-prevConversation")) { // Q_EMIT conversationSwitchRequested(m_prev) QMetaObject::invokeMethod(this, "conversationSwitchRequested", Qt::QueuedConnection, Q_ARG(QDate, m_prev)); return; } AdiumThemeView::onLinkClicked(link); } void MessageView::loadSettings() { const KConfig config(QLatin1String("ktelepathyrc")); const KConfigGroup group = config.group("LogViewer"); m_sortMode = static_cast<SortMode>(group.readEntry("SortMode", static_cast<int>(SortOldestTop))); } void MessageView::reloadTheme() { loadSettings(); loadLog(m_account, m_entity, m_contact, m_date, qMakePair(m_prev, m_next)); } void MessageView::doHighlightText() { findText(QString()); if (!m_highlightedText.isEmpty()) { findText(m_highlightedText, QWebPage::HighlightAllOccurrences | QWebPage::FindWrapsAroundDocument); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_17) on Mon Jan 11 20:36:42 NZDT 2010 --> <TITLE> weka.classifiers.functions Class Hierarchy </TITLE> <META NAME="date" CONTENT="2010-01-11"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="weka.classifiers.functions Class Hierarchy"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/classifiers/evaluation/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../weka/classifiers/functions/neural/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/classifiers/functions/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package weka.classifiers.functions </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">weka.classifiers.<A HREF="../../../weka/classifiers/Classifier.html" title="class in weka.classifiers"><B>Classifier</B></A> (implements weka.core.<A HREF="../../../weka/core/CapabilitiesHandler.html" title="interface in weka.core">CapabilitiesHandler</A>, java.lang.Cloneable, weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</A>, java.io.Serializable) <UL> <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/GaussianProcesses.html" title="class in weka.classifiers.functions"><B>GaussianProcesses</B></A> (implements weka.classifiers.<A HREF="../../../weka/classifiers/IntervalEstimator.html" title="interface in weka.classifiers">IntervalEstimator</A>, weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/IsotonicRegression.html" title="class in weka.classifiers.functions"><B>IsotonicRegression</B></A> (implements weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/LeastMedSq.html" title="class in weka.classifiers.functions"><B>LeastMedSq</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/LibLINEAR.html" title="class in weka.classifiers.functions"><B>LibLINEAR</B></A> (implements weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/LibSVM.html" title="class in weka.classifiers.functions"><B>LibSVM</B></A> (implements weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/LinearRegression.html" title="class in weka.classifiers.functions"><B>LinearRegression</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/Logistic.html" title="class in weka.classifiers.functions"><B>Logistic</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/MultilayerPerceptron.html" title="class in weka.classifiers.functions"><B>MultilayerPerceptron</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/Randomizable.html" title="interface in weka.core">Randomizable</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/PaceRegression.html" title="class in weka.classifiers.functions"><B>PaceRegression</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/PLSClassifier.html" title="class in weka.classifiers.functions"><B>PLSClassifier</B></A><LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/RBFNetwork.html" title="class in weka.classifiers.functions"><B>RBFNetwork</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/SimpleLinearRegression.html" title="class in weka.classifiers.functions"><B>SimpleLinearRegression</B></A> (implements weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/SimpleLogistic.html" title="class in weka.classifiers.functions"><B>SimpleLogistic</B></A> (implements weka.core.<A HREF="../../../weka/core/AdditionalMeasureProducer.html" title="interface in weka.core">AdditionalMeasureProducer</A>, weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/SMO.html" title="class in weka.classifiers.functions"><B>SMO</B></A> (implements weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/SMOreg.html" title="class in weka.classifiers.functions"><B>SMOreg</B></A> (implements weka.core.<A HREF="../../../weka/core/AdditionalMeasureProducer.html" title="interface in weka.core">AdditionalMeasureProducer</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.core.<A HREF="../../../weka/core/WeightedInstancesHandler.html" title="interface in weka.core">WeightedInstancesHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/VotedPerceptron.html" title="class in weka.classifiers.functions"><B>VotedPerceptron</B></A> (implements weka.core.<A HREF="../../../weka/core/OptionHandler.html" title="interface in weka.core">OptionHandler</A>, weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>) <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/Winnow.html" title="class in weka.classifiers.functions"><B>Winnow</B></A> (implements weka.core.<A HREF="../../../weka/core/TechnicalInformationHandler.html" title="interface in weka.core">TechnicalInformationHandler</A>, weka.classifiers.<A HREF="../../../weka/classifiers/UpdateableClassifier.html" title="interface in weka.classifiers">UpdateableClassifier</A>) </UL> <LI TYPE="circle">weka.classifiers.functions.<A HREF="../../../weka/classifiers/functions/SMO.BinarySMO.html" title="class in weka.classifiers.functions"><B>SMO.BinarySMO</B></A> (implements java.io.Serializable) </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/classifiers/evaluation/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../weka/classifiers/functions/neural/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/classifiers/functions/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
field_dict={'ROME-FIELD-01':[ 267.835895375 , -30.0608178195 , '17:51:20.6149','-30:03:38.9442' ], 'ROME-FIELD-02':[ 269.636745458 , -27.9782661111 , '17:58:32.8189','-27:58:41.758' ], 'ROME-FIELD-03':[ 268.000049542 , -28.8195573333 , '17:52:00.0119','-28:49:10.4064' ], 'ROME-FIELD-04':[ 268.180171708 , -29.27851275 , '17:52:43.2412','-29:16:42.6459' ], 'ROME-FIELD-05':[ 268.35435 , -30.2578356389 , '17:53:25.044','-30:15:28.2083' ], 'ROME-FIELD-06':[ 268.356124833 , -29.7729819283 , '17:53:25.47','-29:46:22.7349' ], 'ROME-FIELD-07':[ 268.529571333 , -28.6937071111 , '17:54:07.0971','-28:41:37.3456' ], 'ROME-FIELD-08':[ 268.709737083 , -29.1867251944 , '17:54:50.3369','-29:11:12.2107' ], 'ROME-FIELD-09':[ 268.881108542 , -29.7704673333 , '17:55:31.4661','-29:46:13.6824' ], 'ROME-FIELD-10':[ 269.048498333 , -28.6440675 , '17:56:11.6396','-28:38:38.643' ], 'ROME-FIELD-11':[ 269.23883225 , -29.2716684211 , '17:56:57.3197','-29:16:18.0063' ], 'ROME-FIELD-12':[ 269.39478875 , -30.0992361667 , '17:57:34.7493','-30:05:57.2502' ], 'ROME-FIELD-13':[ 269.563719375 , -28.4422328996 , '17:58:15.2927','-28:26:32.0384' ], 'ROME-FIELD-14':[ 269.758843 , -29.1796030365 , '17:59:02.1223','-29:10:46.5709' ], 'ROME-FIELD-15':[ 269.78359875 , -29.63940425 , '17:59:08.0637','-29:38:21.8553' ], 'ROME-FIELD-16':[ 270.074981708 , -28.5375585833 , '18:00:17.9956','-28:32:15.2109' ], 'ROME-FIELD-17':[ 270.81 , -28.0978333333 , '18:03:14.4','-28:05:52.2' ], 'ROME-FIELD-18':[ 270.290886667 , -27.9986032778 , '18:01:09.8128','-27:59:54.9718' ], 'ROME-FIELD-19':[ 270.312763708 , -29.0084241944 , '18:01:15.0633','-29:00:30.3271' ], 'ROME-FIELD-20':[ 270.83674125 , -28.8431573889 , '18:03:20.8179','-28:50:35.3666' ]}
Java
<?php include("config_mynonprofit.php"); include("connect.php"); //Start session session_start(); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Sanitize the POST values $fname = htmlentities($_POST['fname']); $lname = htmlentities($_POST['lname']); $email = htmlentities($_POST['email']); $username = htmlentities($_POST['username']); $member_type = htmlentities($_POST['member_type']); $password = htmlentities($_POST['password']); $cpassword = htmlentities($_POST['cpassword']); $today = date('Y-m-d H:i:s'); $hash = md5($today); //Input Validations if ($fname == '') { $errmsg_arr[] = 'First name missing'; $errflag = true; } if ($lname == '') { $errmsg_arr[] = 'Last name missing'; $errflag = true; } if ($email == '') { $errmsg_arr[] = 'Email missing'; $errflag = true; } if ($username == '') { $errmsg_arr[] = 'Username missing'; $errflag = true; } if ($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if ($cpassword == '') { $errmsg_arr[] = 'Confirm password missing'; $errflag = true; } if (strcmp($password, $cpassword) != 0) { $errmsg_arr[] = 'Passwords do not match'; $errflag = true; } //Check for duplicate username if ($username != '') { $query = $db->prepare('SELECT * FROM members WHERE username=:username'); $query->execute(array('username' => $username)); if ($query->rowCount() > 0) { $errmsg_arr[] = 'Username already in use'; $errflag = true; } } //If there are input validations, redirect back to the registration form if ($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: registration.php"); exit(); } $password2 = md5($password); if ($member_type != 'General') { $to = 'ruthwitte@gmail.com, bjwitte@gmail.com'; $subject = 'New member requesting membership type.'; $body = 'New member ' . $username . ' ' . $fname . ' ' . $lname . ' ' . $email . ' requesting membership type of ' . $member_type . ''; $headers = "From: mygp@growingplaces.cc\r\n" . mail($to, $subject, $body, $headers); } //Create INSERT query $query2 = $db->prepare('INSERT INTO members(firstname, lastname, email, username, password, date_registered, member_type, confirm_hash, auth_type) VALUES(:fname,:lname,:email,:username,:password,:today ,"General",:hash, 0)'); $result = $query2->execute(array('fname' => $fname, 'lname' => $lname, 'email' => $email, 'username' => $username, 'password' => $password2, 'today' => $today, 'hash' => $hash)); $member_id = $db->lastInsertId('member_id'); if (is_array($_POST['volunteertypes'])) { $query4 = $db->prepare('INSERT INTO volunteer_types_by_member (volunteer_type_id, member_id) VALUES (:checked ,:member_id)'); foreach ($_POST['volunteertypes'] as $checked) { $query4->execute(array('checked' => $checked, 'member_id' => $member_id)); } } //Check whether the query was successful or not if ($result) { $to = $email; $subject = "" . $site_name . " Confirmation"; $message = "<html><head><title>" . $site_name . " Confirmation</title></head><body><p> Click the following link to confirm your registration information.</p><a href='http://www.growingplaces.cc/mygp/confirm.php?confirm=" . $hash . "'>http://www.growingplaces.cc/mygp/confirm.php?confirm=" . $hash . "</a>"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "From: mygp@growingplaces.cc\r\n"; $mailed = mail($to, $subject, $message, $headers); header("location: register-success.php"); exit(); } else { die("Query failed"); } ?>
Java
<script type="text/javascript"> jQuery(document).ready(function() { // type of media jQuery('#type').change(function() { switch (jQuery(this).val()) { case '<?php echo MEDIA_TYPE_EMAIL; ?>': jQuery('#smtp_server, #smtp_helo, #smtp_email').closest('li').removeClass('hidden'); jQuery('#exec_path, #gsm_modem, #jabber_username, #eztext_username, #eztext_limit, #passwd') .closest('li') .addClass('hidden'); jQuery('#eztext_link').addClass('hidden'); break; case '<?php echo MEDIA_TYPE_EXEC; ?>': jQuery('#exec_path').closest('li').removeClass('hidden'); jQuery('#smtp_server, #smtp_helo, #smtp_email, #gsm_modem, #jabber_username, #eztext_username, #eztext_limit, #passwd') .closest('li') .addClass('hidden'); jQuery('#eztext_link').addClass('hidden'); break; case '<?php echo MEDIA_TYPE_SMS; ?>': jQuery('#gsm_modem').closest('li').removeClass('hidden'); jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #jabber_username, #eztext_username, #eztext_limit, #passwd') .closest('li') .addClass('hidden'); jQuery('#eztext_link').addClass('hidden'); break; case '<?php echo MEDIA_TYPE_JABBER; ?>': jQuery('#jabber_username, #passwd').closest('li').removeClass('hidden'); jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #gsm_modem, #eztext_username, #eztext_limit') .closest('li') .addClass('hidden'); jQuery('#eztext_link').addClass('hidden'); break; case '<?php echo MEDIA_TYPE_EZ_TEXTING; ?>': jQuery('#eztext_username, #eztext_limit, #passwd').closest('li').removeClass('hidden'); jQuery('#eztext_link').removeClass('hidden'); jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #gsm_modem, #jabber_username') .closest('li') .addClass('hidden'); break; } }); // clone button jQuery('#clone').click(function() { jQuery('#mediatypeid, #delete, #clone').remove(); jQuery('#update span').text(<?php echo CJs::encodeJson(_('Add')); ?>); jQuery('#update').val('mediatype.create').attr({id: 'add'}); jQuery('#cancel').addClass('ui-corner-left'); jQuery('#description').focus(); }); // trim spaces on sumbit jQuery('#mediaTypeForm').submit(function() { jQuery('#description').val(jQuery.trim(jQuery('#description').val())); jQuery('#smtp_server').val(jQuery.trim(jQuery('#smtp_server').val())); jQuery('#smtp_helo').val(jQuery.trim(jQuery('#smtp_helo').val())); jQuery('#smtp_email').val(jQuery.trim(jQuery('#smtp_email').val())); jQuery('#exec_path').val(jQuery.trim(jQuery('#exec_path').val())); jQuery('#gsm_modem').val(jQuery.trim(jQuery('#gsm_modem').val())); jQuery('#jabber_username').val(jQuery.trim(jQuery('#jabber_username').val())); jQuery('#eztext_username').val(jQuery.trim(jQuery('#eztext_username').val())); }); // refresh field visibility on document load jQuery('#type').trigger('change'); }); </script>
Java
/* OS134, Copyright (C) 2005, Benjamin Stein, Jaap Weel, Ting Liao -- 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Loader. loads an a.out into the memory. */ /* The starting address for the text (code) section - 64K of code. */ #define I_ADDRESS 0x600000 /* The starting address for the data section - 64K of data. */ #define D_ADDRESS 0x800000 typedef unsigned short uint16_t; typedef unsigned long uint32_t; typedef struct { uint16_t magic __PACKED__; /* Magic number. */ uint16_t version __PACKED__; /* Version number. */ uint32_t code_size __PACKED__; /* Text segment size. */ uint32_t data_size __PACKED__; /* Initialized data size. */ uint32_t bss_size __PACKED__; /* Uninitialized data size. */ uint32_t syms_size __PACKED__; uint32_t entry __PACKED__; uint32_t code_offset __PACKED__; uint32_t data_offset __PACKED__; } aout_head_t; /* 28 bytes */ /* * Since the OS does not have File I/O code yet, we need an image * pointer that points to the file I have not figured out a way to do * that yet, one reason is that we have no file system in the OS yet. */ /* * Entry is the entry point of the program. */ int load_aout(char *filename, unsigned char *image, unsigned *entry) { /* * Load the a.out format file filename. * * Read the text segment from the file to I_ADDRESS. * * Read the data segment from the file to D_ADDRESS. Zero out the BSS segment. * * Create and map in a stack segment (usually separate from the data * segment, since the data heap and stack grow separately.) Place * arguments from the command line or calling program on the stack. * * Set registers appropriately and jump to the starting address. */ aout_head_t *aout; /* Validate headers. */ aout = (aout_head_t *) image; image += sizeof(aout_head_t); /* Move to the code section. */ /* Get entry point. */ (*entry) = aout->entry; /* Load text to I_ADDRESS. * * Copy aout->code_size bytes of code starting at image + * code_offset to I_ADDRESS. */ image += aout->code_size; /* Load DATA to D_ADDRESS. * * Copy aout->data_size bytes of code starting at image + * data_offset to D_ADDRESS. */ image += aout->data_size; /* Set uninitialized data to 0. */ /* Copy bss_size bytes of 0 starting at D_ADDRESS + aout->data_size. */ }
Java
/************************************************** * Funkcje związane z geolokalizacją GPS **************************************************/ WMB.Comment = { /** * Funkcja dodająca nowy komentarz do zgłoszenia * * @method onAddSubmit */ onAddSubmit: function(marker_id) { if (WMB.User.isLoggedIn()) { if ($('#add-comment-form')[0].checkValidity()) { var post_data = new FormData(); post_data.append('user_id', parseInt(getCookie('user_id'))); post_data.append('marker_id', parseInt(marker_id)); post_data.append('comment', $('#comment').val()); $.ajax({ url: REST_API_URL + 'comment', beforeSend: function(request) { request.setRequestHeader('Authorization', 'Token ' + getCookie('token')); }, type: 'POST', cache: false, processData: false, contentType: false, data: post_data, success: function(s) { $('#add-comment-modal').modal('hide'); bootbox.alert('Pomyślnie dodaną komentarz.', function() { location.reload(); }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('#add-comment-modal').modal('hide'); var response = JSON.parse(XMLHttpRequest.responseText); bootbox.alert(response.message); } }); } } else { bootbox.alert('Aby móc dodawać komentarze musisz być zalogowany.'); } }, onEditClick: function(id) { // Pobranie danych o komentarzu $.ajax({ url: REST_API_URL + 'comment/id/' + id, type: 'GET', success: function(data) { // Wstawienie danych do formularza $('#comment_id').val(id); $('#comment').val(data.comment); $('#edit-comment-modal').modal('show'); }, error: function(XMLHttpRequest, textStatus, errorThrown) { var response = JSON.parse(XMLHttpRequest.responseText); bootbox.alert(response.message, function() { window.location.href = WEBSITE_URL; }); } }); }, onEditSubmit: function() { if ($('#edit-comment-form')[0].checkValidity()) { var comment_data = new FormData(), comment_id = parseInt($('#comment_id').val()), comment = $('#comment').val(); comment_data.append('comment', comment); $.ajax({ url: REST_API_URL + 'comment/id/' + comment_id + '/edit', beforeSend: function (request) { request.setRequestHeader('Authorization', 'Token ' + getCookie('token')); }, type: 'POST', cache: false, processData: false, contentType: false, data: comment_data, success: function(s) { $('#edit-comment-modal').modal('hide'); bootbox.alert('Pomyślnie zedytowano komentarz.', function() { window.location.href = WEBSITE_URL + 'comments'; }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { var response = JSON.parse(XMLHttpRequest.responseText); bootbox.alert(response.message); } }); } }, onDeleteClick: function(id) { $.ajax({ url: REST_API_URL + 'comment/id/' + id, beforeSend: function (request) { request.setRequestHeader('Authorization', 'Token ' + getCookie('token')); }, type: 'DELETE', cache: false, processData: false, contentType: false, success: function(data) { $('#edit-comment-modal').modal('hide'); bootbox.alert('Pomyślnie usunięto komentarz.', function() { location.reload(); }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { var response = JSON.parse(XMLHttpRequest.responseText); bootbox.alert(response.message, function() { window.location.href = WEBSITE_URL; }); } }); }, /** * Funkcja służąca do zmiany statusu komentarza * * @method changeStatus * @param {Integer} id Identyfikator komentarza * @param {Integer} status_id Identyfikator statusu */ changeStatus: function(id, status_id) { if (WMB.User.isLoggedIn()) { $.ajax({ url: REST_API_URL + 'comment/id/' + id + '/status/' + status_id, beforeSend: function (request) { request.setRequestHeader('Authorization', 'Token ' + getCookie('token')); }, type: 'PUT', cache: false, processData: false, contentType: false, success: function(data) { if (status_id == 0) { bootbox.alert('Pomyślnie zgłoszono nadużycie w komentarzu.', function() { location.reload(); }); } else { bootbox.alert('Pomyślnie zmieniono status komentarza na ' + comment_statuses[status_id] + '.', function() { location.reload(); }); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { var response = JSON.parse(XMLHttpRequest.responseText); bootbox.alert(response.message, function() { window.location.href = WEBSITE_URL; }); } }); } else { bootbox.alert('Aby zgłosić nadużycie musisz być zalogowany/a.'); } }, /** * Funkcja pobierająca wszystkie komentarze dla danego zgłoszenia * * @method getAll * @param {Integer} marker_id Identyfikator zgłoszenia */ getAll: function(marker_id) { $.ajax({ url: REST_API_URL + 'comment/marker/' + marker_id, type: 'GET', cache: false, dataType: 'json', success: function(data) { $.each(data.comments, function(i) { if (data.comments[i].status_id != 0 && data.comments[i].user_id == parseInt(getCookie('user_id'))) { $('#marker-comment-list').append( '<tr>' + '<td>' + data.comments[i].login + '</td>' + '<td>' + data.comments[i].date + '</td>' + '<td>' + data.comments[i].comment + '</td>' + '<td>brak</td>' + '</tr>'); } else if (data.comments[i].status_id != 0) { $('#marker-comment-list').append( '<tr>' + '<td>' + data.comments[i].login + '</td>' + '<td>' + data.comments[i].date + '</td>' + '<td>' + data.comments[i].comment + '</td>' + '<td><a href="#" onclick="WMB.Comment.changeStatus(' + data.comments[i].comment_id + ', 0)">Zgłoś nadużycie</a></td>' + '</tr>'); } }); } }); } }
Java
<h2>Methods run, sorted chronologically</h2><h3>&gt;&gt; means before, &lt;&lt; means after</h3><p/><br/><em>Default suite</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/> <table border="1"> <tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr> <tr bgcolor="756c8c"> <td>15/10/03 22:12:02</td> <td>0</td> <td>&nbsp;</td><td title="&gt;&gt;InitializeWebDriver.setUp()[pri:0, instance:testcases.module.login.LoginTest@4b5bc191]">&gt;&gt;setUp</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td> <td>main@63390789</td> <td></td> </tr> <tr bgcolor="756c8c"> <td>15/10/03 22:14:00</td> <td>118087</td> <td>&nbsp;</td><td title="&lt;&lt;InitializeWebDriver.tearDown()[pri:0, instance:testcases.module.login.LoginTest@4b5bc191]">&lt;&lt;tearDown</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td> <td>main@63390789</td> <td></td> </tr> <tr bgcolor="e09bd6"> <td>15/10/03 22:13:25</td> <td>83119</td> <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td title="LoginTest.testcaseone()[pri:0, instance:testcases.module.login.LoginTest@4b5bc191]">testcaseone</td> <td>main@63390789</td> <td></td> </tr> </table>
Java
/*********************************************** * Author: Alexander Oro Acebo * Date: 01/22/2015 * Description: Change current dir * ********************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/shm.h> #include "../include/RootDir.h" #include "../include/fatSupport.h" #include "../include/Shared_Info.h" #define BYTES_TO_READ_IN_BOOT_SECTOR 512 #define BLUE "\x1B[1;36m" // for listing directories as blue #define RESET "\033[0m" #define BOLD "\033[1m" FILE* FILE_SYSTEM_ID; int BYTES_PER_SECTOR; char* NEW_DIR; Shared_Info *CUR_DIR; void usage(); char* readFile(char*, char*[]); char* readFileNonRoot(char*); void getSharedMem(int, key_t, char*, char*); void createSharedMem(int, key_t, char*, char*); char* readFAT12Table(char*); int main(int argc, char *argv[]) { int fd[2], nbytes; int i = 0, j = 0; char *buffer; int shmid; key_t key; char *shm, *s, *pch, tmp[9], *tmp_cur; CUR_DIR = malloc(sizeof(Shared_Info)); // Read shared memory from terminal getSharedMem(shmid, key, shm, s); char *trunk[CUR_DIR->FLC]; if (argc != 2) { usage(); return 1; } NEW_DIR = malloc(sizeof(argv)); strcpy(NEW_DIR, argv[argc - 1]); FILE_SYSTEM_ID = fopen(CUR_DIR->img, "r+"); if (FILE_SYSTEM_ID == NULL) { fprintf(stderr, "Could not open the floppy drive or image.\n"); exit(1); } // Set it to this only to read the boot sector BYTES_PER_SECTOR = BYTES_TO_READ_IN_BOOT_SECTOR; buffer = (char*) malloc(32 * sizeof(char)); if (strcmp(NEW_DIR, "..") != 0) { tmp_cur = malloc(sizeof(CUR_DIR->path)); strcpy(tmp_cur, CUR_DIR->path); i = 0; pch = strtok(tmp_cur, " /"); while (pch != NULL) { trunk[i] = pch; pch = strtok(NULL, " /"); i++; } if (strcmp(CUR_DIR->path, "/") == 0) buffer = readFile(buffer, trunk); // Read directory sectors into buffer else buffer = readFileNonRoot(buffer); } else { tmp_cur = malloc(sizeof(CUR_DIR->path)); strcpy(tmp_cur, CUR_DIR->path); pch = strtok(tmp_cur, " /"); while (pch != NULL) { strcpy(tmp, pch); pch = strtok(NULL, " /"); } strcpy(tmp_cur, CUR_DIR->path); strcpy(CUR_DIR->path, "/"); pch = strtok(tmp_cur, " /"); while (strcmp(pch, tmp) != 0) { strcat(CUR_DIR->path, pch); strcat(CUR_DIR->path, "/"); pch = strtok(NULL, " /"); } CUR_DIR->FLC = CUR_DIR->OLD_FLC; } // Free data free(buffer); buffer = NULL; fclose(FILE_SYSTEM_ID); // Push new shared data to terminal createSharedMem(shmid, key, shm, s); exit(EXIT_SUCCESS); } char* readFAT12Table(char* buffer) { int i = 0; // Read in FAT table to buffer for (i = 1; i <= 9; i++) { if (read_sector(i, (buffer + BYTES_PER_SECTOR * (i - 1))) == -1) { fprintf(stderr, "Something has gone wrong -- could not read the sector\n"); } } return buffer; } void createSharedMem(int shmid, key_t key, char * shm, char * s) { key = 5678; int i = 0; Shared_Info* tmp; if ((shmid = shmget(key, sizeof(Shared_Info*), IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if ((tmp = shmat(shmid, NULL, 0)) == (Shared_Info*) -1) { perror("shmat"); exit(1); } tmp = CUR_DIR; tmp = NULL; //s = shm; // Write current path to shared memory //for (i = 0; i < sizeof(CUR_DIR->path); i++) // *s++ = CUR_DIR->path[i]; //*s = NULL; } void getSharedMem(int shmid, key_t key, char * shm, char * s) { key = 5678; int i = 0; Shared_Info* tmp; if ((shmid = shmget(key, sizeof(Shared_Info*), 0666)) < 0) { perror("shmget"); exit(1); } if ((tmp = shmat(shmid, NULL, 0)) == (Shared_Info*) -1) { perror("shmat"); exit(1); } CUR_DIR = tmp; //i = 0; //for(s = shm; *s != NULL; s++) { // CUR_DIR->path[i] = *s; // i++; //} } char* readFileNonRoot(char* buffer) { int fat, start_sector = CUR_DIR->FLC, i = 0, j = 0, attrib, tmp1, tmp2; // Allocate memory char *sector = (char*) malloc(BYTES_PER_SECTOR * sizeof(char)); char *fat_buffer = (char*) malloc(9 * BYTES_PER_SECTOR * sizeof(char)); char tmp[9]; fat_buffer = readFAT12Table(fat_buffer); // Read fat table into buffer while (1) { if (read_sector(start_sector, sector) == -1) { // Read data sector fprintf(stderr, "Something has gone wrong -- could not read the boot sector\n"); } i = 0; j = 0; while (i < 512) { for (j = 0; j < 32; j++) buffer[j] = sector[j + i]; attrib = ( (int) buffer[11] ); // if is subdir if (attrib == 16) { // read subdir name into tmp for (j = 0; j < 8; j++) tmp[j] = buffer[j]; tmp[strlen(NEW_DIR)] = '\0'; NEW_DIR[strlen(NEW_DIR)] = '\0'; // compare if (strcmp(NEW_DIR, tmp) == 0) { strcat(CUR_DIR->path, NEW_DIR); strcat(CUR_DIR->path, "/"); tmp1 = ( ( (int) buffer[27] ) << 8 ) & 0x0000ff00; tmp2 = ( (int) buffer[26] ) & 0x000000ff; CUR_DIR->FLC = tmp1 | tmp2; CUR_DIR->FLC += 33 - 2; break; } } i += 32; } //printf("\n"); //printf("%s\n", sector); // Display data sector contents fat = get_fat_entry(start_sector - 33 + 2, fat_buffer); // Get fat entrie from table buffer if (fat >= 4088 && fat <= 4095) { // Last cluster in file break; } else if (fat >= 4080 && fat <= 4086) { // Reserved cluster break; } else if (fat == 0 || fat == 4087) { // Unused OR Bad cluster break; } else { // Next cluster in file start_sector = fat + 33 - 2; } } // Free memory free(sector); free(buffer); sector = NULL; buffer = NULL; } char* readFile(char* buffer, char* trunk[]) { int i = 0, j = 0, bytes_read, attrib, tmp1, tmp2; char tmp[9]; fpos_t position; i = CUR_DIR->FLC * 512; fseek(FILE_SYSTEM_ID, i, SEEK_SET); // Set pos to beginning file while (1) { bytes_read = fread(buffer, sizeof(char), 32, FILE_SYSTEM_ID); // read 32 bytes at a time into buffer attrib = ( (int) buffer[11] ); // if is subdir if (attrib == 16) { // read subdir name into tmp for (j = 0; j < 8; j++) tmp[j] = buffer[j]; tmp[strlen(NEW_DIR)] = '\0'; NEW_DIR[strlen(NEW_DIR)] = '\0'; // compare if (strcmp(NEW_DIR, tmp) == 0) { strcat(CUR_DIR->path, NEW_DIR); strcat(CUR_DIR->path, "/"); tmp1 = ( ( (int) buffer[27] ) << 8 ) & 0x0000ff00; tmp2 = ( (int) buffer[26] ) & 0x000000ff; CUR_DIR->FLC = tmp1 | tmp2; CUR_DIR->FLC += 33 - 2; break; } } if (i >= 32 * 512) { // If i has incrimented to the end of the root dir break fprintf(stderr, "ERROR: directory '%s' does not exist\n", NEW_DIR); break; } i = i + 32; } return buffer; } void usage() { printf("\nusage: cd (/path/to/SUBDIR)\n\n"); }
Java
<?php /** * * Share On extension for the phpBB Forum Software package. * * @copyright (c) 2015 Vinny <https://github.com/vinny> * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ » “ ” … // $lang = array_merge($lang, array( 'SO_SELECT' => 'Κοινοποίηση στο', 'SHARE_TOPIC' => 'Κοινοποίηση αυτού του θέματος στο', 'SHARE_POST' => 'Κοινοποίηση αυτής της απάντησης στο', // Share On viewtopic.php 'SHARE_ON_FACEBOOK' => 'Κοινοποίηση στο Facebook', 'SHARE_ON_TWITTER' => 'Κοινοποίηση στο Twitter', 'SHARE_ON_TUENTI' => 'Κοινοποίηση στο Tuenti', 'SHARE_ON_DIGG' => 'Κοινοποίηση στο Digg', 'SHARE_ON_REDDIT' => 'Κοινοποίηση στο Reddit', 'SHARE_ON_DELICIOUS' => 'Κοινοποίηση στο Delicious', 'SHARE_ON_VK' => 'Κοινοποίηση στο VK', 'SHARE_ON_TUMBLR' => 'Κοινοποίηση στο Tumblr', 'SHARE_ON_GOOGLE' => 'Κοινοποίηση στο Google+', 'SHARE_ON_WHATSAPP' => 'Κοινοποίηση στο Whatsapp', 'SHARE_ON_POCKET' => 'Κοινοποίηση στο Pocket', ));
Java
<?xml version="1.0" encoding="US-ASCII"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Example: bib2xhtml -s named -n Spinellis -U -c -R</title> <meta http-equiv="Content-type" content="text/html; charset=US-ASCII" /> <meta name="Generator" content="http://www.spinellis.gr/sw/textproc/bib2xhtml/" /> </head> <body> <!-- BEGIN BIBLIOGRAPHY example --> <!-- DO NOT MODIFY THIS BIBLIOGRAPHY BY HAND! IT IS MAINTAINED AUTOMATICALLY! YOUR CHANGES WILL BE LOST THE NEXT TIME IT IS UPDATED! --> <!-- Generated by: bib2xhtml.pl -s named -n Spinellis -U -c -R -h Example: bib2xhtml -s named -n Spinellis -U -c -R example.bib eg/named-n-c-UCR.html --> <dl class="bib2xhtml"> <!-- Authors: somelongidtotestbibtexlinebreaks --> <dt><a name="somelongidtotestbibtexlinebreaks">[somelongidtotestbibtexlinebreaks]</a></dt><dd>somelongidtotestbibtexlinebreaks. somelongidtotestbibtexlinebreaks.</dd> <!-- Authors: Ken Thompson --> <dt><a name="Thompson:1968">[Thompson, 1968]</a></dt><dd>Ken Thompson. Programming techniques: Regular expression search algorithm. <cite>Communications of the ACM</cite>, 11(6):419&#x2013;422, 1968. (<a href="http://dx.doi.org/10.1145/363347.363387">doi:10.1145/363347.363387</a>)</dd> <!-- Authors: Alfred V Aho and John E Hopcroft and Jeffrey D Ullman --> <dt><a name="RedDragon">[Aho et&nbsp;al., 1974]</a></dt><dd>Alfred&nbsp;V. Aho, John&nbsp;E. Hopcroft, and Jeffrey&nbsp;D. Ullman. <cite>The Design and Analysis of Computer Algorithms</cite>. Addison-Wesley, Reading, MA, 1974.</dd> <!-- Authors: Harold Abelson and Gerald Jay Sussman and Jullie Sussman --> <dt><a name="SICP">[Abelson et&nbsp;al., 1985]</a></dt><dd>Harold Abelson, Gerald&nbsp;Jay Sussman, and Jullie Sussman. <cite>Structure and Interpretation of Computer Programs</cite>. MIT Press, Cambridge, 1985.</dd> <!-- Authors: Adele Goldberg and David Robson --> <dt><a name="Smalltalk">[Goldberg and Robson, 1989]</a></dt><dd>Adele Goldberg and David Robson. <cite>Smalltalk-80: The Language</cite>. Addison-Wesley, Reading, MA, 1989.</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:1990">[Spinellis, 1990]</a></dt><dd><strong>Diomidis Spinellis</strong>. An implementation of the Haskell language. Master's thesis, Imperial College, London, UK, June 1990. (<a href="http://www.dmst.aueb.gr/dds/pubs/thesis/MEng/html/haskell.pdf">PDF</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:1993">[Spinellis, 1993]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/1993-StrProg-Haskell/html/exp.html">Implementing Haskell: Language implementation as a tool building exercise</a>. <cite>Structured Programming (Software Concepts and Tools)</cite>, 14:37&#x2013;48, 1993.</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:1994">[Spinellis, 1994]</a></dt><dd><strong>Diomidis Spinellis</strong>. <cite>Programming Paradigms as Object Classes: A Structuring Mechanism for Multiparadigm Programming</cite>. PhD thesis, Imperial College of Science, Technology and Medicine, London, UK, February 1994. (<a href="http://www.dmst.aueb.gr/dds/pubs/thesis/PhD/html/thesis.pdf">PDF</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:1996">[Spinellis, 1996]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/tr/rfc-1947/html/RFC1947.html">Greek character encoding for electronic mail messages</a>. Network Information Center, Request for Comments 1947, May 1996. RFC-1947.</dd> <!-- Authors: Stefanos Gritzalis and Diomidis Spinellis and Panagiotis Georgiadis --> <dt><a name="Gritzalis:1999">[Gritzalis et&nbsp;al., 1999]</a></dt><dd>Stefanos Gritzalis, <strong>Diomidis Spinellis</strong>, and Panagiotis Georgiadis. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/1997-CompComm-Formal/html/formal.htm">Security protocols over open networks and distributed systems: Formal methods for their analysis, design, and verification</a>. <cite>Computer Communications</cite>, 22(8):695&#x2013;707, May 1999. (<a href="http://dx.doi.org/10.1016/S0140-3664(99)00030-4">doi:10.1016/S0140-3664(99)00030-4</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:2000">[Spinellis, 2000]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/conf/2000-Usenix-outwit/html/utool.html">Outwit: Unix tool-based programming meets the Windows world</a>. In Christopher Small, editor, <cite>USENIX 2000 Technical Conference Proceedings</cite>, pages 149&#x2013;158, Berkeley, CA, June 2000. Usenix Association.</dd> <!-- Authors: Albert Laszlo Barabasi and Monica Ferreira da Silva and F Paterno and Wladyslaw M Turski and Sten AAke Tarnlund and Ketil Bo and J Encarnaccao and Deltaiotaomicronmuetadeltaetavarsigma Sigmapiiotanuepsilonlambdalambdaetavarsigma and Pesster vCuezog --> <dt><a name="XXX00">[Barab&#xe1;si et&nbsp;al., 2000]</a></dt><dd>Albert-L&#xe1;szl&#xf3; Barab&#xe1;si, M&#xf4;nica&nbsp;Ferreira da&nbsp;Silva, F.&nbsp;Patern&#xf2;, W&#x142;adys&#x142;aw&nbsp;M. Turski, Sten-&#xc5;ke T&#xe4;rnlund, Ketil B&#xf8;, J.&nbsp;Encarna&#xe7;&#xe3;o, &#x394;&#x3b9;&#x3bf;&#x3bc;&#x3b7;&#x3b4;&#x3b7;&#x3c2; &#x3a3;&#x3c0;&#x3b9;&#x3bd;&#x3b5;&#x3bb;&#x3bb;&#x3b7;&#x3c2;, and P&#xeb;&#xdf;t&#xea;r &#x10c;&#x115;&#x17c;&#x14d;&#x121;. Cite this paper. <cite>&#xa1;Journal of Authors Against ASCII!</cite>, 45(281):69&#x2013;77, 2000.</dd> <!-- Authors: Elizabeth Zwicky and Simon Cooper and D Brent Chapman --> <dt><a name="Firewalls">[Zwicky et&nbsp;al., 2000]</a></dt><dd>Elizabeth Zwicky, Simon Cooper, and D. Brent Chapman. <cite>Building Internet Firewalls</cite>. O'Reilly and Associates, Sebastopol, CA, second edition, 2000.</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:2003">[Spinellis, 2003]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2003-CACM-URLcite/html/urlcite.html">The decay and failures of web references</a>. <cite>Communications of the ACM</cite>, 46(1):71&#x2013;77, January 2003. (<a href="http://dx.doi.org/10.1145/602421.602422">doi:10.1145/602421.602422</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spinellis:2003b">[Spinellis, 2003]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2003-TSE-Refactor/html/Spi03r.html">Global analysis and transformations in preprocessed languages</a>. <cite>IEEE Transactions on Software Engineering</cite>, 29(11):1019&#x2013;1030, November 2003. (<a href="http://dx.doi.org/10.1109/TSE.2003.1245303">doi:10.1109/TSE.2003.1245303</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="CodeReading">[Spinellis, 2003]</a></dt><dd><strong>Diomidis Spinellis</strong>. <a href="http://www.spinellis.gr/codereading"><cite>Code Reading: The Open Source Perspective</cite></a>. Effective Software Development Series. Addison-Wesley, Boston, MA, 2003.</dd> <!-- Authors: Stephanos Androutsellis Theotokis and Diomidis Spinellis --> <dt><a name="Androutsellis:2004">[Androutsellis-Theotokis and Spinellis, 2004]</a></dt><dd>Stephanos Androutsellis-Theotokis and <strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2004-ACMCS-p2p/html/AS04.html">A survey of peer-to-peer content distribution technologies</a>. <cite>ACM Computing Surveys</cite>, 36(4):335&#x2013;371, December 2004. (<a href="http://dx.doi.org/10.1145/1041680.1041681">doi:10.1145/1041680.1041681</a>)</dd> <!-- Authors: Diomidis Spinellis --> <dt><a name="Spi06i">[Spinellis, 2006]</a></dt><dd><strong>Diomidis Spinellis</strong>. Open source and professional advancement. <cite>IEEE Software</cite>, 23(5):70&#x2013;71, September/October 2006. (<a href="eg/v23n5.pdf">PDF</a>, 116157 bytes) (<a href="http://dx.doi.org/10.1109/MS.2006.136">doi:10.1109/MS.2006.136</a>)</dd> <!-- Authors: First&#x107; Last&#x17e; and Second Third&#xe4;&#xf6;&#xfc; --> <dt><a name="testingUTFcharacters2018a">[Last&#x17e; and Third&#xe4;&#xf6;&#xfc;, 2018]</a></dt><dd>First&#x107; Last&#x17e; and Second Third&#xe4;&#xf6;&#xfc;. Just a title. In <cite>Pattern Recognition</cite>, 2018.</dd> </dl> <!-- END BIBLIOGRAPHY example --> </body></html>
Java
# -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from kgrants.items import KgrantsItem from scrapy.http import Request import time class GrantsSpider(Spider): name = "grants" allowed_domains = ["www.knightfoundation.org"] pages = 1 base_url = 'http://www.knightfoundation.org' start_url_str = 'http://www.knightfoundation.org/grants/?sort=title&page=%s' def __init__(self, pages=None, *args, **kwargs): super(GrantsSpider, self).__init__(*args, **kwargs) if pages is not None: self.pages = pages self.start_urls = [ self.start_url_str % str(page) for page in xrange(1,int(self.pages)+1)] def parse(self, response): hxs = Selector(response) projects = hxs.xpath('//article') for project in projects: time.sleep(2) project_url = self.base_url + ''.join(project.xpath('a/@href').extract()) grants = KgrantsItem() grants['page'] = project_url grants['project'] = ''.join(project.xpath('a/div/header/h1/text()').extract()).strip() grants['description'] = ''.join(project.xpath('p/text()').extract()).strip() yield Request(grants['page'], callback = self.parse_project, meta={'grants':grants}) def parse_project(self,response): hxs = Selector(response) grants = response.meta['grants'] details = hxs.xpath('//section[@id="grant_info"]') fields = hxs.xpath('//dt') values = hxs.xpath('//dd') self.log('field: <%s>' % fields.extract()) for item in details: grants['fiscal_agent'] = ''.join(item.xpath('header/h2/text()').extract()).strip() count = 0 for field in fields: normalized_field = ''.join(field.xpath('text()').extract()).strip().lower().replace(' ','_') self.log('field: <%s>' % normalized_field) try: grants[normalized_field] = values.xpath('text()').extract()[count] except: if normalized_field == 'community': grants[normalized_field] = values.xpath('a/text()').extract()[1] elif normalized_field == 'focus_area': grants[normalized_field] = values.xpath('a/text()').extract()[0] count += 1 grants['grantee_contact_email'] = ''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/@href').extract()).replace('mailto:','').strip() grants['grantee_contact_name'] = ''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/text()').extract()).strip() grants['grantee_contact_location'] = ''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="location"]/text()').extract()).strip() grants['grantee_contact_facebook'] = ''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="facebook"]/a/@href').extract()).strip() grants['grantee_contact_twitter'] = item.xpath('section[@id="grant_contact"]/ul/li[@class="twitter"]/a/@href').extract() grants['grantee_contact_website'] = item.xpath('section[@id="grant_contact"]/ul/li[@class="website"]/a/@href').extract() if 'grant_period' in grants: grant_period = grants['grant_period'].split(' to ') grants['grant_period_start'] = grant_period[0] grants['grant_period_end'] = grant_period[1] yield grants
Java
/* Theme Name: achdut-israel Theme URI: http://underscores.me/ Author: Ido Barnea Author URI: http://www.barbareshet.co.il Description: Achdut Israel\'s theme for website Version: 1.0.0 License: GNU General Public License v2 or later License URI: LICENSE Text Domain: achdut Tags: This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. achdut-israel is based on Underscores http://underscores.me/, (C) 2012-2016 Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2 or later. Normalizing styles have been helped along thanks to the fine work of Nicolas Gallagher and Jonathan Neal http://necolas.github.io/normalize.css/ */ /* Globals */ @import url("https://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans:400,700"); body { font-family: "Open Sans", sans-serif; } .no-border { border: none; } #site-footer { min-height: 250px; background-color: #333333; color: #fff; } /* Elements*/ header#masthead { background: #0088ba; } header #top-bar { color: #ffffff; } #masthead .navbar-inverse{ background-color: #0088ba; border-color: #0088ba; overflow: hidden; border-bottom: 5px solid #fff; } .navbar-inverse{ background-color: #0088ba; border-color: #0088ba; } .navbar { border-radius: 0; margin-bottom: 0; } .navbar .nav li a { text-transform: uppercase; font-size: 2.5rem; font-width: 600; color: #000000; } .navbar .nav li.active a { color: #ffffff; } .navbar.affix { position: fixed; right: 0; left: 0; top: 0; z-index: 9999; } #main-menu li.menu-item.active a:after { content: ""; display: block; width: 15px; height: 15px; background: #fff; position: absolute; bottom: -10px; left: 40%; transform: rotate(45deg); } #page-title, .section-title { text-align: center; text-transform: capitalize; font-family: "Montserrat", sans-serif; font-size: 2em; } .btn-readmore { border-radius: 20px; } .divider { width: 85%; border-top-color: #ddd; } /* Layouts */ #hero { background: url("assets/img/AdobeStock_56249320_Preview.jpeg") no-repeat center center; background-size: cover; height: 450px; margin-bottom: 15px; } #hero #page-title, #hero #post-title { text-transform: capitalize; text-align: center; font-weight: bold; font-size: 4.3em; color: #ffffff; } #hero .title-wrap { position: absolute; max-width: 1150px; top: 30%; transform: translateY(-50%); } .hp-gallery-image-wrap{ overflow: hidden; padding: 5px; max-height: 250px; } .hp-gallery-image-wrap:before{ background-color: rgba(0,0,0,0.4); content: ""; position: absolute; right: 5px; left: 5px; top: 5px; bottom: 5px; transition: all .3s ease-in-out; overflow: hidden; } .hp-gallery-image{ height: 250; width: 100%; transition: all .5s ease-in-out; } .hp-gallery-image-wrap:hover:before { background-color: rgba(0,0,0,0); } .hp-gallery-image-wrap:hover .hp-gallery-image{ transform: scale(1.4) rotate(5deg); } .breaker { min-height: 200px; background-color: #9cbbd3; color: #333; border-bottom: 3px solid navy; padding: 50px; margin-top: 15px; margin-bottom: 15px; } .btn-wrap{ margin-top: 30px; margin-bottom: 15px; } a.btn, a.btn:hover, a.btn:visited{ color: #fff; } .btn-default{ background: #9cbbd3; } #activities .event a.btn:before{ content: ""; display: block; width: 25px; height: 25px; background: #fff; position: absolute; right: -10px; transform: rotate(45deg); top:-12px; } #activities .event a.btn:after{ content: ""; display: block; width: 25px; height: 25px; background: #fff; position: absolute; right: -10px; transform: rotate(45deg); bottom: -12px; } #activities .event a.btn{ border-radius: 0; overflow: hidden; } #activities .event .thumbnail { border: 5px solid navy; color: #333; border-radius: 0; padding: 7px; height: 180px; } #activities .event .thumbnail .event-title { font-weight: bold; } #activities .event .thumbnail ul { list-style-type: none; padding-left: 0; margin-left: 0; } #activities .event .thumbnail a.btn-event { border: none; box-shadow: none; text-align: right; position: absolute; right: 25px; bottom: 35px; } /*#activities .event .thumbnail:hover {*/ /*box-shadow: ;*/ /*}*/ #events-option-2 .inner-row, #events .inner-row{ margin-top: 15px; padding-top: 15px; } #events-option-2 .event-date .date, #events .event-date .date{ font-size: 4em; font-weight: bold; } #events-option-2 .event-date .month, #events .event-date .month{ display: block; position: absolute; top: 18px; left: 85px; } #events-option-2 .event-info .event-title, #events .event-info .event-title{ font-weight: 600; letter-spacing: 2px; font-size: 2.3rem; } #events-option-2 .event-readmore, #events .event-readmore{ text-align: center; } #events-option-2 .event-readmore a.btn-readmore, #events .event-readmore a.btn-readmore{ margin-top: 25px; } #events-option-2 .event-divider, #events .event-divider{ text-align: center; width: 75%; } /* Pages*/ #gallery .gal-img { margin-top: 15px; } .thumbnail.no-border { border: none; } .thumbnail.no-border .tm-text { line-height: 1.4; } .btn-readmore{ text-transform: capitalize; } #hp-blog .blog-item .thumbnail{ min-height:600px; } #hp-blog .blog-item .thumbnail .read-more-wrap{ position: absolute; bottom: 35px; right: 25px; } #contact-info .fa{ color: #9cbbd3; } /* Media*/ /*Plugins*/ .slick-slider img { margin: 0 auto; } .slick-arrow { position: absolute; top: 100px; z-index: 999; } .fa-chevron-right { right: 0; } .fa-chevron-left { left: 0; } /* Fonts*/ .single-events #event-information, .single-events #event-information a{ color: #fff; font-size:18px; } .upcoming-list{ padding-left: 0; margin-left: 0; list-style-type: none; } .upcoming-list .coming-event{ font-size: 18px; line-height: 1.5; margin-bottom: 5px; } .upcoming-list .coming-event small{ font-size: 14px; } .footer-widget ul{ padding-left: 0; margin-left: 0; list-style-type: none; } .footer-widget ul li{ } .footer-widget ul li a{ color: #fff; text-transform: capitalize; } footer .site-info a{ color: #fff; } #masthead .navbar-inverse .navbar-nav>.active>a, #masthead .navbar-inverse .navbar-nav>.active>a:focus, #masthead .navbar-inverse .navbar-nav>.active>a:hover{ background-color: #0A246A; color: #ffffff; } .ceremonies.ceremony{ margin-top: 10px; min-height: 350px; } .blog article.col-sm-6.blog-post{ min-height:460px; }
Java
/** * */ package co.innovate.rentavoz.services.almacen.impl; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import co.innovate.rentavoz.model.Tercero; import co.innovate.rentavoz.model.almacen.Cuota; import co.innovate.rentavoz.model.almacen.venta.Venta; import co.innovate.rentavoz.repositories.GenericRepository; import co.innovate.rentavoz.repositories.almacen.CuotaDao; import co.innovate.rentavoz.services.almacen.CuotaService; import co.innovate.rentavoz.services.impl.GenericServiceImpl; /** * @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a> * @project rentavoz3 * @class CuotaServiceImpl * @date 7/02/2014 * */ @Service("cuotaService") public class CuotaServiceImpl extends GenericServiceImpl<Cuota, Integer> implements CuotaService,Serializable { /** * 7/02/2014 * @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a> * serialVersionUID */ private static final long serialVersionUID = 1L; @Autowired private CuotaDao cuotaDao; /* (non-Javadoc) * @see co.innovate.rentavoz.services.impl.GenericServiceImpl#getDao() */ @Override public GenericRepository<Cuota, Integer> getDao() { return cuotaDao; } /* (non-Javadoc) * @see co.innovate.rentavoz.services.almacen.CuotaService#buscarCuotasPendientesPorCliente(co.innovate.rentavoz.model.Tercero) */ @Override public List<Cuota> buscarCuotasPendientesPorCliente(Tercero cliente) { return cuotaDao.buscarCuotasPendientesPorCliente(cliente); } /* (non-Javadoc) * @see co.innovate.rentavoz.services.almacen.CuotaService#buscarRutaDeCuotasPorCobrador(co.innovate.rentavoz.model.Tercero) */ @Override public List<Cuota> buscarRutaDeCuotasPorCobrador(Tercero cobrador) { return cuotaDao.buscarRutaDeCuotasPorCobrador(cobrador); } /* (non-Javadoc) * @see co.innovate.rentavoz.services.almacen.CuotaService#findByVenta(co.innovate.rentavoz.model.almacen.venta.Venta) */ @Override public List<Cuota> findByVenta(Venta venta) { return cuotaDao.findByVenta(venta); } /* (non-Javadoc) * @see co.innovate.rentavoz.services.almacen.CuotaService#findDeudoresMorosos(java.util.Date) */ @Override public List<Tercero> findDeudoresMorosos(Date fechaCierre) { return cuotaDao.findDeudoresMorosos(fechaCierre); } }
Java
;(function() { /** Used to access the Firebug Lite panel (set by `run`). */ var fbPanel; /** Used as a safe reference for `undefined` in pre ES5 environments. */ var undefined; /** Used as a reference to the global object. */ var root = typeof global == 'object' && global || this; /** Method and object shortcuts. */ var phantom = root.phantom, amd = root.define && define.amd, argv = root.process && process.argv, document = !phantom && root.document, noop = function() {}, params = root.arguments, system = root.system; /** Add `console.log()` support for Narwhal, Rhino, and RingoJS. */ var console = root.console || (root.console = { 'log': root.print }); /** The file path of the Lo-Dash file to test. */ var filePath = (function() { var min = 0, result = []; if (phantom) { result = params = phantom.args; } else if (system) { min = 1; result = params = system.args; } else if (argv) { min = 2; result = params = argv; } else if (params) { result = params; } var last = result[result.length - 1]; result = (result.length > min && !/perf(?:\.js)?$/.test(last)) ? last : '../lodash.js'; if (!amd) { try { result = require('fs').realpathSync(result); } catch(e) {} try { result = require.resolve(result); } catch(e) {} } return result; }()); /** Used to match path separators. */ var rePathSeparator = /[\/\\]/; /** Used to detect primitive types. */ var rePrimitive = /^(?:boolean|number|string|undefined)$/; /** Used to match RegExp special characters. */ var reSpecialChars = /[.*+?^=!:${}()|[\]\/\\]/g; /** The `ui` object. */ var ui = root.ui || (root.ui = { 'buildPath': basename(filePath, '.js'), 'otherPath': 'underscore' }); /** The Lo-Dash build basename. */ var buildName = root.buildName = basename(ui.buildPath, '.js'); /** The other library basename. */ var otherName = root.otherName = (function() { var result = basename(ui.otherPath, '.js'); return result + (result == buildName ? ' (2)' : ''); }()); /** Used to score performance. */ var score = { 'a': [], 'b': [] }; /** Used to queue benchmark suites. */ var suites = []; /** Used to resolve a value's internal [[Class]]. */ var toString = Object.prototype.toString; /** Detect if in a browser environment. */ var isBrowser = isHostType(root, 'document') && isHostType(root, 'navigator'); /** Detect if in a Java environment. */ var isJava = !isBrowser && /Java/.test(toString.call(root.java)); /** Use a single "load" function. */ var load = (typeof require == 'function' && !amd) ? require : (isJava && root.load) || noop; /** Load Lo-Dash. */ var lodash = root.lodash || (root.lodash = ( lodash = load(filePath) || root._, lodash = lodash._ || lodash, (lodash.runInContext ? lodash.runInContext(root) : lodash), lodash.noConflict() )); /** Load Benchmark.js. */ var Benchmark = root.Benchmark || (root.Benchmark = ( Benchmark = load('../vendor/benchmark.js/benchmark.js') || root.Benchmark, Benchmark = Benchmark.Benchmark || Benchmark, Benchmark.runInContext(lodash.extend({}, root, { '_': lodash })) )); /** Load Underscore. */ var _ = root._ || (root._ = ( _ = load('../vendor/underscore/underscore.js') || root._, _._ || _ )); /*--------------------------------------------------------------------------*/ /** * Gets the basename of the given `filePath`. If the file `extension` is passed, * it will be removed from the basename. * * @private * @param {string} path The file path to inspect. * @param {string} extension The extension to remove. * @returns {string} Returns the basename. */ function basename(filePath, extension) { var result = (filePath || '').split(rePathSeparator).pop(); return (arguments.length < 2) ? result : result.replace(RegExp(extension.replace(reSpecialChars, '\\$&') + '$'), ''); } /** * Computes the geometric mean (log-average) of an array of values. * See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms. * * @private * @param {Array} array The array of values. * @returns {number} The geometric mean. */ function getGeometricMean(array) { return Math.pow(Math.E, lodash.reduce(array, function(sum, x) { return sum + Math.log(x); }, 0) / array.length) || 0; } /** * Gets the Hz, i.e. operations per second, of `bench` adjusted for the * margin of error. * * @private * @param {Object} bench The benchmark object. * @returns {number} Returns the adjusted Hz. */ function getHz(bench) { var result = 1 / (bench.stats.mean + bench.stats.moe); return isFinite(result) ? result : 0; } /** * Host objects can return type values that are different from their actual * data type. The objects we are concerned with usually return non-primitive * types of "object", "function", or "unknown". * * @private * @param {*} object The owner of the property. * @param {string} property The property to check. * @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`. */ function isHostType(object, property) { if (object == null) { return false; } var type = typeof object[property]; return !rePrimitive.test(type) && (type != 'object' || !!object[property]); } /** * Logs text to the console. * * @private * @param {string} text The text to log. */ function log(text) { console.log(text + ''); if (fbPanel) { // Scroll the Firebug Lite panel down. fbPanel.scrollTop = fbPanel.scrollHeight; } } /** * Runs all benchmark suites. * * @private (@public in the browser) */ function run() { fbPanel = (fbPanel = root.document && document.getElementById('FirebugUI')) && (fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) && fbPanel.getElementById('fbPanel1'); log('\nSit back and relax, this may take a while.'); suites[0].run({ 'async': !isJava }); } /*--------------------------------------------------------------------------*/ lodash.extend(Benchmark.Suite.options, { 'onStart': function() { log('\n' + this.name + ':'); }, 'onCycle': function(event) { log(event.target); }, 'onComplete': function() { for (var index = 0, length = this.length; index < length; index++) { var bench = this[index]; if (bench.error) { var errored = true; } } if (errored) { log('There was a problem, skipping...'); } else { var formatNumber = Benchmark.formatNumber, fastest = this.filter('fastest'), fastestHz = getHz(fastest[0]), slowest = this.filter('slowest'), slowestHz = getHz(slowest[0]), aHz = getHz(this[0]), bHz = getHz(this[1]); if (fastest.length > 1) { log('It\'s too close to call.'); aHz = bHz = slowestHz; } else { var percent = ((fastestHz / slowestHz) - 1) * 100; log( fastest[0].name + ' is ' + formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) + '% faster.' ); } // Add score adjusted for margin of error. score.a.push(aHz); score.b.push(bHz); } // Remove current suite from queue. suites.shift(); if (suites.length) { // Run next suite. suites[0].run({ 'async': !isJava }); } else { var aMeanHz = getGeometricMean(score.a), bMeanHz = getGeometricMean(score.b), fastestMeanHz = Math.max(aMeanHz, bMeanHz), slowestMeanHz = Math.min(aMeanHz, bMeanHz), xFaster = fastestMeanHz / slowestMeanHz, percentFaster = formatNumber(Math.round((xFaster - 1) * 100)), message = 'is ' + percentFaster + '% ' + (xFaster == 1 ? '' : '(' + formatNumber(xFaster.toFixed(2)) + 'x) ') + 'faster than'; // Report results. if (aMeanHz >= bMeanHz) { log('\n' + buildName + ' ' + message + ' ' + otherName + '.'); } else { log('\n' + otherName + ' ' + message + ' ' + buildName + '.'); } } } }); /*--------------------------------------------------------------------------*/ lodash.extend(Benchmark.options, { 'async': true, 'setup': '\ var _ = global._,\ lodash = global.lodash,\ belt = this.name == buildName ? lodash : _;\ \ var date = new Date,\ limit = 20,\ regexp = /x/,\ object = {},\ objects = Array(limit),\ numbers = Array(limit),\ fourNumbers = [5, 25, 10, 30],\ nestedNumbers = [1, [2], [3, [[4]]]],\ nestedObjects = [{}, [{}], [{}, [[{}]]]],\ twoNumbers = [12, 23];\ \ for (var index = 0; index < limit; index++) {\ numbers[index] = index;\ object["key" + index] = index;\ objects[index] = { "num": index };\ }\ var strNumbers = numbers + "";\ \ if (typeof bind != "undefined") {\ var thisArg = { "name": "fred" };\ \ var func = function(greeting, punctuation) {\ return (greeting || "hi") + " " + this.name + (punctuation || ".");\ };\ \ var _boundNormal = _.bind(func, thisArg),\ _boundMultiple = _boundNormal,\ _boundPartial = _.bind(func, thisArg, "hi");\ \ var lodashBoundNormal = lodash.bind(func, thisArg),\ lodashBoundMultiple = lodashBoundNormal,\ lodashBoundPartial = lodash.bind(func, thisArg, "hi");\ \ for (index = 0; index < 10; index++) {\ _boundMultiple = _.bind(_boundMultiple, { "name": "fred" + index });\ lodashBoundMultiple = lodash.bind(lodashBoundMultiple, { "name": "fred" + index });\ }\ }\ if (typeof bindAll != "undefined") {\ var bindAllCount = -1,\ bindAllObjects = Array(this.count);\ \ var funcNames = belt.reject(belt.functions(belt).slice(0, 40), function(funcName) {\ return /^_/.test(funcName);\ });\ \ // Potentially expensive.\n\ for (index = 0; index < this.count; index++) {\ bindAllObjects[index] = belt.reduce(funcNames, function(object, funcName) {\ object[funcName] = belt[funcName];\ return object;\ }, {});\ }\ }\ if (typeof chaining != "undefined") {\ var even = function(v) { return v % 2 == 0; },\ square = function(v) { return v * v; };\ \ var largeArray = belt.range(10000),\ _chaining = _.chain ? _(largeArray).chain() : _(largeArray),\ lodashChaining = lodash(largeArray);\ }\ if (typeof compact != "undefined") {\ var uncompacted = numbers.slice();\ uncompacted[2] = false;\ uncompacted[6] = null;\ uncompacted[18] = "";\ }\ if (typeof compose != "undefined") {\ var compAddOne = function(n) { return n + 1; },\ compAddTwo = function(n) { return n + 2; },\ compAddThree = function(n) { return n + 3; };\ \ var _composed = _.compose(compAddThree, compAddTwo, compAddOne),\ lodashComposed = lodash.compose(compAddThree, compAddTwo, compAddOne);\ }\ if (typeof countBy != "undefined" || typeof omit != "undefined") {\ var wordToNumber = {\ "one": 1,\ "two": 2,\ "three": 3,\ "four": 4,\ "five": 5,\ "six": 6,\ "seven": 7,\ "eight": 8,\ "nine": 9,\ "ten": 10,\ "eleven": 11,\ "twelve": 12,\ "thirteen": 13,\ "fourteen": 14,\ "fifteen": 15,\ "sixteen": 16,\ "seventeen": 17,\ "eighteen": 18,\ "nineteen": 19,\ "twenty": 20,\ "twenty-one": 21,\ "twenty-two": 22,\ "twenty-three": 23,\ "twenty-four": 24,\ "twenty-five": 25,\ "twenty-six": 26,\ "twenty-seven": 27,\ "twenty-eight": 28,\ "twenty-nine": 29,\ "thirty": 30,\ "thirty-one": 31,\ "thirty-two": 32,\ "thirty-three": 33,\ "thirty-four": 34,\ "thirty-five": 35,\ "thirty-six": 36,\ "thirty-seven": 37,\ "thirty-eight": 38,\ "thirty-nine": 39,\ "forty": 40\ };\ \ var words = belt.keys(wordToNumber).slice(0, limit);\ }\ if (typeof flatten != "undefined") {\ var _flattenDeep = _.flatten([[1]])[0] !== 1,\ lodashFlattenDeep = lodash.flatten([[1]]) !== 1;\ }\ if (typeof isEqual != "undefined") {\ var objectOfPrimitives = {\ "boolean": true,\ "number": 1,\ "string": "a"\ };\ \ var objectOfObjects = {\ "boolean": new Boolean(true),\ "number": new Number(1),\ "string": new String("a")\ };\ \ var objectOfObjects2 = {\ "boolean": new Boolean(true),\ "number": new Number(1),\ "string": new String("A")\ };\ \ var object2 = {},\ object3 = {},\ objects2 = Array(limit),\ objects3 = Array(limit),\ numbers2 = Array(limit),\ numbers3 = Array(limit),\ nestedNumbers2 = [1, [2], [3, [[4]]]],\ nestedNumbers3 = [1, [2], [3, [[6]]]];\ \ for (index = 0; index < limit; index++) {\ object2["key" + index] = index;\ object3["key" + index] = index;\ objects2[index] = { "num": index };\ objects3[index] = { "num": index };\ numbers2[index] = index;\ numbers3[index] = index;\ }\ object3["key" + (limit - 1)] = -1;\ objects3[limit - 1].num = -1;\ numbers3[limit - 1] = -1;\ }\ if (typeof matches != "undefined") {\ var source = { "num": 9 };\ \ var _findWhere = _.findWhere || _.find,\ _match = (_.matches || _.createCallback || _.noop)(source);\ \ var lodashFindWhere = lodash.findWhere || lodash.find,\ lodashMatch = (lodash.matches || lodash.createCallback || lodash.noop)(source);\ }\ if (typeof multiArrays != "undefined") {\ var twentyValues = belt.shuffle(belt.range(20)),\ fortyValues = belt.shuffle(belt.range(40)),\ hundredSortedValues = belt.range(100),\ hundredValues = belt.shuffle(hundredSortedValues),\ hundredValues2 = belt.shuffle(hundredValues),\ hundredTwentyValues = belt.shuffle(belt.range(120)),\ hundredTwentyValues2 = belt.shuffle(hundredTwentyValues),\ twoHundredValues = belt.shuffle(belt.range(200)),\ twoHundredValues2 = belt.shuffle(twoHundredValues);\ }\ if (typeof partial != "undefined") {\ var func = function(greeting, punctuation) {\ return greeting + " fred" + (punctuation || ".");\ };\ \ var _partial = _.partial(func, "hi"),\ lodashPartial = lodash.partial(func, "hi");\ }\ if (typeof template != "undefined") {\ var tplData = {\ "header1": "Header1",\ "header2": "Header2",\ "header3": "Header3",\ "header4": "Header4",\ "header5": "Header5",\ "header6": "Header6",\ "list": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]\ };\ \ var tpl =\ "<div>" +\ "<h1 class=\'header1\'><%= header1 %></h1>" +\ "<h2 class=\'header2\'><%= header2 %></h2>" +\ "<h3 class=\'header3\'><%= header3 %></h3>" +\ "<h4 class=\'header4\'><%= header4 %></h4>" +\ "<h5 class=\'header5\'><%= header5 %></h5>" +\ "<h6 class=\'header6\'><%= header6 %></h6>" +\ "<ul class=\'list\'>" +\ "<% for (var index = 0, length = list.length; index < length; index++) { %>" +\ "<li class=\'item\'><%= list[index] %></li>" +\ "<% } %>" +\ "</ul>" +\ "</div>";\ \ var tplVerbose =\ "<div>" +\ "<h1 class=\'header1\'><%= data.header1 %></h1>" +\ "<h2 class=\'header2\'><%= data.header2 %></h2>" +\ "<h3 class=\'header3\'><%= data.header3 %></h3>" +\ "<h4 class=\'header4\'><%= data.header4 %></h4>" +\ "<h5 class=\'header5\'><%= data.header5 %></h5>" +\ "<h6 class=\'header6\'><%= data.header6 %></h6>" +\ "<ul class=\'list\'>" +\ "<% for (var index = 0, length = data.list.length; index < length; index++) { %>" +\ "<li class=\'item\'><%= data.list[index] %></li>" +\ "<% } %>" +\ "</ul>" +\ "</div>";\ \ var settingsObject = { "variable": "data" };\ \ var _tpl = _.template(tpl),\ _tplVerbose = _.template(tplVerbose, null, settingsObject);\ \ var lodashTpl = lodash.template(tpl),\ lodashTplVerbose = lodash.template(tplVerbose, null, settingsObject);\ }\ if (typeof wrap != "undefined") {\ var add = function(a, b) {\ return a + b;\ };\ \ var average = function(func, a, b) {\ return (func(a, b) / 2).toFixed(2);\ };\ \ var _wrapped = _.wrap(add, average);\ lodashWrapped = lodash.wrap(add, average);\ }\ if (typeof zip != "undefined") {\ var unzipped = [["a", "b", "c"], [1, 2, 3], [true, false, true]];\ }' }); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_(...).map(...).filter(...).take(...).value()`') .add(buildName, { 'fn': 'lodashChaining.map(square).filter(even).take(100).value()', 'teardown': 'function chaining(){}' }) .add(otherName, { 'fn': '_chaining.map(square).filter(even).take(100).value()', 'teardown': 'function chaining(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.bind` (slow path)') .add(buildName, { 'fn': 'lodash.bind(function() { return this.name; }, { "name": "fred" })', 'teardown': 'function bind(){}' }) .add(otherName, { 'fn': '_.bind(function() { return this.name; }, { "name": "fred" })', 'teardown': 'function bind(){}' }) ); suites.push( Benchmark.Suite('bound call with arguments') .add(buildName, { 'fn': 'lodashBoundNormal("hi", "!")', 'teardown': 'function bind(){}' }) .add(otherName, { 'fn': '_boundNormal("hi", "!")', 'teardown': 'function bind(){}' }) ); suites.push( Benchmark.Suite('bound and partially applied call with arguments') .add(buildName, { 'fn': 'lodashBoundPartial("!")', 'teardown': 'function bind(){}' }) .add(otherName, { 'fn': '_boundPartial("!")', 'teardown': 'function bind(){}' }) ); suites.push( Benchmark.Suite('bound multiple times') .add(buildName, { 'fn': 'lodashBoundMultiple()', 'teardown': 'function bind(){}' }) .add(otherName, { 'fn': '_boundMultiple()', 'teardown': 'function bind(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.bindAll` iterating arguments') .add(buildName, { 'fn': 'lodash.bindAll.apply(lodash, [bindAllObjects[++bindAllCount]].concat(funcNames))', 'teardown': 'function bindAll(){}' }) .add(otherName, { 'fn': '_.bindAll.apply(_, [bindAllObjects[++bindAllCount]].concat(funcNames))', 'teardown': 'function bindAll(){}' }) ); suites.push( Benchmark.Suite('`_.bindAll` iterating the `object`') .add(buildName, { 'fn': 'lodash.bindAll(bindAllObjects[++bindAllCount])', 'teardown': 'function bindAll(){}' }) .add(otherName, { 'fn': '_.bindAll(bindAllObjects[++bindAllCount])', 'teardown': 'function bindAll(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.clone` with an array') .add(buildName, '\ lodash.clone(numbers)' ) .add(otherName, '\ _.clone(numbers)' ) ); suites.push( Benchmark.Suite('`_.clone` with an object') .add(buildName, '\ lodash.clone(object)' ) .add(otherName, '\ _.clone(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.compact`') .add(buildName, { 'fn': 'lodash.compact(uncompacted)', 'teardown': 'function compact(){}' }) .add(otherName, { 'fn': '_.compact(uncompacted)', 'teardown': 'function compact(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.compose`') .add(buildName, { 'fn': 'lodash.compose(compAddThree, compAddTwo, compAddOne)', 'teardown': 'function compose(){}' }) .add(otherName, { 'fn': '_.compose(compAddThree, compAddTwo, compAddOne)', 'teardown': 'function compose(){}' }) ); suites.push( Benchmark.Suite('composed call') .add(buildName, { 'fn': 'lodashComposed(0)', 'teardown': 'function compose(){}' }) .add(otherName, { 'fn': '_composed(0)', 'teardown': 'function compose(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.countBy` with `callback` iterating an array') .add(buildName, '\ lodash.countBy(numbers, function(num) { return num >> 1; })' ) .add(otherName, '\ _.countBy(numbers, function(num) { return num >> 1; })' ) ); suites.push( Benchmark.Suite('`_.countBy` with `property` name iterating an array') .add(buildName, { 'fn': 'lodash.countBy(words, "length")', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.countBy(words, "length")', 'teardown': 'function countBy(){}' }) ); suites.push( Benchmark.Suite('`_.countBy` with `callback` iterating an object') .add(buildName, { 'fn': 'lodash.countBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.countBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.defaults`') .add(buildName, '\ lodash.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' ) .add(otherName, '\ _.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.difference`') .add(buildName, '\ lodash.difference(numbers, twoNumbers, fourNumbers)' ) .add(otherName, '\ _.difference(numbers, twoNumbers, fourNumbers)' ) ); suites.push( Benchmark.Suite('`_.difference` iterating 200 elements') .add(buildName, { 'fn': 'lodash.difference(twoHundredValues, twoHundredValues2)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.difference(twoHundredValues, twoHundredValues2)', 'teardown': 'function multiArrays(){}' }) ); suites.push( Benchmark.Suite('`_.difference` iterating 20 and 40 elements') .add(buildName, { 'fn': 'lodash.difference(twentyValues, fortyValues)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.difference(twentyValues, fortyValues)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.each` iterating an array') .add(buildName, '\ var result = [];\ lodash.each(numbers, function(num) {\ result.push(num * 2);\ })' ) .add(otherName, '\ var result = [];\ _.each(numbers, function(num) {\ result.push(num * 2);\ })' ) ); suites.push( Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)') .add(buildName, '\ var result = [];\ lodash.each(numbers, function(num, index) {\ result.push(num + this["key" + index]);\ }, object)' ) .add(otherName, '\ var result = [];\ _.each(numbers, function(num, index) {\ result.push(num + this["key" + index]);\ }, object)' ) ); suites.push( Benchmark.Suite('`_.each` iterating an object') .add(buildName, '\ var result = [];\ lodash.each(object, function(num) {\ result.push(num * 2);\ })' ) .add(otherName, '\ var result = [];\ _.each(object, function(num) {\ result.push(num * 2);\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.every` iterating an array') .add(buildName, '\ lodash.every(numbers, function(num) {\ return num < limit;\ })' ) .add(otherName, '\ _.every(numbers, function(num) {\ return num < limit;\ })' ) ); suites.push( Benchmark.Suite('`_.every` iterating an object') .add(buildName, '\ lodash.every(object, function(num) {\ return num < limit;\ })' ) .add(otherName, '\ _.every(object, function(num) {\ return num < limit;\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.extend`') .add(buildName, '\ lodash.extend({}, object)' ) .add(otherName, '\ _.extend({}, object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.filter` iterating an array') .add(buildName, '\ lodash.filter(numbers, function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.filter(numbers, function(num) {\ return num % 2;\ })' ) ); suites.push( Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)') .add(buildName, '\ lodash.filter(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) .add(otherName, '\ _.filter(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) ); suites.push( Benchmark.Suite('`_.filter` iterating an object') .add(buildName, '\ lodash.filter(object, function(num) {\ return num % 2\ })' ) .add(otherName, '\ _.filter(object, function(num) {\ return num % 2\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.find` iterating an array') .add(buildName, '\ lodash.find(numbers, function(num) {\ return num === (limit - 1);\ })' ) .add(otherName, '\ _.find(numbers, function(num) {\ return num === (limit - 1);\ })' ) ); suites.push( Benchmark.Suite('`_.find` iterating an object') .add(buildName, '\ lodash.find(object, function(value, key) {\ return /\D9$/.test(key);\ })' ) .add(otherName, '\ _.find(object, function(value, key) {\ return /\D9$/.test(key);\ })' ) ); // Avoid Underscore induced `OutOfMemoryError` in Rhino, Narwhal, and Ringo. if (!isJava) { suites.push( Benchmark.Suite('`_.find` with `properties`') .add(buildName, { 'fn': 'lodashFindWhere(objects, source)', 'teardown': 'function matches(){}' }) .add(otherName, { 'fn': '_findWhere(objects, source)', 'teardown': 'function matches(){}' }) ); } /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.flatten`') .add(buildName, { 'fn': 'lodash.flatten(nestedNumbers, !lodashFlattenDeep)', 'teardown': 'function flatten(){}' }) .add(otherName, { 'fn': '_.flatten(nestedNumbers, !_flattenDeep)', 'teardown': 'function flatten(){}' }) ); suites.push( Benchmark.Suite('`_.flatten` nested arrays of numbers with `isDeep`') .add(buildName, { 'fn': 'lodash.flatten(nestedNumbers, lodashFlattenDeep)', 'teardown': 'function flatten(){}' }) .add(otherName, { 'fn': '_.flatten(nestedNumbers, _flattenDeep)', 'teardown': 'function flatten(){}' }) ); suites.push( Benchmark.Suite('`_.flatten` nest arrays of objects with `isDeep`') .add(buildName, { 'fn': 'lodash.flatten(nestedObjects, lodashFlattenDeep)', 'teardown': 'function flatten(){}' }) .add(otherName, { 'fn': '_.flatten(nestedObjects, _flattenDeep)', 'teardown': 'function flatten(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.functions`') .add(buildName, '\ lodash.functions(lodash)' ) .add(otherName, '\ _.functions(lodash)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.groupBy` with `callback` iterating an array') .add(buildName, '\ lodash.groupBy(numbers, function(num) { return num >> 1; })' ) .add(otherName, '\ _.groupBy(numbers, function(num) { return num >> 1; })' ) ); suites.push( Benchmark.Suite('`_.groupBy` with `property` name iterating an array') .add(buildName, { 'fn': 'lodash.groupBy(words, "length")', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.groupBy(words, "length")', 'teardown': 'function countBy(){}' }) ); suites.push( Benchmark.Suite('`_.groupBy` with `callback` iterating an object') .add(buildName, { 'fn': 'lodash.groupBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.groupBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.include` iterating an array') .add(buildName, '\ lodash.include(numbers, limit - 1)' ) .add(otherName, '\ _.include(numbers, limit - 1)' ) ); suites.push( Benchmark.Suite('`_.include` iterating an object') .add(buildName, '\ lodash.include(object, limit - 1)' ) .add(otherName, '\ _.include(object, limit - 1)' ) ); if (lodash.include('ab', 'ab') && _.include('ab', 'ab')) { suites.push( Benchmark.Suite('`_.include` iterating a string') .add(buildName, '\ lodash.include(strNumbers, "," + (limit - 1))' ) .add(otherName, '\ _.include(strNumbers, "," + (limit - 1))' ) ); } /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.indexBy` with `callback` iterating an array') .add(buildName, '\ lodash.indexBy(numbers, function(num) { return num >> 1; })' ) .add(otherName, '\ _.indexBy(numbers, function(num) { return num >> 1; })' ) ); suites.push( Benchmark.Suite('`_.indexBy` with `property` name iterating an array') .add(buildName, { 'fn': 'lodash.indexBy(words, "length")', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.indexBy(words, "length")', 'teardown': 'function countBy(){}' }) ); suites.push( Benchmark.Suite('`_.indexBy` with `callback` iterating an object') .add(buildName, { 'fn': 'lodash.indexBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.indexBy(wordToNumber, function(num) { return num >> 1; })', 'teardown': 'function countBy(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.indexOf`') .add(buildName, { 'fn': 'lodash.indexOf(hundredSortedValues, 99)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.indexOf(hundredSortedValues, 99)', 'teardown': 'function multiArrays(){}' }) ); suites.push( Benchmark.Suite('`_.indexOf` performing a binary search') .add(buildName, { 'fn': 'lodash.indexOf(hundredSortedValues, 99, true)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.indexOf(hundredSortedValues, 99, true)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.intersection`') .add(buildName, '\ lodash.intersection(numbers, twoNumbers, fourNumbers)' ) .add(otherName, '\ _.intersection(numbers, twoNumbers, fourNumbers)' ) ); suites.push( Benchmark.Suite('`_.intersection` iterating 120 elements') .add(buildName, { 'fn': 'lodash.intersection(hundredTwentyValues, hundredTwentyValues2)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.intersection(hundredTwentyValues, hundredTwentyValues2)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.invert`') .add(buildName, '\ lodash.invert(object)' ) .add(otherName, '\ _.invert(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.invoke` iterating an array') .add(buildName, '\ lodash.invoke(numbers, "toFixed")' ) .add(otherName, '\ _.invoke(numbers, "toFixed")' ) ); suites.push( Benchmark.Suite('`_.invoke` with arguments iterating an array') .add(buildName, '\ lodash.invoke(numbers, "toFixed", 1)' ) .add(otherName, '\ _.invoke(numbers, "toFixed", 1)' ) ); suites.push( Benchmark.Suite('`_.invoke` with a function for `methodName` iterating an array') .add(buildName, '\ lodash.invoke(numbers, Number.prototype.toFixed, 1)' ) .add(otherName, '\ _.invoke(numbers, Number.prototype.toFixed, 1)' ) ); suites.push( Benchmark.Suite('`_.invoke` iterating an object') .add(buildName, '\ lodash.invoke(object, "toFixed", 1)' ) .add(otherName, '\ _.invoke(object, "toFixed", 1)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.isEqual` comparing primitives') .add(buildName, { 'fn': '\ lodash.isEqual(1, "1");\ lodash.isEqual(1, 1)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(1, "1");\ _.isEqual(1, 1);', 'teardown': 'function isEqual(){}' }) ); suites.push( Benchmark.Suite('`_.isEqual` comparing primitives and their object counterparts (edge case)') .add(buildName, { 'fn': '\ lodash.isEqual(objectOfPrimitives, objectOfObjects);\ lodash.isEqual(objectOfPrimitives, objectOfObjects2)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(objectOfPrimitives, objectOfObjects);\ _.isEqual(objectOfPrimitives, objectOfObjects2)', 'teardown': 'function isEqual(){}' }) ); suites.push( Benchmark.Suite('`_.isEqual` comparing arrays') .add(buildName, { 'fn': '\ lodash.isEqual(numbers, numbers2);\ lodash.isEqual(numbers2, numbers3)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(numbers, numbers2);\ _.isEqual(numbers2, numbers3)', 'teardown': 'function isEqual(){}' }) ); suites.push( Benchmark.Suite('`_.isEqual` comparing nested arrays') .add(buildName, { 'fn': '\ lodash.isEqual(nestedNumbers, nestedNumbers2);\ lodash.isEqual(nestedNumbers2, nestedNumbers3)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(nestedNumbers, nestedNumbers2);\ _.isEqual(nestedNumbers2, nestedNumbers3)', 'teardown': 'function isEqual(){}' }) ); suites.push( Benchmark.Suite('`_.isEqual` comparing arrays of objects') .add(buildName, { 'fn': '\ lodash.isEqual(objects, objects2);\ lodash.isEqual(objects2, objects3)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(objects, objects2);\ _.isEqual(objects2, objects3)', 'teardown': 'function isEqual(){}' }) ); suites.push( Benchmark.Suite('`_.isEqual` comparing objects') .add(buildName, { 'fn': '\ lodash.isEqual(object, object2);\ lodash.isEqual(object2, object3)', 'teardown': 'function isEqual(){}' }) .add(otherName, { 'fn': '\ _.isEqual(object, object2);\ _.isEqual(object2, object3)', 'teardown': 'function isEqual(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.isArguments`, `_.isDate`, `_.isFunction`, `_.isNumber`, `_.isObject`, `_.isRegExp`') .add(buildName, '\ lodash.isArguments(arguments);\ lodash.isArguments(object);\ lodash.isDate(date);\ lodash.isDate(object);\ lodash.isFunction(lodash);\ lodash.isFunction(object);\ lodash.isNumber(1);\ lodash.isNumber(object);\ lodash.isObject(object);\ lodash.isObject(1);\ lodash.isRegExp(regexp);\ lodash.isRegExp(object)' ) .add(otherName, '\ _.isArguments(arguments);\ _.isArguments(object);\ _.isDate(date);\ _.isDate(object);\ _.isFunction(_);\ _.isFunction(object);\ _.isNumber(1);\ _.isNumber(object);\ _.isObject(object);\ _.isObject(1);\ _.isRegExp(regexp);\ _.isRegExp(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)') .add(buildName, '\ lodash.keys(object)' ) .add(otherName, '\ _.keys(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.lastIndexOf`') .add(buildName, { 'fn': 'lodash.lastIndexOf(hundredSortedValues, 0)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.lastIndexOf(hundredSortedValues, 0)', 'teardown': 'function multiArrays(){}' }) ); suites.push( Benchmark.Suite('`_.lastIndexOf` performing a binary search') .add(buildName, { 'fn': 'lodash.lastIndexOf(hundredSortedValues, 0, true)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.lastIndexOf(hundredSortedValues, 0, true)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.map` iterating an array') .add(buildName, '\ lodash.map(objects, function(value) {\ return value.num;\ })' ) .add(otherName, '\ _.map(objects, function(value) {\ return value.num;\ })' ) ); suites.push( Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)') .add(buildName, '\ lodash.map(objects, function(value, index) {\ return this["key" + index] + value.num;\ }, object)' ) .add(otherName, '\ _.map(objects, function(value, index) {\ return this["key" + index] + value.num;\ }, object)' ) ); suites.push( Benchmark.Suite('`_.map` iterating an object') .add(buildName, '\ lodash.map(object, function(value) {\ return value;\ })' ) .add(otherName, '\ _.map(object, function(value) {\ return value;\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.matches` predicate') .add(buildName, { 'fn': 'lodash.filter(objects, lodashMatch)', 'teardown': 'function matches(){}' }) .add(otherName, { 'fn': '_.filter(objects, _match)', 'teardown': 'function matches(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.max`') .add(buildName, '\ lodash.max(numbers)' ) .add(otherName, '\ _.max(numbers)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.min`') .add(buildName, '\ lodash.min(numbers)' ) .add(otherName, '\ _.min(numbers)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.omit` iterating 20 properties, omitting 2 keys') .add(buildName, '\ lodash.omit(object, "key6", "key13")' ) .add(otherName, '\ _.omit(object, "key6", "key13")' ) ); suites.push( Benchmark.Suite('`_.omit` iterating 40 properties, omitting 20 keys') .add(buildName, { 'fn': 'lodash.omit(wordToNumber, words)', 'teardown': 'function omit(){}' }) .add(otherName, { 'fn': '_.omit(wordToNumber, words)', 'teardown': 'function omit(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.pairs`') .add(buildName, '\ lodash.pairs(object)' ) .add(otherName, '\ _.pairs(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.partial` (slow path)') .add(buildName, { 'fn': 'lodash.partial(function(greeting) { return greeting + " " + this.name; }, "hi")', 'teardown': 'function partial(){}' }) .add(otherName, { 'fn': '_.partial(function(greeting) { return greeting + " " + this.name; }, "hi")', 'teardown': 'function partial(){}' }) ); suites.push( Benchmark.Suite('partially applied call with arguments') .add(buildName, { 'fn': 'lodashPartial("!")', 'teardown': 'function partial(){}' }) .add(otherName, { 'fn': '_partial("!")', 'teardown': 'function partial(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.partition` iterating an array') .add(buildName, '\ lodash.partition(numbers, function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.partition(numbers, function(num) {\ return num % 2;\ })' ) ); suites.push( Benchmark.Suite('`_.partition` iterating an array with `thisArg` (slow path)') .add(buildName, '\ lodash.partition(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) .add(otherName, '\ _.partition(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) ); suites.push( Benchmark.Suite('`_.partition` iterating an object') .add(buildName, '\ lodash.partition(object, function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.partition(object, function(num) {\ return num % 2;\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.pick`') .add(buildName, '\ lodash.pick(object, "key6", "key13")' ) .add(otherName, '\ _.pick(object, "key6", "key13")' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.pluck`') .add(buildName, '\ lodash.pluck(objects, "num")' ) .add(otherName, '\ _.pluck(objects, "num")' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.reduce` iterating an array') .add(buildName, '\ lodash.reduce(numbers, function(result, value, index) {\ result[index] = value;\ return result;\ }, {})' ) .add(otherName, '\ _.reduce(numbers, function(result, value, index) {\ result[index] = value;\ return result;\ }, {})' ) ); suites.push( Benchmark.Suite('`_.reduce` iterating an object') .add(buildName, '\ lodash.reduce(object, function(result, value, key) {\ result.push(key, value);\ return result;\ }, [])' ) .add(otherName, '\ _.reduce(object, function(result, value, key) {\ result.push(key, value);\ return result;\ }, [])' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.reduceRight` iterating an array') .add(buildName, '\ lodash.reduceRight(numbers, function(result, value, index) {\ result[index] = value;\ return result;\ }, {})' ) .add(otherName, '\ _.reduceRight(numbers, function(result, value, index) {\ result[index] = value;\ return result;\ }, {})' ) ); suites.push( Benchmark.Suite('`_.reduceRight` iterating an object') .add(buildName, '\ lodash.reduceRight(object, function(result, value, key) {\ result.push(key, value);\ return result;\ }, [])' ) .add(otherName, '\ _.reduceRight(object, function(result, value, key) {\ result.push(key, value);\ return result;\ }, [])' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.reject` iterating an array') .add(buildName, '\ lodash.reject(numbers, function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.reject(numbers, function(num) {\ return num % 2;\ })' ) ); suites.push( Benchmark.Suite('`_.reject` iterating an array with `thisArg` (slow path)') .add(buildName, '\ lodash.reject(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) .add(otherName, '\ _.reject(numbers, function(num, index) {\ return this["key" + index] % 2;\ }, object)' ) ); suites.push( Benchmark.Suite('`_.reject` iterating an object') .add(buildName, '\ lodash.reject(object, function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.reject(object, function(num) {\ return num % 2;\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.sample` with an `n`') .add(buildName, '\ lodash.sample(numbers, limit / 2)' ) .add(otherName, '\ _.sample(numbers, limit / 2)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.shuffle`') .add(buildName, '\ lodash.shuffle(numbers)' ) .add(otherName, '\ _.shuffle(numbers)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.size` with an object') .add(buildName, '\ lodash.size(object)' ) .add(otherName, '\ _.size(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.some` iterating an array') .add(buildName, '\ lodash.some(numbers, function(num) {\ return num == (limit - 1);\ })' ) .add(otherName, '\ _.some(numbers, function(num) {\ return num == (limit - 1);\ })' ) ); suites.push( Benchmark.Suite('`_.some` with `thisArg` iterating an array (slow path)') .add(buildName, '\ lodash.some(objects, function(value, index) {\ return this["key" + index] == (limit - 1);\ }, object)' ) .add(otherName, '\ _.some(objects, function(value, index) {\ return this["key" + index] == (limit - 1);\ }, object)' ) ); suites.push( Benchmark.Suite('`_.some` iterating an object') .add(buildName, '\ lodash.some(object, function(num) {\ return num == (limit - 1);\ })' ) .add(otherName, '\ _.some(object, function(num) {\ return num == (limit - 1);\ })' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.sortBy` with `callback`') .add(buildName, '\ lodash.sortBy(numbers, function(num) { return Math.sin(num); })' ) .add(otherName, '\ _.sortBy(numbers, function(num) { return Math.sin(num); })' ) ); suites.push( Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)') .add(buildName, '\ lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math)' ) .add(otherName, '\ _.sortBy(numbers, function(num) { return this.sin(num); }, Math)' ) ); suites.push( Benchmark.Suite('`_.sortBy` with `property` name') .add(buildName, { 'fn': 'lodash.sortBy(words, "length")', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '_.sortBy(words, "length")', 'teardown': 'function countBy(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.sortedIndex` with `callback`') .add(buildName, { 'fn': '\ lodash.sortedIndex(words, "twenty-five", function(value) {\ return wordToNumber[value];\ })', 'teardown': 'function countBy(){}' }) .add(otherName, { 'fn': '\ _.sortedIndex(words, "twenty-five", function(value) {\ return wordToNumber[value];\ })', 'teardown': 'function countBy(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.template` (slow path)') .add(buildName, { 'fn': 'lodash.template(tpl)(tplData)', 'teardown': 'function template(){}' }) .add(otherName, { 'fn': '_.template(tpl)(tplData)', 'teardown': 'function template(){}' }) ); suites.push( Benchmark.Suite('compiled template') .add(buildName, { 'fn': 'lodashTpl(tplData)', 'teardown': 'function template(){}' }) .add(otherName, { 'fn': '_tpl(tplData)', 'teardown': 'function template(){}' }) ); suites.push( Benchmark.Suite('compiled template without a with-statement') .add(buildName, { 'fn': 'lodashTplVerbose(tplData)', 'teardown': 'function template(){}' }) .add(otherName, { 'fn': '_tplVerbose(tplData)', 'teardown': 'function template(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.times`') .add(buildName, '\ var result = [];\ lodash.times(limit, function(n) { result.push(n); })' ) .add(otherName, '\ var result = [];\ _.times(limit, function(n) { result.push(n); })' ) ); suites.push( Benchmark.Suite('`_.times` with `thisArg` (slow path)') .add(buildName, '\ var result = [];\ lodash.times(limit, function(n) { result.push(this.sin(n)); }, Math)' ) .add(otherName, '\ var result = [];\ _.times(limit, function(n) { result.push(this.sin(n)); }, Math)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.toArray` with an array (edge case)') .add(buildName, '\ lodash.toArray(numbers)' ) .add(otherName, '\ _.toArray(numbers)' ) ); suites.push( Benchmark.Suite('`_.toArray` with an object') .add(buildName, '\ lodash.toArray(object)' ) .add(otherName, '\ _.toArray(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.unescape` string without html entities') .add(buildName, '\ lodash.unescape("`&`, `<`, `>`, `\\"`, and `\'`")' ) .add(otherName, '\ _.unescape("`&`, `<`, `>`, `\\"`, and `\'`")' ) ); suites.push( Benchmark.Suite('`_.unescape` string with html entities') .add(buildName, '\ lodash.unescape("`&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;`")' ) .add(otherName, '\ _.unescape("`&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;`")' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.union`') .add(buildName, '\ lodash.union(numbers, twoNumbers, fourNumbers)' ) .add(otherName, '\ _.union(numbers, twoNumbers, fourNumbers)' ) ); suites.push( Benchmark.Suite('`_.union` iterating an array of 200 elements') .add(buildName, { 'fn': 'lodash.union(hundredValues, hundredValues2)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.union(hundredValues, hundredValues2)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.uniq`') .add(buildName, '\ lodash.uniq(numbers.concat(twoNumbers, fourNumbers))' ) .add(otherName, '\ _.uniq(numbers.concat(twoNumbers, fourNumbers))' ) ); suites.push( Benchmark.Suite('`_.uniq` with `callback`') .add(buildName, '\ lodash.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\ return num % 2;\ })' ) .add(otherName, '\ _.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\ return num % 2;\ })' ) ); suites.push( Benchmark.Suite('`_.uniq` iterating an array of 200 elements') .add(buildName, { 'fn': 'lodash.uniq(twoHundredValues)', 'teardown': 'function multiArrays(){}' }) .add(otherName, { 'fn': '_.uniq(twoHundredValues)', 'teardown': 'function multiArrays(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.values`') .add(buildName, '\ lodash.values(object)' ) .add(otherName, '\ _.values(object)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.where`') .add(buildName, { 'fn': 'lodash.where(objects, source)', 'teardown': 'function matches(){}' }) .add(otherName, { 'fn': '_.where(objects, source)', 'teardown': 'function matches(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.without`') .add(buildName, '\ lodash.without(numbers, 9, 12, 14, 15)' ) .add(otherName, '\ _.without(numbers, 9, 12, 14, 15)' ) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.wrap` result called') .add(buildName, { 'fn': 'lodashWrapped(2, 5)', 'teardown': 'function wrap(){}' }) .add(otherName, { 'fn': '_wrapped(2, 5)', 'teardown': 'function wrap(){}' }) ); /*--------------------------------------------------------------------------*/ suites.push( Benchmark.Suite('`_.zip`') .add(buildName, { 'fn': 'lodash.zip.apply(lodash, unzipped)', 'teardown': 'function zip(){}' }) .add(otherName, { 'fn': '_.zip.apply(_, unzipped)', 'teardown': 'function zip(){}' }) ); /*--------------------------------------------------------------------------*/ if (Benchmark.platform + '') { log(Benchmark.platform); } // Expose `run` to be called later when executing in a browser. if (document) { root.run = run; } else { run(); } }.call(this));
Java
// // SLFSettingsViewController.h // Selfy // // Created by MadArkitekt on 4/30/14. // Copyright (c) 2014 Ed Salter. All rights reserved. // #import <UIKit/UIKit.h> @interface SLFSettingsViewController : UIViewController @end
Java
Intermediate PHP & MySQL ======================== ![PHP](images/php.png "PHP") ![MySQL](images/mysql.png "MySQL") ![Symfony](images/symfony.png "Symfony") > This course is designed for students with a fundamental understanding of programming. > We will spend some time reviewing PHP basics, for students who are familiar with another language. > We will then move on to commonly used linguistic constructs, talk about the web, learn Object Oriented principles, apply some of the most commonly used design patterns, learn about the MySQL database server and learn Symfony. > We will then spend the rest of the class working on a project, which will ultimately become a part of our portfolio. Week 1 - [PHP Basics](syllabus/01 PHP Basics.md) [:notebook_with_decorative_cover:](syllabus/homework/01_count_types.md) Week 2 - [Functions, Arrays & Strings](syllabus/02 Strings Functions Arrays.md) [:notebook_with_decorative_cover:](syllabus/homework/02_card_game.md) Week 3 - [Web Programming](syllabus/03 Web Programming.md) [:notebook_with_decorative_cover:](syllabus/homework/03_countries_on_earth.md) Week 4 - [Object Oriented Programming](syllabus/04 Object Oriented Programming.md) [:notebook_with_decorative_cover:](syllabus/homework/04_OO_card_game.md) Week 5 - [Design Patterns](syllabus/05 Design Patterns.md) [:notebook_with_decorative_cover:](syllabus/homework/05_simon_says.md) Week 6 - [MySQL Fundamentals](syllabus/06 MySQL Fundamentals.md) Week 7 - [Introduction to Symfony](syllabus/07 Introduction to Symfony.md) Week 8 - [ACAShop - Capstone Project Kickoff](syllabus/08 ACAShop Capstone Project Kickoff.md) Week 9 - In class coding and project completion Week 10 - Continue in class coding for ACAShop, Student Q&A, the state of PHP and the job market. #### Required Software Here are some applications you will need installed. - [VirtualBox](https://www.virtualbox.org/) - Create and run a virtual development environment - [Vagrant](https://www.vagrantup.com/) - Provision a virtual machine - [ansible](http://docs.ansible.com/intro_installation.html) - Configure the VM - [PHPStorm](https://www.jetbrains.com/phpstorm/download/) - State of the art PHP IDE (we will be providing everyone student licenses) - [git](http://git-scm.com/) - Version control system - [SourceTree](http://www.sourcetreeapp.com/) - Free git GUI client #### Developer Environment #### Virtual Machine We have created a seperate repository that contains instructions on how to setup and configure your VM. Clone [VirtualMachines](https://github.com/AustinCodingAcademy/VirtualMachines) and follow the instructions. *Note: We will host workshops, prior to class, to help students setup their machines.* #### Book [The Symfony Book](http://symfony.com/doc/current/book/index.html) - The Symfony bible, written and maintained by the core team #### Reference - [Helpful Links](Links.md) - [git Commands](GitCommands.md) *** `Instructor`: [Samir Patel](http://samirpatel.me) `Phone`: (512) 745-7846 `Email`: samir at austincodingacademy dot com `Office Hours`: 30 minutes after class
Java
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace Git.Storage.Common { public enum EEquipmentStatus { /// <summary> /// 闲置 /// </summary> [Description("闲置")] Unused = 1, /// <summary> /// 正在使用 /// </summary> [Description("正在使用")] IsUsing = 2, /// <summary> /// 报修 /// </summary> [Description("报修")] Repair = 3, /// <summary> /// 报损 /// </summary> [Description("报损")] Breakage = 4, /// <summary> /// 遗失 /// </summary> [Description("遗失")] Lost = 5, } }
Java
--[[ @title Motion Detect ]] a=6 -- columns to split picture into b=6 -- rows to split picture into c=1 -- measure mode (Y,U,V R,G,B) – U=0, Y=1, V=2, R=3, G=4, B=5 d=300000 -- timeout (mSec) e=200 -- comparison interval (msec) - less than 100 will slow down other CHDK functions f=5 -- threshold (difference in cell to trigger detection) g=1 -- draw grid (0=no, 1=yes) h=0 -- not used in LUA - in uBasic is the variable that gets loaded with the number of cells with motion detected i=0 -- region masking mode: 0=no regions, 1=include, 2=exclude j=0 -- first column k=0 -- first row l=0 -- last column m=0 -- last row n=0 -- optional parameters (1=shoot immediate) o=2 -- pixel step p=0 -- triggering delay (msec) zones = md_detect_motion( a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) if( zones > 0 ) then shoot() end
Java
body { background-image: url("http://www.army-technology.com/contractor_images/eimco/1-eimco-military-camps.jpg"); background-size: 800px } p { color: #000000 } img { top:100%; left:100%; } a:link { color: blue; } a:hover { text-decoration: none; color: red; }
Java
<?php /** * @Copyright Freestyle Joomla (C) 2010 * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * * This file is part of Freestyle Support Portal * 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, see <http://www.gnu.org/licenses/>. **/ ?> <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <?php echo FSS_Helper::PageStyle(); ?> <?php if (FSS_Helper::IsTests()) : ?> <?php echo FSS_Helper::PageTitle('COMMENT_MODERATION'); ?> <?php else: ?> <?php echo FSS_Helper::PageTitle('SUPPORT_ADMIN','COMMENT_MODERATION'); ?> <?php endif; ?> <?php //##NOT_TEST_START## ?> <?php include JPATH_SITE.DS.'components'.DS.'com_fss'.DS.'views'.DS.'admin'.DS.'snippet'.DS.'_tabbar.php'; //include "components/com_fss/views/admin/snippet/_tabbar.php" ?> <?php //##NOT_TEST_END## ?> <?php $this->comments->DisplayModerate(); ?> <?php include JPATH_SITE.DS.'components'.DS.'com_fss'.DS.'_powered.php'; ?> <?php echo FSS_Helper::PageStyleEnd(); ?>
Java
/* * Copyright (C) 2010 Xavier Claessens <xclaesse@gmail.com> * Copyright (C) 2010 Collabora Ltd. * * 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 2 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 St, Fifth Floor, * Boston, MA 02110-1301 USA */ #include "config.h" #include <stdlib.h> #include <gio/gio.h> #include <telepathy-glib/telepathy-glib.h> static GMainLoop *loop = NULL; static GList *channel_list = NULL; static void channel_invalidated_cb (TpChannel *channel, guint domain, gint code, gchar *message, gpointer user_data) { channel_list = g_list_remove (channel_list, channel); g_object_unref (channel); if (channel_list == NULL) g_main_loop_quit (loop); } static void session_complete (TpChannel *channel, const GError *error) { if (error != NULL) { g_debug ("Error for channel %p: %s", channel, error ? error->message : "No error message"); } tp_channel_close_async (channel, NULL, NULL); } static void splice_cb (GObject *source_object, GAsyncResult *res, gpointer channel) { GError *error = NULL; g_io_stream_splice_finish (res, &error); session_complete (channel, error); g_clear_error (&error); } static void accept_tube_cb (GObject *object, GAsyncResult *res, gpointer user_data) { TpChannel *channel = TP_CHANNEL (object); TpStreamTubeConnection *stc; GInetAddress *inet_address = NULL; GSocketAddress *socket_address = NULL; GSocket *socket = NULL; GSocketConnection *tube_connection = NULL; GSocketConnection *sshd_connection = NULL; GError *error = NULL; stc = tp_stream_tube_channel_accept_finish (TP_STREAM_TUBE_CHANNEL (channel), res, &error); if (stc == NULL) goto OUT; tube_connection = tp_stream_tube_connection_get_socket_connection (stc); /* Connect to the sshd */ inet_address = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4); socket_address = g_inet_socket_address_new (inet_address, 22); socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, &error); if (socket == NULL) goto OUT; if (!g_socket_connect (socket, socket_address, NULL, &error)) goto OUT; sshd_connection = g_socket_connection_factory_create_connection (socket); /* Splice tube and ssh connections */ g_io_stream_splice_async (G_IO_STREAM (tube_connection), G_IO_STREAM (sshd_connection), G_IO_STREAM_SPLICE_NONE, G_PRIORITY_DEFAULT, NULL, splice_cb, channel); OUT: if (error != NULL) session_complete (channel, error); tp_clear_object (&stc); tp_clear_object (&inet_address); tp_clear_object (&socket_address); tp_clear_object (&socket); tp_clear_object (&sshd_connection); g_clear_error (&error); } static void got_channel_cb (TpSimpleHandler *handler, TpAccount *account, TpConnection *connection, GList *channels, GList *requests_satisfied, gint64 user_action_time, TpHandleChannelsContext *context, gpointer user_data) { GList *l; for (l = channels; l != NULL; l = l->next) { if (TP_IS_STREAM_TUBE_CHANNEL (l->data)) { TpStreamTubeChannel *channel = l->data; channel_list = g_list_prepend (channel_list, g_object_ref (channel)); g_signal_connect (channel, "invalidated", G_CALLBACK (channel_invalidated_cb), NULL); tp_stream_tube_channel_accept_async (channel, accept_tube_cb, NULL); } } tp_handle_channels_context_accept (context); } int main (gint argc, gchar *argv[]) { TpDBusDaemon *dbus = NULL; TpSimpleClientFactory *factory = NULL; TpBaseClient *client = NULL; gboolean success = TRUE; GError *error = NULL; g_type_init (); tp_debug_set_flags (g_getenv ("SSH_CONTACT_DEBUG")); dbus = tp_dbus_daemon_dup (&error); if (dbus == NULL) goto OUT; factory = (TpSimpleClientFactory *) tp_automatic_client_factory_new (dbus); client = tp_simple_handler_new_with_factory (factory, FALSE, FALSE, "SSHContact", FALSE, got_channel_cb, NULL, NULL); tp_base_client_take_handler_filter (client, tp_asv_new ( TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_STREAM_TUBE, TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT, TP_PROP_CHANNEL_TYPE_STREAM_TUBE_SERVICE, G_TYPE_STRING, TUBE_SERVICE, TP_PROP_CHANNEL_REQUESTED, G_TYPE_BOOLEAN, FALSE, NULL)); if (!tp_base_client_register (client, &error)) goto OUT; loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (loop); OUT: if (error != NULL) { g_debug ("Error: %s", error->message); success = FALSE; } tp_clear_pointer (&loop, g_main_loop_unref); tp_clear_object (&dbus); tp_clear_object (&factory); tp_clear_object (&client); g_clear_error (&error); return success ? EXIT_SUCCESS : EXIT_FAILURE; }
Java
/* Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work of Simon Willison (see comments by Simon below). Small fixes by J.Dobrowolski for Front Accounting May 2008 Description: Uses css selectors to apply javascript behaviours to enable unobtrusive javascript in html documents. Usage: var myrules = { 'b.someclass' : function(element){ element.onclick = function(){ alert(this.innerHTML); } }, '#someid u' : function(element){ element.onmouseover = function(){ this.innerHTML = "BLAH!"; } } }; Behaviour.register(myrules); // Call Behaviour.apply() to re-apply the rules (if you // update the dom, etc). License: This file is entirely BSD licensed. More information: http://ripcord.co.nz/behaviour/ */ var Behaviour = { list : new Array, register : function(sheet){ Behaviour.list.push(sheet); }, start : function(){ Behaviour.addLoadEvent(function(){ Behaviour.apply(); }); }, apply : function(){ for (h=0;sheet=Behaviour.list[h];h++){ for (selector in sheet){ var sels = selector.split(','); for (var n = 0; n < sels.length; n++) { list = document.getElementsBySelector(sels[n]); if (!list){ continue; } for (i=0;element=list[i];i++){ sheet[selector](element); } } } } }, addLoadEvent : function(func){ var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } } Behaviour.start(); /* The following code is Copyright (C) Simon Willison 2004. document.getElementsBySelector(selector) - returns an array of element objects from the current document matching the CSS selector. Selectors can contain element names, class names and ids and can be nested. For example: elements = document.getElementsBySelect('div#main p a.external') Will return an array of all 'a' elements with 'external' in their class attribute that are contained inside 'p' elements that are contained inside the 'div' element which has id="main" New in version 0.4: Support for CSS2 and CSS3 attribute selectors: See http://www.w3.org/TR/css3-selectors/#attribute-selectors Version 0.4 - Simon Willison, March 25th 2003 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows -- Opera 7 fails */ function getAllChildren(e) { // Returns all children of element. Workaround required for IE5/Windows. Ugh. return e.all ? e.all : e.getElementsByTagName('*'); } document.getElementsBySelector = function(selector) { // Attempt to fail gracefully in lesser browsers if (!document.getElementsByTagName) { return new Array(); } // Split selector in to tokens var tokens = selector.split(' '); var currentContext = new Array(document); for (var i = 0; i < tokens.length; i++) { token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');; if (token.indexOf('#') > -1) { // Token is an ID selector var bits = token.split('#'); var tagName = bits[0]; var id = bits[1]; var element = document.getElementById(id); if (tagName && element.nodeName.toLowerCase() != tagName) { // tag with that ID not found, return false return new Array(); } // Set currentContext to contain just this element currentContext = new Array(element); continue; // Skip to next token } if (token.indexOf('.') > -1) { // Token contains a class selector var bits = token.split('.'); var tagName = bits[0]; var className = bits[1]; if (!tagName) { tagName = '*'; } // Get elements matching tag, filter them for class selector var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].getElementsByTagName(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) { currentContext[currentContextIndex++] = found[k]; } } continue; // Skip to next token } // Code to deal with attribute selectors /* Original reg expression /^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ was replaced by new RegExp() cuz compressor fault */ if (token.match(new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$'))) { var tagName = RegExp.$1; var attrName = RegExp.$2; var attrOperator = RegExp.$3; var attrValue = RegExp.$4; if (!tagName) { tagName = '*'; } // Grab all of the tagName elements within current context var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements; if (tagName == '*') { elements = getAllChildren(currentContext[h]); } else { elements = currentContext[h].getElementsByTagName(tagName); } for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = new Array; var currentContextIndex = 0; var checkFunction; // This function will be used to filter the elements switch (attrOperator) { case '=': // Equality checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); }; break; case '~': // Match one of space seperated words checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('\\b'+attrValue+'\\b'))); }; break; case '|': // Match start with value followed by optional hyphen checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('^'+attrValue+'-?'))); }; break; case '^': // Match starts with value checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) == 0); }; break; case '$': // Match ends with value - fails with "Warning" in Opera 7 checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); }; break; case '*': // Match contains value checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) > -1); }; break; default : // Just test for existence of attribute checkFunction = function(e) { return e.getAttribute(attrName); }; } currentContext = new Array; var currentContextIndex = 0; for (var k = 0; k < found.length; k++) { if (checkFunction(found[k])) { currentContext[currentContextIndex++] = found[k]; } } // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue); continue; // Skip to next token } if (!currentContext[0]){ return; } // If we get here, token is JUST an element (not a class or ID selector) tagName = token; var found = new Array; var foundCount = 0; for (var h = 0; h < currentContext.length; h++) { var elements = currentContext[h].getElementsByTagName(tagName); for (var j = 0; j < elements.length; j++) { found[foundCount++] = elements[j]; } } currentContext = found; } return currentContext; } /* That revolting regular expression explained /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ \---/ \---/\-------------/ \-------/ | | | | | | | The value | | ~,|,^,$,* or = | Attribute Tag */
Java
/***************************************************************************** * macroblock.c: macroblock encoding ***************************************************************************** * Copyright (C) 2003-2017 x264 project * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Loren Merritt <lorenm@u.washington.edu> * Fiona Glaser <fiona@x264.com> * Henrik Gramner <henrik@gramner.com> * * 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 2 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 02111, USA. * * This program is also available under a commercial proprietary license. * For more information, contact us at licensing@x264.com. *****************************************************************************/ #include "common/common.h" #include "macroblock.h" /* These chroma DC functions don't have assembly versions and are only used here. */ #define ZIG(i,y,x) level[i] = dct[x*2+y]; static inline void zigzag_scan_2x2_dc( dctcoef level[4], dctcoef dct[4] ) { ZIG(0,0,0) ZIG(1,0,1) ZIG(2,1,0) ZIG(3,1,1) } #undef ZIG static inline void zigzag_scan_2x4_dc( dctcoef level[8], dctcoef dct[8] ) { level[0] = dct[0]; level[1] = dct[2]; level[2] = dct[1]; level[3] = dct[4]; level[4] = dct[6]; level[5] = dct[3]; level[6] = dct[5]; level[7] = dct[7]; } #define IDCT_DEQUANT_2X2_START \ int d0 = dct[0] + dct[1]; \ int d1 = dct[2] + dct[3]; \ int d2 = dct[0] - dct[1]; \ int d3 = dct[2] - dct[3]; \ int dmf = dequant_mf[i_qp%6][0] << i_qp/6; static inline void idct_dequant_2x2_dc( dctcoef dct[4], dctcoef dct4x4[4][16], int dequant_mf[6][16], int i_qp ) { IDCT_DEQUANT_2X2_START dct4x4[0][0] = (d0 + d1) * dmf >> 5; dct4x4[1][0] = (d0 - d1) * dmf >> 5; dct4x4[2][0] = (d2 + d3) * dmf >> 5; dct4x4[3][0] = (d2 - d3) * dmf >> 5; } static inline void idct_dequant_2x2_dconly( dctcoef dct[4], int dequant_mf[6][16], int i_qp ) { IDCT_DEQUANT_2X2_START dct[0] = (d0 + d1) * dmf >> 5; dct[1] = (d0 - d1) * dmf >> 5; dct[2] = (d2 + d3) * dmf >> 5; dct[3] = (d2 - d3) * dmf >> 5; } #undef IDCT_2X2_DEQUANT_START static inline void dct2x2dc( dctcoef d[4], dctcoef dct4x4[4][16] ) { int d0 = dct4x4[0][0] + dct4x4[1][0]; int d1 = dct4x4[2][0] + dct4x4[3][0]; int d2 = dct4x4[0][0] - dct4x4[1][0]; int d3 = dct4x4[2][0] - dct4x4[3][0]; d[0] = d0 + d1; d[2] = d2 + d3; d[1] = d0 - d1; d[3] = d2 - d3; dct4x4[0][0] = 0; dct4x4[1][0] = 0; dct4x4[2][0] = 0; dct4x4[3][0] = 0; } static ALWAYS_INLINE int array_non_zero( dctcoef *v, int i_count ) { if( WORD_SIZE == 8 ) { for( int i = 0; i < i_count; i += 8/sizeof(dctcoef) ) if( M64( &v[i] ) ) return 1; } else { for( int i = 0; i < i_count; i += 4/sizeof(dctcoef) ) if( M32( &v[i] ) ) return 1; } return 0; } /* All encoding functions must output the correct CBP and NNZ values. * The entropy coding functions will check CBP first, then NNZ, before * actually reading the DCT coefficients. NNZ still must be correct even * if CBP is zero because of the use of NNZ values for context selection. * "NNZ" need only be 0 or 1 rather than the exact coefficient count because * that is only needed in CAVLC, and will be calculated by CAVLC's residual * coding and stored as necessary. */ /* This means that decimation can be done merely by adjusting the CBP and NNZ * rather than memsetting the coefficients. */ static void x264_mb_encode_i16x16( x264_t *h, int p, int i_qp ) { pixel *p_src = h->mb.pic.p_fenc[p]; pixel *p_dst = h->mb.pic.p_fdec[p]; ALIGNED_ARRAY_32( dctcoef, dct4x4,[16],[16] ); ALIGNED_ARRAY_32( dctcoef, dct_dc4x4,[16] ); int nz, block_cbp = 0; int decimate_score = h->mb.b_dct_decimate ? 0 : 9; int i_quant_cat = p ? CQM_4IC : CQM_4IY; int i_mode = h->mb.i_intra16x16_pred_mode; if( h->mb.b_lossless ) x264_predict_lossless_16x16( h, p, i_mode ); else h->predict_16x16[i_mode]( h->mb.pic.p_fdec[p] ); if( h->mb.b_lossless ) { for( int i = 0; i < 16; i++ ) { int oe = block_idx_xy_fenc[i]; int od = block_idx_xy_fdec[i]; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16*p+i], p_src+oe, p_dst+od, &dct_dc4x4[block_idx_yx_1d[i]] ); h->mb.cache.non_zero_count[x264_scan8[16*p+i]] = nz; block_cbp |= nz; } h->mb.i_cbp_luma |= block_cbp * 0xf; h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = array_non_zero( dct_dc4x4, 16 ); h->zigzagf.scan_4x4( h->dct.luma16x16_dc[p], dct_dc4x4 ); return; } CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct( dct4x4, p_src, p_dst ); if( h->mb.b_noise_reduction ) for( int idx = 0; idx < 16; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0], h->nr_offset[0], 16 ); for( int idx = 0; idx < 16; idx++ ) { dct_dc4x4[block_idx_xy_1d[idx]] = dct4x4[idx][0]; dct4x4[idx][0] = 0; } if( h->mb.b_trellis ) { for( int idx = 0; idx < 16; idx++ ) if( x264_quant_4x4_trellis( h, dct4x4[idx], i_quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_AC][p], 1, !!p, idx ) ) { block_cbp = 0xf; h->zigzagf.scan_4x4( h->dct.luma4x4[16*p+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[i_quant_cat], i_qp ); if( decimate_score < 6 ) decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[16*p+idx] ); h->mb.cache.non_zero_count[x264_scan8[16*p+idx]] = 1; } } else { for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[i_quant_cat][i_qp], h->quant4_bias[i_quant_cat][i_qp] ); if( nz ) { block_cbp = 0xf; FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[16*p+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[i_quant_cat], i_qp ); if( decimate_score < 6 ) decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[16*p+idx] ); h->mb.cache.non_zero_count[x264_scan8[16*p+idx]] = 1; } } } } /* Writing the 16 CBFs in an i16x16 block is quite costly, so decimation can save many bits. */ /* More useful with CAVLC, but still useful with CABAC. */ if( decimate_score < 6 ) { CLEAR_16x16_NNZ( p ); block_cbp = 0; } else h->mb.i_cbp_luma |= block_cbp; h->dctf.dct4x4dc( dct_dc4x4 ); if( h->mb.b_trellis ) nz = x264_quant_luma_dc_trellis( h, dct_dc4x4, i_quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_DC][p], 1, LUMA_DC+p ); else nz = h->quantf.quant_4x4_dc( dct_dc4x4, h->quant4_mf[i_quant_cat][i_qp][0]>>1, h->quant4_bias[i_quant_cat][i_qp][0]<<1 ); h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma16x16_dc[p], dct_dc4x4 ); /* output samples to fdec */ h->dctf.idct4x4dc( dct_dc4x4 ); h->quantf.dequant_4x4_dc( dct_dc4x4, h->dequant4_mf[i_quant_cat], i_qp ); /* XXX not inversed */ if( block_cbp ) for( int i = 0; i < 16; i++ ) dct4x4[i][0] = dct_dc4x4[block_idx_xy_1d[i]]; } /* put pixels to fdec */ if( block_cbp ) h->dctf.add16x16_idct( p_dst, dct4x4 ); else if( nz ) h->dctf.add16x16_idct_dc( p_dst, dct_dc4x4 ); } /* Round down coefficients losslessly in DC-only chroma blocks. * Unlike luma blocks, this can't be done with a lookup table or * other shortcut technique because of the interdependencies * between the coefficients due to the chroma DC transform. */ static ALWAYS_INLINE int x264_mb_optimize_chroma_dc( x264_t *h, dctcoef *dct_dc, int dequant_mf[6][16], int i_qp, int chroma422 ) { int dmf = dequant_mf[i_qp%6][0] << i_qp/6; /* If the QP is too high, there's no benefit to rounding optimization. */ if( dmf > 32*64 ) return 1; if( chroma422 ) return h->quantf.optimize_chroma_2x4_dc( dct_dc, dmf ); else return h->quantf.optimize_chroma_2x2_dc( dct_dc, dmf ); } static ALWAYS_INLINE void x264_mb_encode_chroma_internal( x264_t *h, int b_inter, int i_qp, int chroma422 ) { int nz, nz_dc; int b_decimate = b_inter && h->mb.b_dct_decimate; int (*dequant_mf)[16] = h->dequant4_mf[CQM_4IC + b_inter]; ALIGNED_ARRAY_16( dctcoef, dct_dc,[8] ); h->mb.i_cbp_chroma = 0; h->nr_count[2] += h->mb.b_noise_reduction * 4; M16( &h->mb.cache.non_zero_count[x264_scan8[16]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[18]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[32]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[34]] ) = 0; if( chroma422 ) { M16( &h->mb.cache.non_zero_count[x264_scan8[24]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[26]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[40]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[42]] ) = 0; } /* Early termination: check variance of chroma residual before encoding. * Don't bother trying early termination at low QPs. * Values are experimentally derived. */ if( b_decimate && i_qp >= (h->mb.b_trellis ? 12 : 18) && !h->mb.b_noise_reduction ) { int thresh = chroma422 ? (x264_lambda2_tab[i_qp] + 16) >> 5 : (x264_lambda2_tab[i_qp] + 32) >> 6; int ssd[2]; int chromapix = chroma422 ? PIXEL_8x16 : PIXEL_8x8; int score = h->pixf.var2[chromapix]( h->mb.pic.p_fenc[1], FENC_STRIDE, h->mb.pic.p_fdec[1], FDEC_STRIDE, &ssd[0] ); if( score < thresh*4 ) score += h->pixf.var2[chromapix]( h->mb.pic.p_fenc[2], FENC_STRIDE, h->mb.pic.p_fdec[2], FDEC_STRIDE, &ssd[1] ); if( score < thresh*4 ) { h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] = 0; h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] = 0; for( int ch = 0; ch < 2; ch++ ) { if( ssd[ch] > thresh ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; if( chroma422 ) /* Cannot be replaced by two calls to sub8x8_dct_dc since the hadamard transform is different */ h->dctf.sub8x16_dct_dc( dct_dc, p_src, p_dst ); else h->dctf.sub8x8_dct_dc( dct_dc, p_src, p_dst ); if( h->mb.b_trellis ) nz_dc = x264_quant_chroma_dc_trellis( h, dct_dc, i_qp+3*chroma422, !b_inter, CHROMA_DC+ch ); else { nz_dc = 0; for( int i = 0; i <= chroma422; i++ ) nz_dc |= h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4IC+b_inter][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4IC+b_inter][i_qp+3*chroma422][0] << 1 ); } if( nz_dc ) { if( !x264_mb_optimize_chroma_dc( h, dct_dc, dequant_mf, i_qp+3*chroma422, chroma422 ) ) continue; h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = 1; if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.idct_dequant_2x4_dconly( dct_dc, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); idct_dequant_2x2_dconly( dct_dc, dequant_mf, i_qp ); } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct_dc( p_dst + 8*i*FDEC_STRIDE, &dct_dc[4*i] ); h->mb.i_cbp_chroma = 1; } } } return; } } for( int ch = 0; ch < 2; ch++ ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; int i_decimate_score = b_decimate ? 0 : 7; int nz_ac = 0; ALIGNED_ARRAY_32( dctcoef, dct4x4,[8],[16] ); if( h->mb.b_lossless ) { static const uint8_t chroma422_scan[8] = { 0, 2, 1, 5, 3, 6, 4, 7 }; for( int i = 0; i < (chroma422?8:4); i++ ) { int oe = 4*(i&1) + 4*(i>>1)*FENC_STRIDE; int od = 4*(i&1) + 4*(i>>1)*FDEC_STRIDE; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16+i+(chroma422?i&4:0)+ch*16], p_src+oe, p_dst+od, &h->dct.chroma_dc[ch][chroma422?chroma422_scan[i]:i] ); h->mb.cache.non_zero_count[x264_scan8[16+i+(chroma422?i&4:0)+ch*16]] = nz; h->mb.i_cbp_chroma |= nz; } h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = array_non_zero( h->dct.chroma_dc[ch], chroma422?8:4 ); continue; } for( int i = 0; i <= chroma422; i++ ) h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); if( h->mb.b_noise_reduction ) for( int i = 0; i < (chroma422?8:4); i++ ) h->quantf.denoise_dct( dct4x4[i], h->nr_residual_sum[2], h->nr_offset[2], 16 ); if( chroma422 ) h->dctf.dct2x4dc( dct_dc, dct4x4 ); else dct2x2dc( dct_dc, dct4x4 ); /* calculate dct coeffs */ for( int i8x8 = 0; i8x8 < (chroma422?2:1); i8x8++ ) { if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { if( x264_quant_4x4_trellis( h, dct4x4[i8x8*4+i4x4], CQM_4IC+b_inter, i_qp, DCT_CHROMA_AC, !b_inter, 1, 0 ) ) { int idx = 16+ch*16+i8x8*8+i4x4; h->zigzagf.scan_4x4( h->dct.luma4x4[idx], dct4x4[i8x8*4+i4x4] ); h->quantf.dequant_4x4( dct4x4[i8x8*4+i4x4], dequant_mf, i_qp ); if( i_decimate_score < 7 ) i_decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[idx] ); h->mb.cache.non_zero_count[x264_scan8[idx]] = 1; nz_ac = 1; } } } else { nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[CQM_4IC+b_inter][i_qp], h->quant4_bias[CQM_4IC+b_inter][i_qp] ); nz_ac |= nz; FOREACH_BIT( i4x4, 0, nz ) { int idx = 16+ch*16+i8x8*8+i4x4; h->zigzagf.scan_4x4( h->dct.luma4x4[idx], dct4x4[i8x8*4+i4x4] ); h->quantf.dequant_4x4( dct4x4[i8x8*4+i4x4], dequant_mf, i_qp ); if( i_decimate_score < 7 ) i_decimate_score += h->quantf.decimate_score15( h->dct.luma4x4[idx] ); h->mb.cache.non_zero_count[x264_scan8[idx]] = 1; } } } if( h->mb.b_trellis ) nz_dc = x264_quant_chroma_dc_trellis( h, dct_dc, i_qp+3*chroma422, !b_inter, CHROMA_DC+ch ); else { nz_dc = 0; for( int i = 0; i <= chroma422; i++ ) nz_dc |= h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4IC+b_inter][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4IC+b_inter][i_qp+3*chroma422][0] << 1 ); } h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = nz_dc; if( i_decimate_score < 7 || !nz_ac ) { /* Decimate the block */ M16( &h->mb.cache.non_zero_count[x264_scan8[16+16*ch]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[18+16*ch]] ) = 0; if( chroma422 ) { M16( &h->mb.cache.non_zero_count[x264_scan8[24+16*ch]] ) = 0; M16( &h->mb.cache.non_zero_count[x264_scan8[26+16*ch]] ) = 0; } if( !nz_dc ) /* Whole block is empty */ continue; if( !x264_mb_optimize_chroma_dc( h, dct_dc, dequant_mf, i_qp+3*chroma422, chroma422 ) ) { h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+ch]] = 0; continue; } /* DC-only */ if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.idct_dequant_2x4_dconly( dct_dc, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); idct_dequant_2x2_dconly( dct_dc, dequant_mf, i_qp ); } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct_dc( p_dst + 8*i*FDEC_STRIDE, &dct_dc[4*i] ); } else { h->mb.i_cbp_chroma = 1; if( nz_dc ) { if( chroma422 ) { zigzag_scan_2x4_dc( h->dct.chroma_dc[ch], dct_dc ); h->quantf.idct_dequant_2x4_dc( dct_dc, dct4x4, dequant_mf, i_qp+3 ); } else { zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct_dc ); idct_dequant_2x2_dc( dct_dc, dct4x4, dequant_mf, i_qp ); } } for( int i = 0; i <= chroma422; i++ ) h->dctf.add8x8_idct( p_dst + 8*i*FDEC_STRIDE, &dct4x4[4*i] ); } } /* 0 = none, 1 = DC only, 2 = DC+AC */ h->mb.i_cbp_chroma += (h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] | h->mb.i_cbp_chroma); } void x264_mb_encode_chroma( x264_t *h, int b_inter, int i_qp ) { if( CHROMA_FORMAT == CHROMA_420 ) x264_mb_encode_chroma_internal( h, b_inter, i_qp, 0 ); else x264_mb_encode_chroma_internal( h, b_inter, i_qp, 1 ); } static void x264_macroblock_encode_skip( x264_t *h ) { M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 2]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 0]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 2]] ) = 0; if( CHROMA_FORMAT >= CHROMA_422 ) { M32( &h->mb.cache.non_zero_count[x264_scan8[16+ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[16+10]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+ 8]] ) = 0; M32( &h->mb.cache.non_zero_count[x264_scan8[32+10]] ) = 0; } h->mb.i_cbp_luma = 0; h->mb.i_cbp_chroma = 0; h->mb.cbp[h->mb.i_mb_xy] = 0; } /***************************************************************************** * Intra prediction for predictive lossless mode. *****************************************************************************/ void x264_predict_lossless_chroma( x264_t *h, int i_mode ) { int height = 16 >> CHROMA_V_SHIFT; if( i_mode == I_PRED_CHROMA_V ) { h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1]-FENC_STRIDE, FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2]-FENC_STRIDE, FENC_STRIDE, height ); memcpy( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[1]-FDEC_STRIDE, 8*sizeof(pixel) ); memcpy( h->mb.pic.p_fdec[2], h->mb.pic.p_fdec[2]-FDEC_STRIDE, 8*sizeof(pixel) ); } else if( i_mode == I_PRED_CHROMA_H ) { h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1]-1, FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2]-1, FENC_STRIDE, height ); x264_copy_column8( h->mb.pic.p_fdec[1]+4*FDEC_STRIDE, h->mb.pic.p_fdec[1]+4*FDEC_STRIDE-1 ); x264_copy_column8( h->mb.pic.p_fdec[2]+4*FDEC_STRIDE, h->mb.pic.p_fdec[2]+4*FDEC_STRIDE-1 ); if( CHROMA_FORMAT == CHROMA_422 ) { x264_copy_column8( h->mb.pic.p_fdec[1]+12*FDEC_STRIDE, h->mb.pic.p_fdec[1]+12*FDEC_STRIDE-1 ); x264_copy_column8( h->mb.pic.p_fdec[2]+12*FDEC_STRIDE, h->mb.pic.p_fdec[2]+12*FDEC_STRIDE-1 ); } } else { h->predict_chroma[i_mode]( h->mb.pic.p_fdec[1] ); h->predict_chroma[i_mode]( h->mb.pic.p_fdec[2] ); } } void x264_predict_lossless_4x4( x264_t *h, pixel *p_dst, int p, int idx, int i_mode ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; pixel *p_src = h->mb.pic.p_fenc_plane[p] + block_idx_x[idx]*4 + block_idx_y[idx]*4 * stride; if( i_mode == I_PRED_4x4_V ) h->mc.copy[PIXEL_4x4]( p_dst, FDEC_STRIDE, p_src-stride, stride, 4 ); else if( i_mode == I_PRED_4x4_H ) h->mc.copy[PIXEL_4x4]( p_dst, FDEC_STRIDE, p_src-1, stride, 4 ); else h->predict_4x4[i_mode]( p_dst ); } void x264_predict_lossless_8x8( x264_t *h, pixel *p_dst, int p, int idx, int i_mode, pixel edge[36] ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; pixel *p_src = h->mb.pic.p_fenc_plane[p] + (idx&1)*8 + (idx>>1)*8*stride; if( i_mode == I_PRED_8x8_V ) h->mc.copy[PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src-stride, stride, 8 ); else if( i_mode == I_PRED_8x8_H ) h->mc.copy[PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src-1, stride, 8 ); else h->predict_8x8[i_mode]( p_dst, edge ); } void x264_predict_lossless_16x16( x264_t *h, int p, int i_mode ) { int stride = h->fenc->i_stride[p] << MB_INTERLACED; if( i_mode == I_PRED_16x16_V ) h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc_plane[p]-stride, stride, 16 ); else if( i_mode == I_PRED_16x16_H ) h->mc.copy_16x16_unaligned( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc_plane[p]-1, stride, 16 ); else h->predict_16x16[i_mode]( h->mb.pic.p_fdec[p] ); } /***************************************************************************** * x264_macroblock_encode: *****************************************************************************/ static ALWAYS_INLINE void x264_macroblock_encode_internal( x264_t *h, int plane_count, int chroma ) { int i_qp = h->mb.i_qp; int b_decimate = h->mb.b_dct_decimate; int b_force_no_skip = 0; int nz; h->mb.i_cbp_luma = 0; for( int p = 0; p < plane_count; p++ ) h->mb.cache.non_zero_count[x264_scan8[LUMA_DC+p]] = 0; if( h->mb.i_type == I_PCM ) { /* if PCM is chosen, we need to store reconstructed frame data */ for( int p = 0; p < plane_count; p++ ) h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[p], FDEC_STRIDE, h->mb.pic.p_fenc[p], FENC_STRIDE, 16 ); if( chroma ) { int height = 16 >> CHROMA_V_SHIFT; h->mc.copy[PIXEL_8x8] ( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fenc[1], FENC_STRIDE, height ); h->mc.copy[PIXEL_8x8] ( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fenc[2], FENC_STRIDE, height ); } return; } if( !h->mb.b_allow_skip ) { b_force_no_skip = 1; if( IS_SKIP(h->mb.i_type) ) { if( h->mb.i_type == P_SKIP ) h->mb.i_type = P_L0; else if( h->mb.i_type == B_SKIP ) h->mb.i_type = B_DIRECT; } } if( h->mb.i_type == P_SKIP ) { /* don't do pskip motion compensation if it was already done in macroblock_analyse */ if( !h->mb.b_skip_mc ) { int mvx = x264_clip3( h->mb.cache.mv[0][x264_scan8[0]][0], h->mb.mv_min[0], h->mb.mv_max[0] ); int mvy = x264_clip3( h->mb.cache.mv[0][x264_scan8[0]][1], h->mb.mv_min[1], h->mb.mv_max[1] ); for( int p = 0; p < plane_count; p++ ) h->mc.mc_luma( h->mb.pic.p_fdec[p], FDEC_STRIDE, &h->mb.pic.p_fref[0][0][p*4], h->mb.pic.i_stride[p], mvx, mvy, 16, 16, &h->sh.weight[0][p] ); if( chroma ) { int v_shift = CHROMA_V_SHIFT; int height = 16 >> v_shift; /* Special case for mv0, which is (of course) very common in P-skip mode. */ if( mvx | mvy ) h->mc.mc_chroma( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], mvx, 2*mvy>>v_shift, 8, height ); else h->mc.load_deinterleave_chroma_fdec( h->mb.pic.p_fdec[1], h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], height ); if( h->sh.weight[0][1].weightfn ) h->sh.weight[0][1].weightfn[8>>2]( h->mb.pic.p_fdec[1], FDEC_STRIDE, h->mb.pic.p_fdec[1], FDEC_STRIDE, &h->sh.weight[0][1], height ); if( h->sh.weight[0][2].weightfn ) h->sh.weight[0][2].weightfn[8>>2]( h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fdec[2], FDEC_STRIDE, &h->sh.weight[0][2], height ); } } x264_macroblock_encode_skip( h ); return; } if( h->mb.i_type == B_SKIP ) { /* don't do bskip motion compensation if it was already done in macroblock_analyse */ if( !h->mb.b_skip_mc ) x264_mb_mc( h ); x264_macroblock_encode_skip( h ); return; } if( h->mb.i_type == I_16x16 ) { h->mb.b_transform_8x8 = 0; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) x264_mb_encode_i16x16( h, p, i_qp ); } else if( h->mb.i_type == I_8x8 ) { h->mb.b_transform_8x8 = 1; /* If we already encoded 3 of the 4 i8x8 blocks, we don't have to do them again. */ if( h->mb.i_skip_intra ) { h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[0], FDEC_STRIDE, h->mb.pic.i8x8_fdec_buf, 16, 16 ); M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = h->mb.pic.i8x8_nnz_buf[0]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = h->mb.pic.i8x8_nnz_buf[1]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = h->mb.pic.i8x8_nnz_buf[2]; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = h->mb.pic.i8x8_nnz_buf[3]; h->mb.i_cbp_luma = h->mb.pic.i8x8_cbp; /* In RD mode, restore the now-overwritten DCT data. */ if( h->mb.i_skip_intra == 2 ) h->mc.memcpy_aligned( h->dct.luma8x8, h->mb.pic.i8x8_dct_buf, sizeof(h->mb.pic.i8x8_dct_buf) ); } for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { for( int i = (p == 0 && h->mb.i_skip_intra) ? 3 : 0; i < 4; i++ ) { int i_mode = h->mb.cache.intra4x4_pred_mode[x264_scan8[4*i]]; x264_mb_encode_i8x8( h, p, i, i_qp, i_mode, NULL, 1 ); } } } else if( h->mb.i_type == I_4x4 ) { h->mb.b_transform_8x8 = 0; /* If we already encoded 15 of the 16 i4x4 blocks, we don't have to do them again. */ if( h->mb.i_skip_intra ) { h->mc.copy[PIXEL_16x16]( h->mb.pic.p_fdec[0], FDEC_STRIDE, h->mb.pic.i4x4_fdec_buf, 16, 16 ); M32( &h->mb.cache.non_zero_count[x264_scan8[ 0]] ) = h->mb.pic.i4x4_nnz_buf[0]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 2]] ) = h->mb.pic.i4x4_nnz_buf[1]; M32( &h->mb.cache.non_zero_count[x264_scan8[ 8]] ) = h->mb.pic.i4x4_nnz_buf[2]; M32( &h->mb.cache.non_zero_count[x264_scan8[10]] ) = h->mb.pic.i4x4_nnz_buf[3]; h->mb.i_cbp_luma = h->mb.pic.i4x4_cbp; /* In RD mode, restore the now-overwritten DCT data. */ if( h->mb.i_skip_intra == 2 ) h->mc.memcpy_aligned( h->dct.luma4x4, h->mb.pic.i4x4_dct_buf, sizeof(h->mb.pic.i4x4_dct_buf) ); } for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { for( int i = (p == 0 && h->mb.i_skip_intra) ? 15 : 0; i < 16; i++ ) { pixel *p_dst = &h->mb.pic.p_fdec[p][block_idx_xy_fdec[i]]; int i_mode = h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]; if( (h->mb.i_neighbour4[i] & (MB_TOPRIGHT|MB_TOP)) == MB_TOP ) /* emulate missing topright samples */ MPIXEL_X4( &p_dst[4-FDEC_STRIDE] ) = PIXEL_SPLAT_X4( p_dst[3-FDEC_STRIDE] ); x264_mb_encode_i4x4( h, p, i, i_qp, i_mode, 1 ); } } } else /* Inter MB */ { int i_decimate_mb = 0; /* Don't repeat motion compensation if it was already done in non-RD transform analysis */ if( !h->mb.b_skip_mc ) x264_mb_mc( h ); if( h->mb.b_lossless ) { if( h->mb.b_transform_8x8 ) for( int p = 0; p < plane_count; p++ ) for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { int x = i8x8&1; int y = i8x8>>1; nz = h->zigzagf.sub_8x8( h->dct.luma8x8[p*4+i8x8], h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE, h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE ); STORE_8x8_NNZ( p, i8x8, nz ); h->mb.i_cbp_luma |= nz << i8x8; } else for( int p = 0; p < plane_count; p++ ) for( int i4x4 = 0; i4x4 < 16; i4x4++ ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[p*16+i4x4], h->mb.pic.p_fenc[p]+block_idx_xy_fenc[i4x4], h->mb.pic.p_fdec[p]+block_idx_xy_fdec[i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4x4]] = nz; h->mb.i_cbp_luma |= nz << (i4x4>>2); } } else if( h->mb.b_transform_8x8 ) { ALIGNED_ARRAY_32( dctcoef, dct8x8,[4],[64] ); b_decimate &= !h->mb.b_trellis || !h->param.b_cabac; // 8x8 trellis is inherently optimal decimation for CABAC for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_8PC : CQM_8PY; CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct8( dct8x8, h->mb.pic.p_fenc[p], h->mb.pic.p_fdec[p] ); h->nr_count[1+!!p*2] += h->mb.b_noise_reduction * 4; int plane_cbp = 0; for( int idx = 0; idx < 4; idx++ ) { nz = x264_quant_8x8( h, dct8x8[idx], i_qp, ctx_cat_plane[DCT_LUMA_8x8][p], 0, p, idx ); if( nz ) { h->zigzagf.scan_8x8( h->dct.luma8x8[p*4+idx], dct8x8[idx] ); if( b_decimate ) { int i_decimate_8x8 = h->quantf.decimate_score64( h->dct.luma8x8[p*4+idx] ); i_decimate_mb += i_decimate_8x8; if( i_decimate_8x8 >= 4 ) plane_cbp |= 1<<idx; } else plane_cbp |= 1<<idx; } } if( i_decimate_mb >= 6 || !b_decimate ) { h->mb.i_cbp_luma |= plane_cbp; FOREACH_BIT( idx, 0, plane_cbp ) { h->quantf.dequant_8x8( dct8x8[idx], h->dequant8_mf[quant_cat], i_qp ); h->dctf.add8x8_idct8( &h->mb.pic.p_fdec[p][8*(idx&1) + 8*(idx>>1)*FDEC_STRIDE], dct8x8[idx] ); STORE_8x8_NNZ( p, idx, 1 ); } } } } else { ALIGNED_ARRAY_32( dctcoef, dct4x4,[16],[16] ); for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; CLEAR_16x16_NNZ( p ); h->dctf.sub16x16_dct( dct4x4, h->mb.pic.p_fenc[p], h->mb.pic.p_fdec[p] ); if( h->mb.b_noise_reduction ) { h->nr_count[0+!!p*2] += 16; for( int idx = 0; idx < 16; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); } int plane_cbp = 0; for( int i8x8 = 0; i8x8 < 4; i8x8++ ) { int i_decimate_8x8 = b_decimate ? 0 : 6; int nnz8x8 = 0; if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { int idx = i8x8*4+i4x4; if( x264_quant_4x4_trellis( h, dct4x4[idx], quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, !!p, p*16+idx ) ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 6 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+idx] ); h->mb.cache.non_zero_count[x264_scan8[p*16+idx]] = 1; nnz8x8 = 1; } } } else { nnz8x8 = nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); if( nz ) { FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+idx], dct4x4[idx] ); h->quantf.dequant_4x4( dct4x4[idx], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 6 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+idx] ); h->mb.cache.non_zero_count[x264_scan8[p*16+idx]] = 1; } } } if( nnz8x8 ) { i_decimate_mb += i_decimate_8x8; if( i_decimate_8x8 < 4 ) STORE_8x8_NNZ( p, i8x8, 0 ); else plane_cbp |= 1<<i8x8; } } if( i_decimate_mb < 6 ) { plane_cbp = 0; CLEAR_16x16_NNZ( p ); } else { h->mb.i_cbp_luma |= plane_cbp; FOREACH_BIT( i8x8, 0, plane_cbp ) { h->dctf.add8x8_idct( &h->mb.pic.p_fdec[p][(i8x8&1)*8 + (i8x8>>1)*8*FDEC_STRIDE], &dct4x4[i8x8*4] ); } } } } } /* encode chroma */ if( chroma ) { if( IS_INTRA( h->mb.i_type ) ) { int i_mode = h->mb.i_chroma_pred_mode; if( h->mb.b_lossless ) x264_predict_lossless_chroma( h, i_mode ); else { h->predict_chroma[i_mode]( h->mb.pic.p_fdec[1] ); h->predict_chroma[i_mode]( h->mb.pic.p_fdec[2] ); } } /* encode the 8x8 blocks */ x264_mb_encode_chroma( h, !IS_INTRA( h->mb.i_type ), h->mb.i_chroma_qp ); } else h->mb.i_cbp_chroma = 0; /* store cbp */ int cbp = h->mb.i_cbp_chroma << 4 | h->mb.i_cbp_luma; if( h->param.b_cabac ) cbp |= h->mb.cache.non_zero_count[x264_scan8[LUMA_DC ]] << 8 | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+0]] << 9 | h->mb.cache.non_zero_count[x264_scan8[CHROMA_DC+1]] << 10; h->mb.cbp[h->mb.i_mb_xy] = cbp; /* Check for P_SKIP * XXX: in the me perhaps we should take x264_mb_predict_mv_pskip into account * (if multiple mv give same result)*/ if( !b_force_no_skip ) { if( h->mb.i_type == P_L0 && h->mb.i_partition == D_16x16 && !(h->mb.i_cbp_luma | h->mb.i_cbp_chroma) && M32( h->mb.cache.mv[0][x264_scan8[0]] ) == M32( h->mb.cache.pskip_mv ) && h->mb.cache.ref[0][x264_scan8[0]] == 0 ) { h->mb.i_type = P_SKIP; } /* Check for B_SKIP */ if( h->mb.i_type == B_DIRECT && !(h->mb.i_cbp_luma | h->mb.i_cbp_chroma) ) { h->mb.i_type = B_SKIP; } } } void x264_macroblock_encode( x264_t *h ) { if( CHROMA444 ) x264_macroblock_encode_internal( h, 3, 0 ); else x264_macroblock_encode_internal( h, 1, 1 ); } /***************************************************************************** * x264_macroblock_probe_skip: * Check if the current MB could be encoded as a [PB]_SKIP *****************************************************************************/ static ALWAYS_INLINE int x264_macroblock_probe_skip_internal( x264_t *h, int b_bidir, int plane_count, int chroma ) { ALIGNED_ARRAY_32( dctcoef, dct4x4,[8],[16] ); ALIGNED_ARRAY_16( dctcoef, dctscan,[16] ); ALIGNED_4( int16_t mvp[2] ); int i_qp = h->mb.i_qp; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; if( !b_bidir ) { /* Get the MV */ mvp[0] = x264_clip3( h->mb.cache.pskip_mv[0], h->mb.mv_min[0], h->mb.mv_max[0] ); mvp[1] = x264_clip3( h->mb.cache.pskip_mv[1], h->mb.mv_min[1], h->mb.mv_max[1] ); /* Motion compensation */ h->mc.mc_luma( h->mb.pic.p_fdec[p], FDEC_STRIDE, &h->mb.pic.p_fref[0][0][p*4], h->mb.pic.i_stride[p], mvp[0], mvp[1], 16, 16, &h->sh.weight[0][p] ); } for( int i8x8 = 0, i_decimate_mb = 0; i8x8 < 4; i8x8++ ) { int fenc_offset = (i8x8&1) * 8 + (i8x8>>1) * FENC_STRIDE * 8; int fdec_offset = (i8x8&1) * 8 + (i8x8>>1) * FDEC_STRIDE * 8; h->dctf.sub8x8_dct( dct4x4, h->mb.pic.p_fenc[p] + fenc_offset, h->mb.pic.p_fdec[p] + fdec_offset ); if( h->mb.b_noise_reduction ) for( int i4x4 = 0; i4x4 < 4; i4x4++ ) h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); int nz = h->quantf.quant_4x4x4( dct4x4, h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); FOREACH_BIT( idx, 0, nz ) { h->zigzagf.scan_4x4( dctscan, dct4x4[idx] ); i_decimate_mb += h->quantf.decimate_score16( dctscan ); if( i_decimate_mb >= 6 ) return 0; } } } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { i_qp = h->mb.i_chroma_qp; int chroma422 = chroma == CHROMA_422; int thresh = chroma422 ? (x264_lambda2_tab[i_qp] + 16) >> 5 : (x264_lambda2_tab[i_qp] + 32) >> 6; int ssd; ALIGNED_ARRAY_16( dctcoef, dct_dc,[8] ); if( !b_bidir ) { /* Special case for mv0, which is (of course) very common in P-skip mode. */ if( M32( mvp ) ) h->mc.mc_chroma( h->mb.pic.p_fdec[1], h->mb.pic.p_fdec[2], FDEC_STRIDE, h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], mvp[0], mvp[1]<<chroma422, 8, chroma422?16:8 ); else h->mc.load_deinterleave_chroma_fdec( h->mb.pic.p_fdec[1], h->mb.pic.p_fref[0][0][4], h->mb.pic.i_stride[1], chroma422?16:8 ); } for( int ch = 0; ch < 2; ch++ ) { pixel *p_src = h->mb.pic.p_fenc[1+ch]; pixel *p_dst = h->mb.pic.p_fdec[1+ch]; if( !b_bidir && h->sh.weight[0][1+ch].weightfn ) h->sh.weight[0][1+ch].weightfn[8>>2]( h->mb.pic.p_fdec[1+ch], FDEC_STRIDE, h->mb.pic.p_fdec[1+ch], FDEC_STRIDE, &h->sh.weight[0][1+ch], chroma422?16:8 ); /* there is almost never a termination during chroma, but we can't avoid the check entirely */ /* so instead we check SSD and skip the actual check if the score is low enough. */ ssd = h->pixf.ssd[chroma422?PIXEL_8x16:PIXEL_8x8]( p_dst, FDEC_STRIDE, p_src, FENC_STRIDE ); if( ssd < thresh ) continue; /* The vast majority of chroma checks will terminate during the DC check or the higher * threshold check, so we can save time by doing a DC-only DCT. */ if( h->mb.b_noise_reduction ) { for( int i = 0; i <= chroma422; i++ ) h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); for( int i4x4 = 0; i4x4 < (chroma422?8:4); i4x4++ ) { h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[2], h->nr_offset[2], 16 ); dct_dc[i4x4] = dct4x4[i4x4][0]; dct4x4[i4x4][0] = 0; } } else { if( chroma422 ) h->dctf.sub8x16_dct_dc( dct_dc, p_src, p_dst ); else h->dctf.sub8x8_dct_dc( dct_dc, p_src, p_dst ); } for( int i = 0; i <= chroma422; i++ ) if( h->quantf.quant_2x2_dc( &dct_dc[4*i], h->quant4_mf[CQM_4PC][i_qp+3*chroma422][0] >> 1, h->quant4_bias[CQM_4PC][i_qp+3*chroma422][0] << 1 ) ) return 0; /* If there wasn't a termination in DC, we can check against a much higher threshold. */ if( ssd < thresh*4 ) continue; if( !h->mb.b_noise_reduction ) for( int i = 0; i <= chroma422; i++ ) { h->dctf.sub8x8_dct( &dct4x4[4*i], p_src + 8*i*FENC_STRIDE, p_dst + 8*i*FDEC_STRIDE ); dct4x4[i*4+0][0] = 0; dct4x4[i*4+1][0] = 0; dct4x4[i*4+2][0] = 0; dct4x4[i*4+3][0] = 0; } /* calculate dct coeffs */ for( int i8x8 = 0, i_decimate_mb = 0; i8x8 < (chroma422?2:1); i8x8++ ) { int nz = h->quantf.quant_4x4x4( &dct4x4[i8x8*4], h->quant4_mf[CQM_4PC][i_qp], h->quant4_bias[CQM_4PC][i_qp] ); FOREACH_BIT( idx, i8x8*4, nz ) { h->zigzagf.scan_4x4( dctscan, dct4x4[idx] ); i_decimate_mb += h->quantf.decimate_score15( dctscan ); if( i_decimate_mb >= 7 ) return 0; } } } } h->mb.b_skip_mc = 1; return 1; } int x264_macroblock_probe_skip( x264_t *h, int b_bidir ) { if( CHROMA_FORMAT == CHROMA_444 ) return x264_macroblock_probe_skip_internal( h, b_bidir, 3, CHROMA_444 ); else if( CHROMA_FORMAT == CHROMA_422 ) return x264_macroblock_probe_skip_internal( h, b_bidir, 1, CHROMA_422 ); else return x264_macroblock_probe_skip_internal( h, b_bidir, 1, CHROMA_420 ); } /**************************************************************************** * DCT-domain noise reduction / adaptive deadzone * from libavcodec ****************************************************************************/ void x264_noise_reduction_update( x264_t *h ) { h->nr_offset = h->nr_offset_denoise; h->nr_residual_sum = h->nr_residual_sum_buf[0]; h->nr_count = h->nr_count_buf[0]; for( int cat = 0; cat < 3 + CHROMA444; cat++ ) { int dct8x8 = cat&1; int size = dct8x8 ? 64 : 16; const uint32_t *weight = dct8x8 ? x264_dct8_weight2_tab : x264_dct4_weight2_tab; if( h->nr_count[cat] > (dct8x8 ? (1<<16) : (1<<18)) ) { for( int i = 0; i < size; i++ ) h->nr_residual_sum[cat][i] >>= 1; h->nr_count[cat] >>= 1; } for( int i = 0; i < size; i++ ) h->nr_offset[cat][i] = ((uint64_t)h->param.analyse.i_noise_reduction * h->nr_count[cat] + h->nr_residual_sum[cat][i]/2) / ((uint64_t)h->nr_residual_sum[cat][i] * weight[i]/256 + 1); /* Don't denoise DC coefficients */ h->nr_offset[cat][0] = 0; } } /***************************************************************************** * RD only; 4 calls to this do not make up for one macroblock_encode. * doesn't transform chroma dc. *****************************************************************************/ static ALWAYS_INLINE void x264_macroblock_encode_p8x8_internal( x264_t *h, int i8, int plane_count, int chroma ) { int b_decimate = h->mb.b_dct_decimate; int i_qp = h->mb.i_qp; int x = i8&1; int y = i8>>1; int nz; int chroma422 = chroma == CHROMA_422; h->mb.i_cbp_chroma = 0; h->mb.i_cbp_luma &= ~(1 << i8); if( !h->mb.b_skip_mc ) x264_mb_mc_8x8( h, i8 ); if( h->mb.b_lossless ) { for( int p = 0; p < plane_count; p++ ) { pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; int nnz8x8 = 0; if( h->mb.b_transform_8x8 ) { nnz8x8 = h->zigzagf.sub_8x8( h->dct.luma8x8[4*p+i8], p_fenc, p_fdec ); STORE_8x8_NNZ( p, i8, nnz8x8 ); } else { for( int i4 = i8*4; i4 < i8*4+4; i4++ ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[16*p+i4], h->mb.pic.p_fenc[p]+block_idx_xy_fenc[i4], h->mb.pic.p_fdec[p]+block_idx_xy_fdec[i4] ); h->mb.cache.non_zero_count[x264_scan8[16*p+i4]] = nz; nnz8x8 |= nz; } } h->mb.i_cbp_luma |= nnz8x8 << i8; } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { for( int ch = 0; ch < 2; ch++ ) { dctcoef dc; pixel *p_fenc = h->mb.pic.p_fenc[1+ch] + 4*x + (chroma422?8:4)*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[1+ch] + 4*x + (chroma422?8:4)*y*FDEC_STRIDE; for( int i4x4 = 0; i4x4 <= chroma422; i4x4++ ) { int offset = chroma422 ? 8*y + 2*i4x4 + x : i8; nz = h->zigzagf.sub_4x4ac( h->dct.luma4x4[16+offset+ch*16], p_fenc+4*i4x4*FENC_STRIDE, p_fdec+4*i4x4*FDEC_STRIDE, &dc ); h->mb.cache.non_zero_count[x264_scan8[16+offset+ch*16]] = nz; } } h->mb.i_cbp_chroma = 0x02; } } else { if( h->mb.b_transform_8x8 ) { for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_8PC : CQM_8PY; pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; ALIGNED_ARRAY_32( dctcoef, dct8x8,[64] ); h->dctf.sub8x8_dct8( dct8x8, p_fenc, p_fdec ); int nnz8x8 = x264_quant_8x8( h, dct8x8, i_qp, ctx_cat_plane[DCT_LUMA_8x8][p], 0, p, i8 ); if( nnz8x8 ) { h->zigzagf.scan_8x8( h->dct.luma8x8[4*p+i8], dct8x8 ); if( b_decimate && !h->mb.b_trellis ) nnz8x8 = 4 <= h->quantf.decimate_score64( h->dct.luma8x8[4*p+i8] ); if( nnz8x8 ) { h->quantf.dequant_8x8( dct8x8, h->dequant8_mf[quant_cat], i_qp ); h->dctf.add8x8_idct8( p_fdec, dct8x8 ); STORE_8x8_NNZ( p, i8, 1 ); h->mb.i_cbp_luma |= 1 << i8; } else STORE_8x8_NNZ( p, i8, 0 ); } else STORE_8x8_NNZ( p, i8, 0 ); } } else { for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; pixel *p_fenc = h->mb.pic.p_fenc[p] + 8*x + 8*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[p] + 8*x + 8*y*FDEC_STRIDE; int i_decimate_8x8 = b_decimate ? 0 : 4; ALIGNED_ARRAY_32( dctcoef, dct4x4,[4],[16] ); int nnz8x8 = 0; h->dctf.sub8x8_dct( dct4x4, p_fenc, p_fdec ); STORE_8x8_NNZ( p, i8, 0 ); if( h->mb.b_noise_reduction ) for( int idx = 0; idx < 4; idx++ ) h->quantf.denoise_dct( dct4x4[idx], h->nr_residual_sum[0+!!p*2], h->nr_offset[0+!!p*2], 16 ); if( h->mb.b_trellis ) { for( int i4x4 = 0; i4x4 < 4; i4x4++ ) { if( x264_quant_4x4_trellis( h, dct4x4[i4x4], quant_cat, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, !!p, i8*4+i4x4+p*16 ) ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i8*4+i4x4], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 4 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+i8*4+i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i8*4+i4x4]] = 1; nnz8x8 = 1; } } } else { nnz8x8 = nz = h->quantf.quant_4x4x4( dct4x4, h->quant4_mf[quant_cat][i_qp], h->quant4_bias[quant_cat][i_qp] ); if( nz ) { FOREACH_BIT( i4x4, 0, nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i8*4+i4x4], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[quant_cat], i_qp ); if( i_decimate_8x8 < 4 ) i_decimate_8x8 += h->quantf.decimate_score16( h->dct.luma4x4[p*16+i8*4+i4x4] ); h->mb.cache.non_zero_count[x264_scan8[p*16+i8*4+i4x4]] = 1; } } } if( nnz8x8 ) { /* decimate this 8x8 block */ if( i_decimate_8x8 < 4 ) STORE_8x8_NNZ( p, i8, 0 ); else { h->dctf.add8x8_idct( p_fdec, dct4x4 ); h->mb.i_cbp_luma |= 1 << i8; } } } } if( chroma == CHROMA_420 || chroma == CHROMA_422 ) { i_qp = h->mb.i_chroma_qp; for( int ch = 0; ch < 2; ch++ ) { ALIGNED_ARRAY_32( dctcoef, dct4x4,[2],[16] ); pixel *p_fenc = h->mb.pic.p_fenc[1+ch] + 4*x + (chroma422?8:4)*y*FENC_STRIDE; pixel *p_fdec = h->mb.pic.p_fdec[1+ch] + 4*x + (chroma422?8:4)*y*FDEC_STRIDE; for( int i4x4 = 0; i4x4 <= chroma422; i4x4++ ) { h->dctf.sub4x4_dct( dct4x4[i4x4], p_fenc + 4*i4x4*FENC_STRIDE, p_fdec + 4*i4x4*FDEC_STRIDE ); if( h->mb.b_noise_reduction ) h->quantf.denoise_dct( dct4x4[i4x4], h->nr_residual_sum[2], h->nr_offset[2], 16 ); dct4x4[i4x4][0] = 0; if( h->mb.b_trellis ) nz = x264_quant_4x4_trellis( h, dct4x4[i4x4], CQM_4PC, i_qp, DCT_CHROMA_AC, 0, 1, 0 ); else nz = h->quantf.quant_4x4( dct4x4[i4x4], h->quant4_mf[CQM_4PC][i_qp], h->quant4_bias[CQM_4PC][i_qp] ); int offset = chroma422 ? ((5*i8) & 0x09) + 2*i4x4 : i8; h->mb.cache.non_zero_count[x264_scan8[16+offset+ch*16]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[16+offset+ch*16], dct4x4[i4x4] ); h->quantf.dequant_4x4( dct4x4[i4x4], h->dequant4_mf[CQM_4PC], i_qp ); h->dctf.add4x4_idct( p_fdec + 4*i4x4*FDEC_STRIDE, dct4x4[i4x4] ); } } } h->mb.i_cbp_chroma = 0x02; } } } void x264_macroblock_encode_p8x8( x264_t *h, int i8 ) { if( CHROMA444 ) x264_macroblock_encode_p8x8_internal( h, i8, 3, CHROMA_444 ); else if( CHROMA_FORMAT == CHROMA_422 ) x264_macroblock_encode_p8x8_internal( h, i8, 1, CHROMA_422 ); else x264_macroblock_encode_p8x8_internal( h, i8, 1, CHROMA_420 ); } /***************************************************************************** * RD only, luma only (for 4:2:0) *****************************************************************************/ static ALWAYS_INLINE void x264_macroblock_encode_p4x4_internal( x264_t *h, int i4, int plane_count ) { int i_qp = h->mb.i_qp; for( int p = 0; p < plane_count; p++, i_qp = h->mb.i_chroma_qp ) { int quant_cat = p ? CQM_4PC : CQM_4PY; pixel *p_fenc = &h->mb.pic.p_fenc[p][block_idx_xy_fenc[i4]]; pixel *p_fdec = &h->mb.pic.p_fdec[p][block_idx_xy_fdec[i4]]; int nz; /* Don't need motion compensation as this function is only used in qpel-RD, which caches pixel data. */ if( h->mb.b_lossless ) { nz = h->zigzagf.sub_4x4( h->dct.luma4x4[p*16+i4], p_fenc, p_fdec ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4]] = nz; } else { ALIGNED_ARRAY_32( dctcoef, dct4x4,[16] ); h->dctf.sub4x4_dct( dct4x4, p_fenc, p_fdec ); nz = x264_quant_4x4( h, dct4x4, i_qp, ctx_cat_plane[DCT_LUMA_4x4][p], 0, p, i4 ); h->mb.cache.non_zero_count[x264_scan8[p*16+i4]] = nz; if( nz ) { h->zigzagf.scan_4x4( h->dct.luma4x4[p*16+i4], dct4x4 ); h->quantf.dequant_4x4( dct4x4, h->dequant4_mf[quant_cat], i_qp ); h->dctf.add4x4_idct( p_fdec, dct4x4 ); } } } } void x264_macroblock_encode_p4x4( x264_t *h, int i8 ) { if( CHROMA444 ) x264_macroblock_encode_p4x4_internal( h, i8, 3 ); else x264_macroblock_encode_p4x4_internal( h, i8, 1 ); }
Java
package oo.Prototype; /* * A Symbol Loader to register all prototype instance */ import java.util.*; public class SymbolLoader { private Hashtable symbols = new Hashtable(); public SymbolLoader() { symbols.put("Line", new LineSymbol()); symbols.put("Note", new NoteSymbol()); } public Hashtable getSymbols() { return symbols; } }
Java
/* This file is part of t8code. t8code is a C library to manage a collection (a forest) of multiple connected adaptive space-trees of general element classes in parallel. Copyright (C) 2015 the developers t8code 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 of the License, or (at your option) any later version. t8code 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 t8code; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file t8_cmesh_readmshfile.h * We define function here that serve to open a mesh file generated by * GMSH and consructing a cmesh from it. */ #ifndef T8_CMESH_READMSHFILE_H #define T8_CMESH_READMSHFILE_H #include <t8.h> #include <t8_eclass.h> #include <t8_cmesh.h> /* The maximum supported .msh file version. * Currently, we support gmsh's file version 2 in ASCII format. */ #define T8_CMESH_SUPPORTED_FILE_VERSION 2 /* put typedefs here */ T8_EXTERN_C_BEGIN (); /* put declarations here */ /** Read a .msh file and create a cmesh from it. * \param [in] fileprefix The prefix of the mesh file. * The file fileprefix.msh is read. * \param [in] partition If true the file is only opened on one process * specified by the \a master argument and saved as * a partitioned cmesh where each other process does not * have any trees. * \param [in] comm The MPI communicator with which the cmesh is to be committed. * \param [in] dim The dimension to read from the .msh files. The .msh format * can store several dimensions of the mesh and therefore the * dimension to read has to be set manually. * \param [in] master If partition is true, a valid MPI rank that will * read the file and store all the trees alone. * \return A committed cmesh holding the mesh of dimension \a dim in the * specified .msh file. */ t8_cmesh_t t8_cmesh_from_msh_file (const char *fileprefix, int partition, sc_MPI_Comm comm, int dim, int master); T8_EXTERN_C_END (); #endif /* !T8_CMESH_READMSHFILE_H */
Java
package com.djtu.signExam.util; import java.io.IOException; import com.djtu.signExam.model.support.EntityGenerator; /** * use this class to bootstrap the project. * There is no need for developers to write model classes themselves. * Once there are some updates or modified parts in the database, * Please run this class as JavaApplication to update Modal class files. * * @author lihe * */ public class Bootstrap { public static void main(String[] args){ EntityGenerator generator = new EntityGenerator(); try { generator.generateModel(); } catch (IOException e) { e.printStackTrace(); } } }
Java
/* MIPS-specific support for ELF Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. Most of the information added by Ian Lance Taylor, Cygnus Support, <ian@cygnus.com>. N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC. <mark@codesourcery.com> Traditional MIPS targets support added by Koundinya.K, Dansk Data Elektronik & Operations Research Group. <kk@ddeorg.soft.net> 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 2 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. */ /* This file handles functionality common to the different MIPS ABI's. */ #include "bfd.h" #include "sysdep.h" #include "libbfd.h" #include "libiberty.h" #include "elf-bfd.h" #include "elfxx-mips.h" #include "elf/mips.h" /* Get the ECOFF swapping routines. */ #include "coff/sym.h" #include "coff/symconst.h" #include "coff/ecoff.h" #include "coff/mips.h" #include "hashtab.h" /* This structure is used to hold .got entries while estimating got sizes. */ struct mips_got_entry { /* The input bfd in which the symbol is defined. */ bfd *abfd; /* The index of the symbol, as stored in the relocation r_info, if we have a local symbol; -1 otherwise. */ long symndx; union { /* If abfd == NULL, an address that must be stored in the got. */ bfd_vma address; /* If abfd != NULL && symndx != -1, the addend of the relocation that should be added to the symbol value. */ bfd_vma addend; /* If abfd != NULL && symndx == -1, the hash table entry corresponding to a global symbol in the got (or, local, if h->forced_local). */ struct mips_elf_link_hash_entry *h; } d; /* The TLS types included in this GOT entry (specifically, GD and IE). The GD and IE flags can be added as we encounter new relocations. LDM can also be set; it will always be alone, not combined with any GD or IE flags. An LDM GOT entry will be a local symbol entry with r_symndx == 0. */ unsigned char tls_type; /* The offset from the beginning of the .got section to the entry corresponding to this symbol+addend. If it's a global symbol whose offset is yet to be decided, it's going to be -1. */ long gotidx; }; /* This structure is used to hold .got information when linking. */ struct mips_got_info { /* The global symbol in the GOT with the lowest index in the dynamic symbol table. */ struct elf_link_hash_entry *global_gotsym; /* The number of global .got entries. */ unsigned int global_gotno; /* The number of .got slots used for TLS. */ unsigned int tls_gotno; /* The first unused TLS .got entry. Used only during mips_elf_initialize_tls_index. */ unsigned int tls_assigned_gotno; /* The number of local .got entries. */ unsigned int local_gotno; /* The number of local .got entries we have used. */ unsigned int assigned_gotno; /* A hash table holding members of the got. */ struct htab *got_entries; /* A hash table mapping input bfds to other mips_got_info. NULL unless multi-got was necessary. */ struct htab *bfd2got; /* In multi-got links, a pointer to the next got (err, rather, most of the time, it points to the previous got). */ struct mips_got_info *next; /* This is the GOT index of the TLS LDM entry for the GOT, MINUS_ONE for none, or MINUS_TWO for not yet assigned. This is needed because a single-GOT link may have multiple hash table entries for the LDM. It does not get initialized in multi-GOT mode. */ bfd_vma tls_ldm_offset; }; /* Map an input bfd to a got in a multi-got link. */ struct mips_elf_bfd2got_hash { bfd *bfd; struct mips_got_info *g; }; /* Structure passed when traversing the bfd2got hash table, used to create and merge bfd's gots. */ struct mips_elf_got_per_bfd_arg { /* A hashtable that maps bfds to gots. */ htab_t bfd2got; /* The output bfd. */ bfd *obfd; /* The link information. */ struct bfd_link_info *info; /* A pointer to the primary got, i.e., the one that's going to get the implicit relocations from DT_MIPS_LOCAL_GOTNO and DT_MIPS_GOTSYM. */ struct mips_got_info *primary; /* A non-primary got we're trying to merge with other input bfd's gots. */ struct mips_got_info *current; /* The maximum number of got entries that can be addressed with a 16-bit offset. */ unsigned int max_count; /* The number of local and global entries in the primary got. */ unsigned int primary_count; /* The number of local and global entries in the current got. */ unsigned int current_count; /* The total number of global entries which will live in the primary got and be automatically relocated. This includes those not referenced by the primary GOT but included in the "master" GOT. */ unsigned int global_count; }; /* Another structure used to pass arguments for got entries traversal. */ struct mips_elf_set_global_got_offset_arg { struct mips_got_info *g; int value; unsigned int needed_relocs; struct bfd_link_info *info; }; /* A structure used to count TLS relocations or GOT entries, for GOT entry or ELF symbol table traversal. */ struct mips_elf_count_tls_arg { struct bfd_link_info *info; unsigned int needed; }; struct _mips_elf_section_data { struct bfd_elf_section_data elf; union { struct mips_got_info *got_info; bfd_byte *tdata; } u; }; #define mips_elf_section_data(sec) \ ((struct _mips_elf_section_data *) elf_section_data (sec)) /* This structure is passed to mips_elf_sort_hash_table_f when sorting the dynamic symbols. */ struct mips_elf_hash_sort_data { /* The symbol in the global GOT with the lowest dynamic symbol table index. */ struct elf_link_hash_entry *low; /* The least dynamic symbol table index corresponding to a non-TLS symbol with a GOT entry. */ long min_got_dynindx; /* The greatest dynamic symbol table index corresponding to a symbol with a GOT entry that is not referenced (e.g., a dynamic symbol with dynamic relocations pointing to it from non-primary GOTs). */ long max_unref_got_dynindx; /* The greatest dynamic symbol table index not corresponding to a symbol without a GOT entry. */ long max_non_got_dynindx; }; /* The MIPS ELF linker needs additional information for each symbol in the global hash table. */ struct mips_elf_link_hash_entry { struct elf_link_hash_entry root; /* External symbol information. */ EXTR esym; /* Number of R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 relocs against this symbol. */ unsigned int possibly_dynamic_relocs; /* If the R_MIPS_32, R_MIPS_REL32, or R_MIPS_64 reloc is against a readonly section. */ bfd_boolean readonly_reloc; /* We must not create a stub for a symbol that has relocations related to taking the function's address, i.e. any but R_MIPS_CALL*16 ones -- see "MIPS ABI Supplement, 3rd Edition", p. 4-20. */ bfd_boolean no_fn_stub; /* If there is a stub that 32 bit functions should use to call this 16 bit function, this points to the section containing the stub. */ asection *fn_stub; /* Whether we need the fn_stub; this is set if this symbol appears in any relocs other than a 16 bit call. */ bfd_boolean need_fn_stub; /* If there is a stub that 16 bit functions should use to call this 32 bit function, this points to the section containing the stub. */ asection *call_stub; /* This is like the call_stub field, but it is used if the function being called returns a floating point value. */ asection *call_fp_stub; /* Are we forced local? This will only be set if we have converted the initial global GOT entry to a local GOT entry. */ bfd_boolean forced_local; #define GOT_NORMAL 0 #define GOT_TLS_GD 1 #define GOT_TLS_LDM 2 #define GOT_TLS_IE 4 #define GOT_TLS_OFFSET_DONE 0x40 #define GOT_TLS_DONE 0x80 unsigned char tls_type; /* This is only used in single-GOT mode; in multi-GOT mode there is one mips_got_entry per GOT entry, so the offset is stored there. In single-GOT mode there may be many mips_got_entry structures all referring to the same GOT slot. It might be possible to use root.got.offset instead, but that field is overloaded already. */ bfd_vma tls_got_offset; }; /* MIPS ELF linker hash table. */ struct mips_elf_link_hash_table { struct elf_link_hash_table root; #if 0 /* We no longer use this. */ /* String section indices for the dynamic section symbols. */ bfd_size_type dynsym_sec_strindex[SIZEOF_MIPS_DYNSYM_SECNAMES]; #endif /* The number of .rtproc entries. */ bfd_size_type procedure_count; /* The size of the .compact_rel section (if SGI_COMPAT). */ bfd_size_type compact_rel_size; /* This flag indicates that the value of DT_MIPS_RLD_MAP dynamic entry is set to the address of __rld_obj_head as in IRIX5. */ bfd_boolean use_rld_obj_head; /* This is the value of the __rld_map or __rld_obj_head symbol. */ bfd_vma rld_value; /* This is set if we see any mips16 stub sections. */ bfd_boolean mips16_stubs_seen; }; #define TLS_RELOC_P(r_type) \ (r_type == R_MIPS_TLS_DTPMOD32 \ || r_type == R_MIPS_TLS_DTPMOD64 \ || r_type == R_MIPS_TLS_DTPREL32 \ || r_type == R_MIPS_TLS_DTPREL64 \ || r_type == R_MIPS_TLS_GD \ || r_type == R_MIPS_TLS_LDM \ || r_type == R_MIPS_TLS_DTPREL_HI16 \ || r_type == R_MIPS_TLS_DTPREL_LO16 \ || r_type == R_MIPS_TLS_GOTTPREL \ || r_type == R_MIPS_TLS_TPREL32 \ || r_type == R_MIPS_TLS_TPREL64 \ || r_type == R_MIPS_TLS_TPREL_HI16 \ || r_type == R_MIPS_TLS_TPREL_LO16) /* Structure used to pass information to mips_elf_output_extsym. */ struct extsym_info { bfd *abfd; struct bfd_link_info *info; struct ecoff_debug_info *debug; const struct ecoff_debug_swap *swap; bfd_boolean failed; }; /* The names of the runtime procedure table symbols used on IRIX5. */ static const char * const mips_elf_dynsym_rtproc_names[] = { "_procedure_table", "_procedure_string_table", "_procedure_table_size", NULL }; /* These structures are used to generate the .compact_rel section on IRIX5. */ typedef struct { unsigned long id1; /* Always one? */ unsigned long num; /* Number of compact relocation entries. */ unsigned long id2; /* Always two? */ unsigned long offset; /* The file offset of the first relocation. */ unsigned long reserved0; /* Zero? */ unsigned long reserved1; /* Zero? */ } Elf32_compact_rel; typedef struct { bfd_byte id1[4]; bfd_byte num[4]; bfd_byte id2[4]; bfd_byte offset[4]; bfd_byte reserved0[4]; bfd_byte reserved1[4]; } Elf32_External_compact_rel; typedef struct { unsigned int ctype : 1; /* 1: long 0: short format. See below. */ unsigned int rtype : 4; /* Relocation types. See below. */ unsigned int dist2to : 8; unsigned int relvaddr : 19; /* (VADDR - vaddr of the previous entry)/ 4 */ unsigned long konst; /* KONST field. See below. */ unsigned long vaddr; /* VADDR to be relocated. */ } Elf32_crinfo; typedef struct { unsigned int ctype : 1; /* 1: long 0: short format. See below. */ unsigned int rtype : 4; /* Relocation types. See below. */ unsigned int dist2to : 8; unsigned int relvaddr : 19; /* (VADDR - vaddr of the previous entry)/ 4 */ unsigned long konst; /* KONST field. See below. */ } Elf32_crinfo2; typedef struct { bfd_byte info[4]; bfd_byte konst[4]; bfd_byte vaddr[4]; } Elf32_External_crinfo; typedef struct { bfd_byte info[4]; bfd_byte konst[4]; } Elf32_External_crinfo2; /* These are the constants used to swap the bitfields in a crinfo. */ #define CRINFO_CTYPE (0x1) #define CRINFO_CTYPE_SH (31) #define CRINFO_RTYPE (0xf) #define CRINFO_RTYPE_SH (27) #define CRINFO_DIST2TO (0xff) #define CRINFO_DIST2TO_SH (19) #define CRINFO_RELVADDR (0x7ffff) #define CRINFO_RELVADDR_SH (0) /* A compact relocation info has long (3 words) or short (2 words) formats. A short format doesn't have VADDR field and relvaddr fields contains ((VADDR - vaddr of the previous entry) >> 2). */ #define CRF_MIPS_LONG 1 #define CRF_MIPS_SHORT 0 /* There are 4 types of compact relocation at least. The value KONST has different meaning for each type: (type) (konst) CT_MIPS_REL32 Address in data CT_MIPS_WORD Address in word (XXX) CT_MIPS_GPHI_LO GP - vaddr CT_MIPS_JMPAD Address to jump */ #define CRT_MIPS_REL32 0xa #define CRT_MIPS_WORD 0xb #define CRT_MIPS_GPHI_LO 0xc #define CRT_MIPS_JMPAD 0xd #define mips_elf_set_cr_format(x,format) ((x).ctype = (format)) #define mips_elf_set_cr_type(x,type) ((x).rtype = (type)) #define mips_elf_set_cr_dist2to(x,v) ((x).dist2to = (v)) #define mips_elf_set_cr_relvaddr(x,d) ((x).relvaddr = (d)<<2) /* The structure of the runtime procedure descriptor created by the loader for use by the static exception system. */ typedef struct runtime_pdr { bfd_vma adr; /* Memory address of start of procedure. */ long regmask; /* Save register mask. */ long regoffset; /* Save register offset. */ long fregmask; /* Save floating point register mask. */ long fregoffset; /* Save floating point register offset. */ long frameoffset; /* Frame size. */ short framereg; /* Frame pointer register. */ short pcreg; /* Offset or reg of return pc. */ long irpss; /* Index into the runtime string table. */ long reserved; struct exception_info *exception_info;/* Pointer to exception array. */ } RPDR, *pRPDR; #define cbRPDR sizeof (RPDR) #define rpdNil ((pRPDR) 0) static struct mips_got_entry *mips_elf_create_local_got_entry (bfd *, bfd *, struct mips_got_info *, asection *, bfd_vma, unsigned long, struct mips_elf_link_hash_entry *, int); static bfd_boolean mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *, void *); static bfd_vma mips_elf_high (bfd_vma); static bfd_boolean mips_elf_stub_section_p (bfd *, asection *); static bfd_boolean mips_elf_create_dynamic_relocation (bfd *, struct bfd_link_info *, const Elf_Internal_Rela *, struct mips_elf_link_hash_entry *, asection *, bfd_vma, bfd_vma *, asection *); static hashval_t mips_elf_got_entry_hash (const void *); static bfd_vma mips_elf_adjust_gp (bfd *, struct mips_got_info *, bfd *); static struct mips_got_info *mips_elf_got_for_ibfd (struct mips_got_info *, bfd *); /* This will be used when we sort the dynamic relocation records. */ static bfd *reldyn_sorting_bfd; /* Nonzero if ABFD is using the N32 ABI. */ #define ABI_N32_P(abfd) \ ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI2) != 0) /* Nonzero if ABFD is using the N64 ABI. */ #define ABI_64_P(abfd) \ (get_elf_backend_data (abfd)->s->elfclass == ELFCLASS64) /* Nonzero if ABFD is using NewABI conventions. */ #define NEWABI_P(abfd) (ABI_N32_P (abfd) || ABI_64_P (abfd)) /* The IRIX compatibility level we are striving for. */ #define IRIX_COMPAT(abfd) \ (get_elf_backend_data (abfd)->elf_backend_mips_irix_compat (abfd)) /* Whether we are trying to be compatible with IRIX at all. */ #define SGI_COMPAT(abfd) \ (IRIX_COMPAT (abfd) != ict_none) /* The name of the options section. */ #define MIPS_ELF_OPTIONS_SECTION_NAME(abfd) \ (NEWABI_P (abfd) ? ".MIPS.options" : ".options") /* True if NAME is the recognized name of any SHT_MIPS_OPTIONS section. Some IRIX system files do not use MIPS_ELF_OPTIONS_SECTION_NAME. */ #define MIPS_ELF_OPTIONS_SECTION_NAME_P(NAME) \ (strcmp (NAME, ".MIPS.options") == 0 || strcmp (NAME, ".options") == 0) /* The name of the stub section. */ #define MIPS_ELF_STUB_SECTION_NAME(abfd) ".MIPS.stubs" /* The size of an external REL relocation. */ #define MIPS_ELF_REL_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_rel) /* The size of an external dynamic table entry. */ #define MIPS_ELF_DYN_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_dyn) /* The size of a GOT entry. */ #define MIPS_ELF_GOT_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->arch_size / 8) /* The size of a symbol-table entry. */ #define MIPS_ELF_SYM_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_sym) /* The default alignment for sections, as a power of two. */ #define MIPS_ELF_LOG_FILE_ALIGN(abfd) \ (get_elf_backend_data (abfd)->s->log_file_align) /* Get word-sized data. */ #define MIPS_ELF_GET_WORD(abfd, ptr) \ (ABI_64_P (abfd) ? bfd_get_64 (abfd, ptr) : bfd_get_32 (abfd, ptr)) /* Put out word-sized data. */ #define MIPS_ELF_PUT_WORD(abfd, val, ptr) \ (ABI_64_P (abfd) \ ? bfd_put_64 (abfd, val, ptr) \ : bfd_put_32 (abfd, val, ptr)) /* Add a dynamic symbol table-entry. */ #define MIPS_ELF_ADD_DYNAMIC_ENTRY(info, tag, val) \ _bfd_elf_add_dynamic_entry (info, tag, val) #define MIPS_ELF_RTYPE_TO_HOWTO(abfd, rtype, rela) \ (get_elf_backend_data (abfd)->elf_backend_mips_rtype_to_howto (rtype, rela)) /* Determine whether the internal relocation of index REL_IDX is REL (zero) or RELA (non-zero). The assumption is that, if there are two relocation sections for this section, one of them is REL and the other is RELA. If the index of the relocation we're testing is in range for the first relocation section, check that the external relocation size is that for RELA. It is also assumed that, if rel_idx is not in range for the first section, and this first section contains REL relocs, then the relocation is in the second section, that is RELA. */ #define MIPS_RELOC_RELA_P(abfd, sec, rel_idx) \ ((NUM_SHDR_ENTRIES (&elf_section_data (sec)->rel_hdr) \ * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel \ > (bfd_vma)(rel_idx)) \ == (elf_section_data (sec)->rel_hdr.sh_entsize \ == (ABI_64_P (abfd) ? sizeof (Elf64_External_Rela) \ : sizeof (Elf32_External_Rela)))) /* In case we're on a 32-bit machine, construct a 64-bit "-1" value from smaller values. Start with zero, widen, *then* decrement. */ #define MINUS_ONE (((bfd_vma)0) - 1) #define MINUS_TWO (((bfd_vma)0) - 2) /* The number of local .got entries we reserve. */ #define MIPS_RESERVED_GOTNO (2) /* The offset of $gp from the beginning of the .got section. */ #define ELF_MIPS_GP_OFFSET(abfd) (0x7ff0) /* The maximum size of the GOT for it to be addressable using 16-bit offsets from $gp. */ #define MIPS_ELF_GOT_MAX_SIZE(abfd) (ELF_MIPS_GP_OFFSET(abfd) + 0x7fff) /* Instructions which appear in a stub. */ #define STUB_LW(abfd) \ ((ABI_64_P (abfd) \ ? 0xdf998010 /* ld t9,0x8010(gp) */ \ : 0x8f998010)) /* lw t9,0x8010(gp) */ #define STUB_MOVE(abfd) \ ((ABI_64_P (abfd) \ ? 0x03e0782d /* daddu t7,ra */ \ : 0x03e07821)) /* addu t7,ra */ #define STUB_JALR 0x0320f809 /* jalr t9,ra */ #define STUB_LI16(abfd) \ ((ABI_64_P (abfd) \ ? 0x64180000 /* daddiu t8,zero,0 */ \ : 0x24180000)) /* addiu t8,zero,0 */ #define MIPS_FUNCTION_STUB_SIZE (16) /* The name of the dynamic interpreter. This is put in the .interp section. */ #define ELF_DYNAMIC_INTERPRETER(abfd) \ (ABI_N32_P (abfd) ? "/usr/lib32/libc.so.1" \ : ABI_64_P (abfd) ? "/usr/lib64/libc.so.1" \ : "/usr/lib/libc.so.1") #ifdef BFD64 #define MNAME(bfd,pre,pos) \ (ABI_64_P (bfd) ? CONCAT4 (pre,64,_,pos) : CONCAT4 (pre,32,_,pos)) #define ELF_R_SYM(bfd, i) \ (ABI_64_P (bfd) ? ELF64_R_SYM (i) : ELF32_R_SYM (i)) #define ELF_R_TYPE(bfd, i) \ (ABI_64_P (bfd) ? ELF64_MIPS_R_TYPE (i) : ELF32_R_TYPE (i)) #define ELF_R_INFO(bfd, s, t) \ (ABI_64_P (bfd) ? ELF64_R_INFO (s, t) : ELF32_R_INFO (s, t)) #else #define MNAME(bfd,pre,pos) CONCAT4 (pre,32,_,pos) #define ELF_R_SYM(bfd, i) \ (ELF32_R_SYM (i)) #define ELF_R_TYPE(bfd, i) \ (ELF32_R_TYPE (i)) #define ELF_R_INFO(bfd, s, t) \ (ELF32_R_INFO (s, t)) #endif /* The mips16 compiler uses a couple of special sections to handle floating point arguments. Section names that look like .mips16.fn.FNNAME contain stubs that copy floating point arguments from the fp regs to the gp regs and then jump to FNNAME. If any 32 bit function calls FNNAME, the call should be redirected to the stub instead. If no 32 bit function calls FNNAME, the stub should be discarded. We need to consider any reference to the function, not just a call, because if the address of the function is taken we will need the stub, since the address might be passed to a 32 bit function. Section names that look like .mips16.call.FNNAME contain stubs that copy floating point arguments from the gp regs to the fp regs and then jump to FNNAME. If FNNAME is a 32 bit function, then any 16 bit function that calls FNNAME should be redirected to the stub instead. If FNNAME is not a 32 bit function, the stub should be discarded. .mips16.call.fp.FNNAME sections are similar, but contain stubs which call FNNAME and then copy the return value from the fp regs to the gp regs. These stubs store the return value in $18 while calling FNNAME; any function which might call one of these stubs must arrange to save $18 around the call. (This case is not needed for 32 bit functions that call 16 bit functions, because 16 bit functions always return floating point values in both $f0/$f1 and $2/$3.) Note that in all cases FNNAME might be defined statically. Therefore, FNNAME is not used literally. Instead, the relocation information will indicate which symbol the section is for. We record any stubs that we find in the symbol table. */ #define FN_STUB ".mips16.fn." #define CALL_STUB ".mips16.call." #define CALL_FP_STUB ".mips16.call.fp." /* Look up an entry in a MIPS ELF linker hash table. */ #define mips_elf_link_hash_lookup(table, string, create, copy, follow) \ ((struct mips_elf_link_hash_entry *) \ elf_link_hash_lookup (&(table)->root, (string), (create), \ (copy), (follow))) /* Traverse a MIPS ELF linker hash table. */ #define mips_elf_link_hash_traverse(table, func, info) \ (elf_link_hash_traverse \ (&(table)->root, \ (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func), \ (info))) /* Get the MIPS ELF linker hash table from a link_info structure. */ #define mips_elf_hash_table(p) \ ((struct mips_elf_link_hash_table *) ((p)->hash)) /* Find the base offsets for thread-local storage in this object, for GD/LD and IE/LE respectively. */ #define TP_OFFSET 0x7000 #define DTP_OFFSET 0x8000 static bfd_vma dtprel_base (struct bfd_link_info *info) { /* If tls_sec is NULL, we should have signalled an error already. */ if (elf_hash_table (info)->tls_sec == NULL) return 0; return elf_hash_table (info)->tls_sec->vma + DTP_OFFSET; } static bfd_vma tprel_base (struct bfd_link_info *info) { /* If tls_sec is NULL, we should have signalled an error already. */ if (elf_hash_table (info)->tls_sec == NULL) return 0; return elf_hash_table (info)->tls_sec->vma + TP_OFFSET; } /* Create an entry in a MIPS ELF linker hash table. */ static struct bfd_hash_entry * mips_elf_link_hash_newfunc (struct bfd_hash_entry *entry, struct bfd_hash_table *table, const char *string) { struct mips_elf_link_hash_entry *ret = (struct mips_elf_link_hash_entry *) entry; /* Allocate the structure if it has not already been allocated by a subclass. */ if (ret == NULL) ret = bfd_hash_allocate (table, sizeof (struct mips_elf_link_hash_entry)); if (ret == NULL) return (struct bfd_hash_entry *) ret; /* Call the allocation method of the superclass. */ ret = ((struct mips_elf_link_hash_entry *) _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret, table, string)); if (ret != NULL) { /* Set local fields. */ memset (&ret->esym, 0, sizeof (EXTR)); /* We use -2 as a marker to indicate that the information has not been set. -1 means there is no associated ifd. */ ret->esym.ifd = -2; ret->possibly_dynamic_relocs = 0; ret->readonly_reloc = FALSE; ret->no_fn_stub = FALSE; ret->fn_stub = NULL; ret->need_fn_stub = FALSE; ret->call_stub = NULL; ret->call_fp_stub = NULL; ret->forced_local = FALSE; ret->tls_type = GOT_NORMAL; } return (struct bfd_hash_entry *) ret; } bfd_boolean _bfd_mips_elf_new_section_hook (bfd *abfd, asection *sec) { struct _mips_elf_section_data *sdata; bfd_size_type amt = sizeof (*sdata); sdata = bfd_zalloc (abfd, amt); if (sdata == NULL) return FALSE; sec->used_by_bfd = sdata; return _bfd_elf_new_section_hook (abfd, sec); } /* Read ECOFF debugging information from a .mdebug section into a ecoff_debug_info structure. */ bfd_boolean _bfd_mips_elf_read_ecoff_info (bfd *abfd, asection *section, struct ecoff_debug_info *debug) { HDRR *symhdr; const struct ecoff_debug_swap *swap; char *ext_hdr; swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap; memset (debug, 0, sizeof (*debug)); ext_hdr = bfd_malloc (swap->external_hdr_size); if (ext_hdr == NULL && swap->external_hdr_size != 0) goto error_return; if (! bfd_get_section_contents (abfd, section, ext_hdr, 0, swap->external_hdr_size)) goto error_return; symhdr = &debug->symbolic_header; (*swap->swap_hdr_in) (abfd, ext_hdr, symhdr); /* The symbolic header contains absolute file offsets and sizes to read. */ #define READ(ptr, offset, count, size, type) \ if (symhdr->count == 0) \ debug->ptr = NULL; \ else \ { \ bfd_size_type amt = (bfd_size_type) size * symhdr->count; \ debug->ptr = bfd_malloc (amt); \ if (debug->ptr == NULL) \ goto error_return; \ if (bfd_seek (abfd, symhdr->offset, SEEK_SET) != 0 \ || bfd_bread (debug->ptr, amt, abfd) != amt) \ goto error_return; \ } READ (line, cbLineOffset, cbLine, sizeof (unsigned char), unsigned char *); READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *); READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *); READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *); READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *); READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext), union aux_ext *); READ (ss, cbSsOffset, issMax, sizeof (char), char *); READ (ssext, cbSsExtOffset, issExtMax, sizeof (char), char *); READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *); READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *); READ (external_ext, cbExtOffset, iextMax, swap->external_ext_size, void *); #undef READ debug->fdr = NULL; return TRUE; error_return: if (ext_hdr != NULL) free (ext_hdr); if (debug->line != NULL) free (debug->line); if (debug->external_dnr != NULL) free (debug->external_dnr); if (debug->external_pdr != NULL) free (debug->external_pdr); if (debug->external_sym != NULL) free (debug->external_sym); if (debug->external_opt != NULL) free (debug->external_opt); if (debug->external_aux != NULL) free (debug->external_aux); if (debug->ss != NULL) free (debug->ss); if (debug->ssext != NULL) free (debug->ssext); if (debug->external_fdr != NULL) free (debug->external_fdr); if (debug->external_rfd != NULL) free (debug->external_rfd); if (debug->external_ext != NULL) free (debug->external_ext); return FALSE; } /* Swap RPDR (runtime procedure table entry) for output. */ static void ecoff_swap_rpdr_out (bfd *abfd, const RPDR *in, struct rpdr_ext *ex) { H_PUT_S32 (abfd, in->adr, ex->p_adr); H_PUT_32 (abfd, in->regmask, ex->p_regmask); H_PUT_32 (abfd, in->regoffset, ex->p_regoffset); H_PUT_32 (abfd, in->fregmask, ex->p_fregmask); H_PUT_32 (abfd, in->fregoffset, ex->p_fregoffset); H_PUT_32 (abfd, in->frameoffset, ex->p_frameoffset); H_PUT_16 (abfd, in->framereg, ex->p_framereg); H_PUT_16 (abfd, in->pcreg, ex->p_pcreg); H_PUT_32 (abfd, in->irpss, ex->p_irpss); } /* Create a runtime procedure table from the .mdebug section. */ static bfd_boolean mips_elf_create_procedure_table (void *handle, bfd *abfd, struct bfd_link_info *info, asection *s, struct ecoff_debug_info *debug) { const struct ecoff_debug_swap *swap; HDRR *hdr = &debug->symbolic_header; RPDR *rpdr, *rp; struct rpdr_ext *erp; void *rtproc; struct pdr_ext *epdr; struct sym_ext *esym; char *ss, **sv; char *str; bfd_size_type size; bfd_size_type count; unsigned long sindex; unsigned long i; PDR pdr; SYMR sym; const char *no_name_func = _("static procedure (no name)"); epdr = NULL; rpdr = NULL; esym = NULL; ss = NULL; sv = NULL; swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap; sindex = strlen (no_name_func) + 1; count = hdr->ipdMax; if (count > 0) { size = swap->external_pdr_size; epdr = bfd_malloc (size * count); if (epdr == NULL) goto error_return; if (! _bfd_ecoff_get_accumulated_pdr (handle, (bfd_byte *) epdr)) goto error_return; size = sizeof (RPDR); rp = rpdr = bfd_malloc (size * count); if (rpdr == NULL) goto error_return; size = sizeof (char *); sv = bfd_malloc (size * count); if (sv == NULL) goto error_return; count = hdr->isymMax; size = swap->external_sym_size; esym = bfd_malloc (size * count); if (esym == NULL) goto error_return; if (! _bfd_ecoff_get_accumulated_sym (handle, (bfd_byte *) esym)) goto error_return; count = hdr->issMax; ss = bfd_malloc (count); if (ss == NULL) goto error_return; if (! _bfd_ecoff_get_accumulated_ss (handle, (bfd_byte *) ss)) goto error_return; count = hdr->ipdMax; for (i = 0; i < (unsigned long) count; i++, rp++) { (*swap->swap_pdr_in) (abfd, epdr + i, &pdr); (*swap->swap_sym_in) (abfd, &esym[pdr.isym], &sym); rp->adr = sym.value; rp->regmask = pdr.regmask; rp->regoffset = pdr.regoffset; rp->fregmask = pdr.fregmask; rp->fregoffset = pdr.fregoffset; rp->frameoffset = pdr.frameoffset; rp->framereg = pdr.framereg; rp->pcreg = pdr.pcreg; rp->irpss = sindex; sv[i] = ss + sym.iss; sindex += strlen (sv[i]) + 1; } } size = sizeof (struct rpdr_ext) * (count + 2) + sindex; size = BFD_ALIGN (size, 16); rtproc = bfd_alloc (abfd, size); if (rtproc == NULL) { mips_elf_hash_table (info)->procedure_count = 0; goto error_return; } mips_elf_hash_table (info)->procedure_count = count + 2; erp = rtproc; memset (erp, 0, sizeof (struct rpdr_ext)); erp++; str = (char *) rtproc + sizeof (struct rpdr_ext) * (count + 2); strcpy (str, no_name_func); str += strlen (no_name_func) + 1; for (i = 0; i < count; i++) { ecoff_swap_rpdr_out (abfd, rpdr + i, erp + i); strcpy (str, sv[i]); str += strlen (sv[i]) + 1; } H_PUT_S32 (abfd, -1, (erp + count)->p_adr); /* Set the size and contents of .rtproc section. */ s->size = size; s->contents = rtproc; /* Skip this section later on (I don't think this currently matters, but someday it might). */ s->map_head.link_order = NULL; if (epdr != NULL) free (epdr); if (rpdr != NULL) free (rpdr); if (esym != NULL) free (esym); if (ss != NULL) free (ss); if (sv != NULL) free (sv); return TRUE; error_return: if (epdr != NULL) free (epdr); if (rpdr != NULL) free (rpdr); if (esym != NULL) free (esym); if (ss != NULL) free (ss); if (sv != NULL) free (sv); return FALSE; } /* Check the mips16 stubs for a particular symbol, and see if we can discard them. */ static bfd_boolean mips_elf_check_mips16_stubs (struct mips_elf_link_hash_entry *h, void *data ATTRIBUTE_UNUSED) { if (h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; if (h->fn_stub != NULL && ! h->need_fn_stub) { /* We don't need the fn_stub; the only references to this symbol are 16 bit calls. Clobber the size to 0 to prevent it from being included in the link. */ h->fn_stub->size = 0; h->fn_stub->flags &= ~SEC_RELOC; h->fn_stub->reloc_count = 0; h->fn_stub->flags |= SEC_EXCLUDE; } if (h->call_stub != NULL && h->root.other == STO_MIPS16) { /* We don't need the call_stub; this is a 16 bit function, so calls from other 16 bit functions are OK. Clobber the size to 0 to prevent it from being included in the link. */ h->call_stub->size = 0; h->call_stub->flags &= ~SEC_RELOC; h->call_stub->reloc_count = 0; h->call_stub->flags |= SEC_EXCLUDE; } if (h->call_fp_stub != NULL && h->root.other == STO_MIPS16) { /* We don't need the call_stub; this is a 16 bit function, so calls from other 16 bit functions are OK. Clobber the size to 0 to prevent it from being included in the link. */ h->call_fp_stub->size = 0; h->call_fp_stub->flags &= ~SEC_RELOC; h->call_fp_stub->reloc_count = 0; h->call_fp_stub->flags |= SEC_EXCLUDE; } return TRUE; } /* R_MIPS16_26 is used for the mips16 jal and jalx instructions. Most mips16 instructions are 16 bits, but these instructions are 32 bits. The format of these instructions is: +--------------+--------------------------------+ | JALX | X| Imm 20:16 | Imm 25:21 | +--------------+--------------------------------+ | Immediate 15:0 | +-----------------------------------------------+ JALX is the 5-bit value 00011. X is 0 for jal, 1 for jalx. Note that the immediate value in the first word is swapped. When producing a relocatable object file, R_MIPS16_26 is handled mostly like R_MIPS_26. In particular, the addend is stored as a straight 26-bit value in a 32-bit instruction. (gas makes life simpler for itself by never adjusting a R_MIPS16_26 reloc to be against a section, so the addend is always zero). However, the 32 bit instruction is stored as 2 16-bit values, rather than a single 32-bit value. In a big-endian file, the result is the same; in a little-endian file, the two 16-bit halves of the 32 bit value are swapped. This is so that a disassembler can recognize the jal instruction. When doing a final link, R_MIPS16_26 is treated as a 32 bit instruction stored as two 16-bit values. The addend A is the contents of the targ26 field. The calculation is the same as R_MIPS_26. When storing the calculated value, reorder the immediate value as shown above, and don't forget to store the value as two 16-bit values. To put it in MIPS ABI terms, the relocation field is T-targ26-16, defined as big-endian: +--------+----------------------+ | | | | | targ26-16 | |31 26|25 0| +--------+----------------------+ little-endian: +----------+------+-------------+ | | | | | sub1 | | sub2 | |0 9|10 15|16 31| +----------+--------------------+ where targ26-16 is sub1 followed by sub2 (i.e., the addend field A is ((sub1 << 16) | sub2)). When producing a relocatable object file, the calculation is (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2) When producing a fully linked file, the calculation is let R = (((A < 2) | ((P + 4) & 0xf0000000) + S) >> 2) ((R & 0x1f0000) << 5) | ((R & 0x3e00000) >> 5) | (R & 0xffff) R_MIPS16_GPREL is used for GP-relative addressing in mips16 mode. A typical instruction will have a format like this: +--------------+--------------------------------+ | EXTEND | Imm 10:5 | Imm 15:11 | +--------------+--------------------------------+ | Major | rx | ry | Imm 4:0 | +--------------+--------------------------------+ EXTEND is the five bit value 11110. Major is the instruction opcode. This is handled exactly like R_MIPS_GPREL16, except that the addend is retrieved and stored as shown in this diagram; that is, the Imm fields above replace the V-rel16 field. All we need to do here is shuffle the bits appropriately. As above, the two 16-bit halves must be swapped on a little-endian system. R_MIPS16_HI16 and R_MIPS16_LO16 are used in mips16 mode to access data when neither GP-relative nor PC-relative addressing can be used. They are handled like R_MIPS_HI16 and R_MIPS_LO16, except that the addend is retrieved and stored as shown above for R_MIPS16_GPREL. */ void _bfd_mips16_elf_reloc_unshuffle (bfd *abfd, int r_type, bfd_boolean jal_shuffle, bfd_byte *data) { bfd_vma extend, insn, val; if (r_type != R_MIPS16_26 && r_type != R_MIPS16_GPREL && r_type != R_MIPS16_HI16 && r_type != R_MIPS16_LO16) return; /* Pick up the mips16 extend instruction and the real instruction. */ extend = bfd_get_16 (abfd, data); insn = bfd_get_16 (abfd, data + 2); if (r_type == R_MIPS16_26) { if (jal_shuffle) val = ((extend & 0xfc00) << 16) | ((extend & 0x3e0) << 11) | ((extend & 0x1f) << 21) | insn; else val = extend << 16 | insn; } else val = ((extend & 0xf800) << 16) | ((insn & 0xffe0) << 11) | ((extend & 0x1f) << 11) | (extend & 0x7e0) | (insn & 0x1f); bfd_put_32 (abfd, val, data); } void _bfd_mips16_elf_reloc_shuffle (bfd *abfd, int r_type, bfd_boolean jal_shuffle, bfd_byte *data) { bfd_vma extend, insn, val; if (r_type != R_MIPS16_26 && r_type != R_MIPS16_GPREL && r_type != R_MIPS16_HI16 && r_type != R_MIPS16_LO16) return; val = bfd_get_32 (abfd, data); if (r_type == R_MIPS16_26) { if (jal_shuffle) { insn = val & 0xffff; extend = ((val >> 16) & 0xfc00) | ((val >> 11) & 0x3e0) | ((val >> 21) & 0x1f); } else { insn = val & 0xffff; extend = val >> 16; } } else { insn = ((val >> 11) & 0xffe0) | (val & 0x1f); extend = ((val >> 16) & 0xf800) | ((val >> 11) & 0x1f) | (val & 0x7e0); } bfd_put_16 (abfd, insn, data + 2); bfd_put_16 (abfd, extend, data); } bfd_reloc_status_type _bfd_mips_elf_gprel16_with_gp (bfd *abfd, asymbol *symbol, arelent *reloc_entry, asection *input_section, bfd_boolean relocatable, void *data, bfd_vma gp) { bfd_vma relocation; bfd_signed_vma val; bfd_reloc_status_type status; if (bfd_is_com_section (symbol->section)) relocation = 0; else relocation = symbol->value; relocation += symbol->section->output_section->vma; relocation += symbol->section->output_offset; if (reloc_entry->address > bfd_get_section_limit (abfd, input_section)) return bfd_reloc_outofrange; /* Set val to the offset into the section or symbol. */ val = reloc_entry->addend; _bfd_mips_elf_sign_extend (val, 16); /* Adjust val for the final section location and GP value. If we are producing relocatable output, we don't want to do this for an external symbol. */ if (! relocatable || (symbol->flags & BSF_SECTION_SYM) != 0) val += relocation - gp; if (reloc_entry->howto->partial_inplace) { status = _bfd_relocate_contents (reloc_entry->howto, abfd, val, (bfd_byte *) data + reloc_entry->address); if (status != bfd_reloc_ok) return status; } else reloc_entry->addend = val; if (relocatable) reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } /* Used to store a REL high-part relocation such as R_MIPS_HI16 or R_MIPS_GOT16. REL is the relocation, INPUT_SECTION is the section that contains the relocation field and DATA points to the start of INPUT_SECTION. */ struct mips_hi16 { struct mips_hi16 *next; bfd_byte *data; asection *input_section; arelent rel; }; /* FIXME: This should not be a static variable. */ static struct mips_hi16 *mips_hi16_list; /* A howto special_function for REL *HI16 relocations. We can only calculate the correct value once we've seen the partnering *LO16 relocation, so just save the information for later. The ABI requires that the *LO16 immediately follow the *HI16. However, as a GNU extension, we permit an arbitrary number of *HI16s to be associated with a single *LO16. This significantly simplies the relocation handling in gcc. */ bfd_reloc_status_type _bfd_mips_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry, asymbol *symbol ATTRIBUTE_UNUSED, void *data, asection *input_section, bfd *output_bfd, char **error_message ATTRIBUTE_UNUSED) { struct mips_hi16 *n; if (reloc_entry->address > bfd_get_section_limit (abfd, input_section)) return bfd_reloc_outofrange; n = bfd_malloc (sizeof *n); if (n == NULL) return bfd_reloc_outofrange; n->next = mips_hi16_list; n->data = data; n->input_section = input_section; n->rel = *reloc_entry; mips_hi16_list = n; if (output_bfd != NULL) reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } /* A howto special_function for REL R_MIPS_GOT16 relocations. This is just like any other 16-bit relocation when applied to global symbols, but is treated in the same as R_MIPS_HI16 when applied to local symbols. */ bfd_reloc_status_type _bfd_mips_elf_got16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol, void *data, asection *input_section, bfd *output_bfd, char **error_message) { if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0 || bfd_is_und_section (bfd_get_section (symbol)) || bfd_is_com_section (bfd_get_section (symbol))) /* The relocation is against a global symbol. */ return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data, input_section, output_bfd, error_message); return _bfd_mips_elf_hi16_reloc (abfd, reloc_entry, symbol, data, input_section, output_bfd, error_message); } /* A howto special_function for REL *LO16 relocations. The *LO16 itself is a straightforward 16 bit inplace relocation, but we must deal with any partnering high-part relocations as well. */ bfd_reloc_status_type _bfd_mips_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol, void *data, asection *input_section, bfd *output_bfd, char **error_message) { bfd_vma vallo; bfd_byte *location = (bfd_byte *) data + reloc_entry->address; if (reloc_entry->address > bfd_get_section_limit (abfd, input_section)) return bfd_reloc_outofrange; _bfd_mips16_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE, location); vallo = bfd_get_32 (abfd, location); _bfd_mips16_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE, location); while (mips_hi16_list != NULL) { bfd_reloc_status_type ret; struct mips_hi16 *hi; hi = mips_hi16_list; /* R_MIPS_GOT16 relocations are something of a special case. We want to install the addend in the same way as for a R_MIPS_HI16 relocation (with a rightshift of 16). However, since GOT16 relocations can also be used with global symbols, their howto has a rightshift of 0. */ if (hi->rel.howto->type == R_MIPS_GOT16) hi->rel.howto = MIPS_ELF_RTYPE_TO_HOWTO (abfd, R_MIPS_HI16, FALSE); /* VALLO is a signed 16-bit number. Bias it by 0x8000 so that any carry or borrow will induce a change of +1 or -1 in the high part. */ hi->rel.addend += (vallo + 0x8000) & 0xffff; ret = _bfd_mips_elf_generic_reloc (abfd, &hi->rel, symbol, hi->data, hi->input_section, output_bfd, error_message); if (ret != bfd_reloc_ok) return ret; mips_hi16_list = hi->next; free (hi); } return _bfd_mips_elf_generic_reloc (abfd, reloc_entry, symbol, data, input_section, output_bfd, error_message); } /* A generic howto special_function. This calculates and installs the relocation itself, thus avoiding the oft-discussed problems in bfd_perform_relocation and bfd_install_relocation. */ bfd_reloc_status_type _bfd_mips_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry, asymbol *symbol, void *data ATTRIBUTE_UNUSED, asection *input_section, bfd *output_bfd, char **error_message ATTRIBUTE_UNUSED) { bfd_signed_vma val; bfd_reloc_status_type status; bfd_boolean relocatable; relocatable = (output_bfd != NULL); if (reloc_entry->address > bfd_get_section_limit (abfd, input_section)) return bfd_reloc_outofrange; /* Build up the field adjustment in VAL. */ val = 0; if (!relocatable || (symbol->flags & BSF_SECTION_SYM) != 0) { /* Either we're calculating the final field value or we have a relocation against a section symbol. Add in the section's offset or address. */ val += symbol->section->output_section->vma; val += symbol->section->output_offset; } if (!relocatable) { /* We're calculating the final field value. Add in the symbol's value and, if pc-relative, subtract the address of the field itself. */ val += symbol->value; if (reloc_entry->howto->pc_relative) { val -= input_section->output_section->vma; val -= input_section->output_offset; val -= reloc_entry->address; } } /* VAL is now the final adjustment. If we're keeping this relocation in the output file, and if the relocation uses a separate addend, we just need to add VAL to that addend. Otherwise we need to add VAL to the relocation field itself. */ if (relocatable && !reloc_entry->howto->partial_inplace) reloc_entry->addend += val; else { bfd_byte *location = (bfd_byte *) data + reloc_entry->address; /* Add in the separate addend, if any. */ val += reloc_entry->addend; /* Add VAL to the relocation field. */ _bfd_mips16_elf_reloc_unshuffle (abfd, reloc_entry->howto->type, FALSE, location); status = _bfd_relocate_contents (reloc_entry->howto, abfd, val, location); _bfd_mips16_elf_reloc_shuffle (abfd, reloc_entry->howto->type, FALSE, location); if (status != bfd_reloc_ok) return status; } if (relocatable) reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } /* Swap an entry in a .gptab section. Note that these routines rely on the equivalence of the two elements of the union. */ static void bfd_mips_elf32_swap_gptab_in (bfd *abfd, const Elf32_External_gptab *ex, Elf32_gptab *in) { in->gt_entry.gt_g_value = H_GET_32 (abfd, ex->gt_entry.gt_g_value); in->gt_entry.gt_bytes = H_GET_32 (abfd, ex->gt_entry.gt_bytes); } static void bfd_mips_elf32_swap_gptab_out (bfd *abfd, const Elf32_gptab *in, Elf32_External_gptab *ex) { H_PUT_32 (abfd, in->gt_entry.gt_g_value, ex->gt_entry.gt_g_value); H_PUT_32 (abfd, in->gt_entry.gt_bytes, ex->gt_entry.gt_bytes); } static void bfd_elf32_swap_compact_rel_out (bfd *abfd, const Elf32_compact_rel *in, Elf32_External_compact_rel *ex) { H_PUT_32 (abfd, in->id1, ex->id1); H_PUT_32 (abfd, in->num, ex->num); H_PUT_32 (abfd, in->id2, ex->id2); H_PUT_32 (abfd, in->offset, ex->offset); H_PUT_32 (abfd, in->reserved0, ex->reserved0); H_PUT_32 (abfd, in->reserved1, ex->reserved1); } static void bfd_elf32_swap_crinfo_out (bfd *abfd, const Elf32_crinfo *in, Elf32_External_crinfo *ex) { unsigned long l; l = (((in->ctype & CRINFO_CTYPE) << CRINFO_CTYPE_SH) | ((in->rtype & CRINFO_RTYPE) << CRINFO_RTYPE_SH) | ((in->dist2to & CRINFO_DIST2TO) << CRINFO_DIST2TO_SH) | ((in->relvaddr & CRINFO_RELVADDR) << CRINFO_RELVADDR_SH)); H_PUT_32 (abfd, l, ex->info); H_PUT_32 (abfd, in->konst, ex->konst); H_PUT_32 (abfd, in->vaddr, ex->vaddr); } /* A .reginfo section holds a single Elf32_RegInfo structure. These routines swap this structure in and out. They are used outside of BFD, so they are globally visible. */ void bfd_mips_elf32_swap_reginfo_in (bfd *abfd, const Elf32_External_RegInfo *ex, Elf32_RegInfo *in) { in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask); in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]); in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]); in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]); in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]); in->ri_gp_value = H_GET_32 (abfd, ex->ri_gp_value); } void bfd_mips_elf32_swap_reginfo_out (bfd *abfd, const Elf32_RegInfo *in, Elf32_External_RegInfo *ex) { H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask); H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]); H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]); H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]); H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]); H_PUT_32 (abfd, in->ri_gp_value, ex->ri_gp_value); } /* In the 64 bit ABI, the .MIPS.options section holds register information in an Elf64_Reginfo structure. These routines swap them in and out. They are globally visible because they are used outside of BFD. These routines are here so that gas can call them without worrying about whether the 64 bit ABI has been included. */ void bfd_mips_elf64_swap_reginfo_in (bfd *abfd, const Elf64_External_RegInfo *ex, Elf64_Internal_RegInfo *in) { in->ri_gprmask = H_GET_32 (abfd, ex->ri_gprmask); in->ri_pad = H_GET_32 (abfd, ex->ri_pad); in->ri_cprmask[0] = H_GET_32 (abfd, ex->ri_cprmask[0]); in->ri_cprmask[1] = H_GET_32 (abfd, ex->ri_cprmask[1]); in->ri_cprmask[2] = H_GET_32 (abfd, ex->ri_cprmask[2]); in->ri_cprmask[3] = H_GET_32 (abfd, ex->ri_cprmask[3]); in->ri_gp_value = H_GET_64 (abfd, ex->ri_gp_value); } void bfd_mips_elf64_swap_reginfo_out (bfd *abfd, const Elf64_Internal_RegInfo *in, Elf64_External_RegInfo *ex) { H_PUT_32 (abfd, in->ri_gprmask, ex->ri_gprmask); H_PUT_32 (abfd, in->ri_pad, ex->ri_pad); H_PUT_32 (abfd, in->ri_cprmask[0], ex->ri_cprmask[0]); H_PUT_32 (abfd, in->ri_cprmask[1], ex->ri_cprmask[1]); H_PUT_32 (abfd, in->ri_cprmask[2], ex->ri_cprmask[2]); H_PUT_32 (abfd, in->ri_cprmask[3], ex->ri_cprmask[3]); H_PUT_64 (abfd, in->ri_gp_value, ex->ri_gp_value); } /* Swap in an options header. */ void bfd_mips_elf_swap_options_in (bfd *abfd, const Elf_External_Options *ex, Elf_Internal_Options *in) { in->kind = H_GET_8 (abfd, ex->kind); in->size = H_GET_8 (abfd, ex->size); in->section = H_GET_16 (abfd, ex->section); in->info = H_GET_32 (abfd, ex->info); } /* Swap out an options header. */ void bfd_mips_elf_swap_options_out (bfd *abfd, const Elf_Internal_Options *in, Elf_External_Options *ex) { H_PUT_8 (abfd, in->kind, ex->kind); H_PUT_8 (abfd, in->size, ex->size); H_PUT_16 (abfd, in->section, ex->section); H_PUT_32 (abfd, in->info, ex->info); } /* This function is called via qsort() to sort the dynamic relocation entries by increasing r_symndx value. */ static int sort_dynamic_relocs (const void *arg1, const void *arg2) { Elf_Internal_Rela int_reloc1; Elf_Internal_Rela int_reloc2; bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1); bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2); return ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info); } /* Like sort_dynamic_relocs, but used for elf64 relocations. */ static int sort_dynamic_relocs_64 (const void *arg1 ATTRIBUTE_UNUSED, const void *arg2 ATTRIBUTE_UNUSED) { #ifdef BFD64 Elf_Internal_Rela int_reloc1[3]; Elf_Internal_Rela int_reloc2[3]; (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in) (reldyn_sorting_bfd, arg1, int_reloc1); (*get_elf_backend_data (reldyn_sorting_bfd)->s->swap_reloc_in) (reldyn_sorting_bfd, arg2, int_reloc2); return (ELF64_R_SYM (int_reloc1[0].r_info) - ELF64_R_SYM (int_reloc2[0].r_info)); #else abort (); #endif } /* This routine is used to write out ECOFF debugging external symbol information. It is called via mips_elf_link_hash_traverse. The ECOFF external symbol information must match the ELF external symbol information. Unfortunately, at this point we don't know whether a symbol is required by reloc information, so the two tables may wind up being different. We must sort out the external symbol information before we can set the final size of the .mdebug section, and we must set the size of the .mdebug section before we can relocate any sections, and we can't know which symbols are required by relocation until we relocate the sections. Fortunately, it is relatively unlikely that any symbol will be stripped but required by a reloc. In particular, it can not happen when generating a final executable. */ static bfd_boolean mips_elf_output_extsym (struct mips_elf_link_hash_entry *h, void *data) { struct extsym_info *einfo = data; bfd_boolean strip; asection *sec, *output_section; if (h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; if (h->root.indx == -2) strip = FALSE; else if ((h->root.def_dynamic || h->root.ref_dynamic || h->root.type == bfd_link_hash_new) && !h->root.def_regular && !h->root.ref_regular) strip = TRUE; else if (einfo->info->strip == strip_all || (einfo->info->strip == strip_some && bfd_hash_lookup (einfo->info->keep_hash, h->root.root.root.string, FALSE, FALSE) == NULL)) strip = TRUE; else strip = FALSE; if (strip) return TRUE; if (h->esym.ifd == -2) { h->esym.jmptbl = 0; h->esym.cobol_main = 0; h->esym.weakext = 0; h->esym.reserved = 0; h->esym.ifd = ifdNil; h->esym.asym.value = 0; h->esym.asym.st = stGlobal; if (h->root.root.type == bfd_link_hash_undefined || h->root.root.type == bfd_link_hash_undefweak) { const char *name; /* Use undefined class. Also, set class and type for some special symbols. */ name = h->root.root.root.string; if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0 || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0) { h->esym.asym.sc = scData; h->esym.asym.st = stLabel; h->esym.asym.value = 0; } else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0) { h->esym.asym.sc = scAbs; h->esym.asym.st = stLabel; h->esym.asym.value = mips_elf_hash_table (einfo->info)->procedure_count; } else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (einfo->abfd)) { h->esym.asym.sc = scAbs; h->esym.asym.st = stLabel; h->esym.asym.value = elf_gp (einfo->abfd); } else h->esym.asym.sc = scUndefined; } else if (h->root.root.type != bfd_link_hash_defined && h->root.root.type != bfd_link_hash_defweak) h->esym.asym.sc = scAbs; else { const char *name; sec = h->root.root.u.def.section; output_section = sec->output_section; /* When making a shared library and symbol h is the one from the another shared library, OUTPUT_SECTION may be null. */ if (output_section == NULL) h->esym.asym.sc = scUndefined; else { name = bfd_section_name (output_section->owner, output_section); if (strcmp (name, ".text") == 0) h->esym.asym.sc = scText; else if (strcmp (name, ".data") == 0) h->esym.asym.sc = scData; else if (strcmp (name, ".sdata") == 0) h->esym.asym.sc = scSData; else if (strcmp (name, ".rodata") == 0 || strcmp (name, ".rdata") == 0) h->esym.asym.sc = scRData; else if (strcmp (name, ".bss") == 0) h->esym.asym.sc = scBss; else if (strcmp (name, ".sbss") == 0) h->esym.asym.sc = scSBss; else if (strcmp (name, ".init") == 0) h->esym.asym.sc = scInit; else if (strcmp (name, ".fini") == 0) h->esym.asym.sc = scFini; else h->esym.asym.sc = scAbs; } } h->esym.asym.reserved = 0; h->esym.asym.index = indexNil; } if (h->root.root.type == bfd_link_hash_common) h->esym.asym.value = h->root.root.u.c.size; else if (h->root.root.type == bfd_link_hash_defined || h->root.root.type == bfd_link_hash_defweak) { if (h->esym.asym.sc == scCommon) h->esym.asym.sc = scBss; else if (h->esym.asym.sc == scSCommon) h->esym.asym.sc = scSBss; sec = h->root.root.u.def.section; output_section = sec->output_section; if (output_section != NULL) h->esym.asym.value = (h->root.root.u.def.value + sec->output_offset + output_section->vma); else h->esym.asym.value = 0; } else if (h->root.needs_plt) { struct mips_elf_link_hash_entry *hd = h; bfd_boolean no_fn_stub = h->no_fn_stub; while (hd->root.root.type == bfd_link_hash_indirect) { hd = (struct mips_elf_link_hash_entry *)h->root.root.u.i.link; no_fn_stub = no_fn_stub || hd->no_fn_stub; } if (!no_fn_stub) { /* Set type and value for a symbol with a function stub. */ h->esym.asym.st = stProc; sec = hd->root.root.u.def.section; if (sec == NULL) h->esym.asym.value = 0; else { output_section = sec->output_section; if (output_section != NULL) h->esym.asym.value = (hd->root.plt.offset + sec->output_offset + output_section->vma); else h->esym.asym.value = 0; } } } if (! bfd_ecoff_debug_one_external (einfo->abfd, einfo->debug, einfo->swap, h->root.root.root.string, &h->esym)) { einfo->failed = TRUE; return FALSE; } return TRUE; } /* A comparison routine used to sort .gptab entries. */ static int gptab_compare (const void *p1, const void *p2) { const Elf32_gptab *a1 = p1; const Elf32_gptab *a2 = p2; return a1->gt_entry.gt_g_value - a2->gt_entry.gt_g_value; } /* Functions to manage the got entry hash table. */ /* Use all 64 bits of a bfd_vma for the computation of a 32-bit hash number. */ static INLINE hashval_t mips_elf_hash_bfd_vma (bfd_vma addr) { #ifdef BFD64 return addr + (addr >> 32); #else return addr; #endif } /* got_entries only match if they're identical, except for gotidx, so use all fields to compute the hash, and compare the appropriate union members. */ static hashval_t mips_elf_got_entry_hash (const void *entry_) { const struct mips_got_entry *entry = (struct mips_got_entry *)entry_; return entry->symndx + ((entry->tls_type & GOT_TLS_LDM) << 17) + (! entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address) : entry->abfd->id + (entry->symndx >= 0 ? mips_elf_hash_bfd_vma (entry->d.addend) : entry->d.h->root.root.root.hash)); } static int mips_elf_got_entry_eq (const void *entry1, const void *entry2) { const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1; const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2; /* An LDM entry can only match another LDM entry. */ if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM) return 0; return e1->abfd == e2->abfd && e1->symndx == e2->symndx && (! e1->abfd ? e1->d.address == e2->d.address : e1->symndx >= 0 ? e1->d.addend == e2->d.addend : e1->d.h == e2->d.h); } /* multi_got_entries are still a match in the case of global objects, even if the input bfd in which they're referenced differs, so the hash computation and compare functions are adjusted accordingly. */ static hashval_t mips_elf_multi_got_entry_hash (const void *entry_) { const struct mips_got_entry *entry = (struct mips_got_entry *)entry_; return entry->symndx + (! entry->abfd ? mips_elf_hash_bfd_vma (entry->d.address) : entry->symndx >= 0 ? ((entry->tls_type & GOT_TLS_LDM) ? (GOT_TLS_LDM << 17) : (entry->abfd->id + mips_elf_hash_bfd_vma (entry->d.addend))) : entry->d.h->root.root.root.hash); } static int mips_elf_multi_got_entry_eq (const void *entry1, const void *entry2) { const struct mips_got_entry *e1 = (struct mips_got_entry *)entry1; const struct mips_got_entry *e2 = (struct mips_got_entry *)entry2; /* Any two LDM entries match. */ if (e1->tls_type & e2->tls_type & GOT_TLS_LDM) return 1; /* Nothing else matches an LDM entry. */ if ((e1->tls_type ^ e2->tls_type) & GOT_TLS_LDM) return 0; return e1->symndx == e2->symndx && (e1->symndx >= 0 ? e1->abfd == e2->abfd && e1->d.addend == e2->d.addend : e1->abfd == NULL || e2->abfd == NULL ? e1->abfd == e2->abfd && e1->d.address == e2->d.address : e1->d.h == e2->d.h); } /* Returns the dynamic relocation section for DYNOBJ. */ static asection * mips_elf_rel_dyn_section (bfd *dynobj, bfd_boolean create_p) { static const char dname[] = ".rel.dyn"; asection *sreloc; sreloc = bfd_get_section_by_name (dynobj, dname); if (sreloc == NULL && create_p) { sreloc = bfd_make_section_with_flags (dynobj, dname, (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY)); if (sreloc == NULL || ! bfd_set_section_alignment (dynobj, sreloc, MIPS_ELF_LOG_FILE_ALIGN (dynobj))) return NULL; } return sreloc; } /* Returns the GOT section for ABFD. */ static asection * mips_elf_got_section (bfd *abfd, bfd_boolean maybe_excluded) { asection *sgot = bfd_get_section_by_name (abfd, ".got"); if (sgot == NULL || (! maybe_excluded && (sgot->flags & SEC_EXCLUDE) != 0)) return NULL; return sgot; } /* Returns the GOT information associated with the link indicated by INFO. If SGOTP is non-NULL, it is filled in with the GOT section. */ static struct mips_got_info * mips_elf_got_info (bfd *abfd, asection **sgotp) { asection *sgot; struct mips_got_info *g; sgot = mips_elf_got_section (abfd, TRUE); BFD_ASSERT (sgot != NULL); BFD_ASSERT (mips_elf_section_data (sgot) != NULL); g = mips_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); if (sgotp) *sgotp = (sgot->flags & SEC_EXCLUDE) == 0 ? sgot : NULL; return g; } /* Count the number of relocations needed for a TLS GOT entry, with access types from TLS_TYPE, and symbol H (or a local symbol if H is NULL). */ static int mips_tls_got_relocs (struct bfd_link_info *info, unsigned char tls_type, struct elf_link_hash_entry *h) { int indx = 0; int ret = 0; bfd_boolean need_relocs = FALSE; bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created; if (h && WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, h) && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, h))) indx = h->dynindx; if ((info->shared || indx != 0) && (h == NULL || ELF_ST_VISIBILITY (h->other) == STV_DEFAULT || h->root.type != bfd_link_hash_undefweak)) need_relocs = TRUE; if (!need_relocs) return FALSE; if (tls_type & GOT_TLS_GD) { ret++; if (indx != 0) ret++; } if (tls_type & GOT_TLS_IE) ret++; if ((tls_type & GOT_TLS_LDM) && info->shared) ret++; return ret; } /* Count the number of TLS relocations required for the GOT entry in ARG1, if it describes a local symbol. */ static int mips_elf_count_local_tls_relocs (void **arg1, void *arg2) { struct mips_got_entry *entry = * (struct mips_got_entry **) arg1; struct mips_elf_count_tls_arg *arg = arg2; if (entry->abfd != NULL && entry->symndx != -1) arg->needed += mips_tls_got_relocs (arg->info, entry->tls_type, NULL); return 1; } /* Count the number of TLS GOT entries required for the global (or forced-local) symbol in ARG1. */ static int mips_elf_count_global_tls_entries (void *arg1, void *arg2) { struct mips_elf_link_hash_entry *hm = (struct mips_elf_link_hash_entry *) arg1; struct mips_elf_count_tls_arg *arg = arg2; if (hm->tls_type & GOT_TLS_GD) arg->needed += 2; if (hm->tls_type & GOT_TLS_IE) arg->needed += 1; return 1; } /* Count the number of TLS relocations required for the global (or forced-local) symbol in ARG1. */ static int mips_elf_count_global_tls_relocs (void *arg1, void *arg2) { struct mips_elf_link_hash_entry *hm = (struct mips_elf_link_hash_entry *) arg1; struct mips_elf_count_tls_arg *arg = arg2; arg->needed += mips_tls_got_relocs (arg->info, hm->tls_type, &hm->root); return 1; } /* Output a simple dynamic relocation into SRELOC. */ static void mips_elf_output_dynamic_relocation (bfd *output_bfd, asection *sreloc, unsigned long indx, int r_type, bfd_vma offset) { Elf_Internal_Rela rel[3]; memset (rel, 0, sizeof (rel)); rel[0].r_info = ELF_R_INFO (output_bfd, indx, r_type); rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset; if (ABI_64_P (output_bfd)) { (*get_elf_backend_data (output_bfd)->s->swap_reloc_out) (output_bfd, &rel[0], (sreloc->contents + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel))); } else bfd_elf32_swap_reloc_out (output_bfd, &rel[0], (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel))); ++sreloc->reloc_count; } /* Initialize a set of TLS GOT entries for one symbol. */ static void mips_elf_initialize_tls_slots (bfd *abfd, bfd_vma got_offset, unsigned char *tls_type_p, struct bfd_link_info *info, struct mips_elf_link_hash_entry *h, bfd_vma value) { int indx; asection *sreloc, *sgot; bfd_vma offset, offset2; bfd *dynobj; bfd_boolean need_relocs = FALSE; dynobj = elf_hash_table (info)->dynobj; sgot = mips_elf_got_section (dynobj, FALSE); indx = 0; if (h != NULL) { bfd_boolean dyn = elf_hash_table (info)->dynamic_sections_created; if (WILL_CALL_FINISH_DYNAMIC_SYMBOL (dyn, info->shared, &h->root) && (!info->shared || !SYMBOL_REFERENCES_LOCAL (info, &h->root))) indx = h->root.dynindx; } if (*tls_type_p & GOT_TLS_DONE) return; if ((info->shared || indx != 0) && (h == NULL || ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT || h->root.type != bfd_link_hash_undefweak)) need_relocs = TRUE; /* MINUS_ONE means the symbol is not defined in this object. It may not be defined at all; assume that the value doesn't matter in that case. Otherwise complain if we would use the value. */ BFD_ASSERT (value != MINUS_ONE || (indx != 0 && need_relocs) || h->root.root.type == bfd_link_hash_undefweak); /* Emit necessary relocations. */ sreloc = mips_elf_rel_dyn_section (dynobj, FALSE); /* General Dynamic. */ if (*tls_type_p & GOT_TLS_GD) { offset = got_offset; offset2 = offset + MIPS_ELF_GOT_SIZE (abfd); if (need_relocs) { mips_elf_output_dynamic_relocation (abfd, sreloc, indx, ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32, sgot->output_offset + sgot->output_section->vma + offset); if (indx) mips_elf_output_dynamic_relocation (abfd, sreloc, indx, ABI_64_P (abfd) ? R_MIPS_TLS_DTPREL64 : R_MIPS_TLS_DTPREL32, sgot->output_offset + sgot->output_section->vma + offset2); else MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info), sgot->contents + offset2); } else { MIPS_ELF_PUT_WORD (abfd, 1, sgot->contents + offset); MIPS_ELF_PUT_WORD (abfd, value - dtprel_base (info), sgot->contents + offset2); } got_offset += 2 * MIPS_ELF_GOT_SIZE (abfd); } /* Initial Exec model. */ if (*tls_type_p & GOT_TLS_IE) { offset = got_offset; if (need_relocs) { if (indx == 0) MIPS_ELF_PUT_WORD (abfd, value - elf_hash_table (info)->tls_sec->vma, sgot->contents + offset); else MIPS_ELF_PUT_WORD (abfd, 0, sgot->contents + offset); mips_elf_output_dynamic_relocation (abfd, sreloc, indx, ABI_64_P (abfd) ? R_MIPS_TLS_TPREL64 : R_MIPS_TLS_TPREL32, sgot->output_offset + sgot->output_section->vma + offset); } else MIPS_ELF_PUT_WORD (abfd, value - tprel_base (info), sgot->contents + offset); } if (*tls_type_p & GOT_TLS_LDM) { /* The initial offset is zero, and the LD offsets will include the bias by DTP_OFFSET. */ MIPS_ELF_PUT_WORD (abfd, 0, sgot->contents + got_offset + MIPS_ELF_GOT_SIZE (abfd)); if (!info->shared) MIPS_ELF_PUT_WORD (abfd, 1, sgot->contents + got_offset); else mips_elf_output_dynamic_relocation (abfd, sreloc, indx, ABI_64_P (abfd) ? R_MIPS_TLS_DTPMOD64 : R_MIPS_TLS_DTPMOD32, sgot->output_offset + sgot->output_section->vma + got_offset); } *tls_type_p |= GOT_TLS_DONE; } /* Return the GOT index to use for a relocation of type R_TYPE against a symbol accessed using TLS_TYPE models. The GOT entries for this symbol in this GOT start at GOT_INDEX. This function initializes the GOT entries and corresponding relocations. */ static bfd_vma mips_tls_got_index (bfd *abfd, bfd_vma got_index, unsigned char *tls_type, int r_type, struct bfd_link_info *info, struct mips_elf_link_hash_entry *h, bfd_vma symbol) { BFD_ASSERT (r_type == R_MIPS_TLS_GOTTPREL || r_type == R_MIPS_TLS_GD || r_type == R_MIPS_TLS_LDM); mips_elf_initialize_tls_slots (abfd, got_index, tls_type, info, h, symbol); if (r_type == R_MIPS_TLS_GOTTPREL) { BFD_ASSERT (*tls_type & GOT_TLS_IE); if (*tls_type & GOT_TLS_GD) return got_index + 2 * MIPS_ELF_GOT_SIZE (abfd); else return got_index; } if (r_type == R_MIPS_TLS_GD) { BFD_ASSERT (*tls_type & GOT_TLS_GD); return got_index; } if (r_type == R_MIPS_TLS_LDM) { BFD_ASSERT (*tls_type & GOT_TLS_LDM); return got_index; } return got_index; } /* Returns the GOT offset at which the indicated address can be found. If there is not yet a GOT entry for this value, create one. If R_SYMNDX refers to a TLS symbol, create a TLS GOT entry instead. Returns -1 if no satisfactory GOT offset can be found. */ static bfd_vma mips_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info, bfd_vma value, unsigned long r_symndx, struct mips_elf_link_hash_entry *h, int r_type) { asection *sgot; struct mips_got_info *g; struct mips_got_entry *entry; g = mips_elf_got_info (elf_hash_table (info)->dynobj, &sgot); entry = mips_elf_create_local_got_entry (abfd, ibfd, g, sgot, value, r_symndx, h, r_type); if (!entry) return MINUS_ONE; if (TLS_RELOC_P (r_type)) return mips_tls_got_index (abfd, entry->gotidx, &entry->tls_type, r_type, info, h, value); else return entry->gotidx; } /* Returns the GOT index for the global symbol indicated by H. */ static bfd_vma mips_elf_global_got_index (bfd *abfd, bfd *ibfd, struct elf_link_hash_entry *h, int r_type, struct bfd_link_info *info) { bfd_vma index; asection *sgot; struct mips_got_info *g, *gg; long global_got_dynindx = 0; gg = g = mips_elf_got_info (abfd, &sgot); if (g->bfd2got && ibfd) { struct mips_got_entry e, *p; BFD_ASSERT (h->dynindx >= 0); g = mips_elf_got_for_ibfd (g, ibfd); if (g->next != gg || TLS_RELOC_P (r_type)) { e.abfd = ibfd; e.symndx = -1; e.d.h = (struct mips_elf_link_hash_entry *)h; e.tls_type = 0; p = htab_find (g->got_entries, &e); BFD_ASSERT (p->gotidx > 0); if (TLS_RELOC_P (r_type)) { bfd_vma value = MINUS_ONE; if ((h->root.type == bfd_link_hash_defined || h->root.type == bfd_link_hash_defweak) && h->root.u.def.section->output_section) value = (h->root.u.def.value + h->root.u.def.section->output_offset + h->root.u.def.section->output_section->vma); return mips_tls_got_index (abfd, p->gotidx, &p->tls_type, r_type, info, e.d.h, value); } else return p->gotidx; } } if (gg->global_gotsym != NULL) global_got_dynindx = gg->global_gotsym->dynindx; if (TLS_RELOC_P (r_type)) { struct mips_elf_link_hash_entry *hm = (struct mips_elf_link_hash_entry *) h; bfd_vma value = MINUS_ONE; if ((h->root.type == bfd_link_hash_defined || h->root.type == bfd_link_hash_defweak) && h->root.u.def.section->output_section) value = (h->root.u.def.value + h->root.u.def.section->output_offset + h->root.u.def.section->output_section->vma); index = mips_tls_got_index (abfd, hm->tls_got_offset, &hm->tls_type, r_type, info, hm, value); } else { /* Once we determine the global GOT entry with the lowest dynamic symbol table index, we must put all dynamic symbols with greater indices into the GOT. That makes it easy to calculate the GOT offset. */ BFD_ASSERT (h->dynindx >= global_got_dynindx); index = ((h->dynindx - global_got_dynindx + g->local_gotno) * MIPS_ELF_GOT_SIZE (abfd)); } BFD_ASSERT (index < sgot->size); return index; } /* Find a GOT entry that is within 32KB of the VALUE. These entries are supposed to be placed at small offsets in the GOT, i.e., within 32KB of GP. Return the index into the GOT for this page, and store the offset from this entry to the desired address in OFFSETP, if it is non-NULL. */ static bfd_vma mips_elf_got_page (bfd *abfd, bfd *ibfd, struct bfd_link_info *info, bfd_vma value, bfd_vma *offsetp) { asection *sgot; struct mips_got_info *g; bfd_vma index; struct mips_got_entry *entry; g = mips_elf_got_info (elf_hash_table (info)->dynobj, &sgot); entry = mips_elf_create_local_got_entry (abfd, ibfd, g, sgot, (value + 0x8000) & (~(bfd_vma)0xffff), 0, NULL, R_MIPS_GOT_PAGE); if (!entry) return MINUS_ONE; index = entry->gotidx; if (offsetp) *offsetp = value - entry->d.address; return index; } /* Find a GOT entry whose higher-order 16 bits are the same as those for value. Return the index into the GOT for this entry. */ static bfd_vma mips_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info, bfd_vma value, bfd_boolean external) { asection *sgot; struct mips_got_info *g; struct mips_got_entry *entry; if (! external) { /* Although the ABI says that it is "the high-order 16 bits" that we want, it is really the %high value. The complete value is calculated with a `addiu' of a LO16 relocation, just as with a HI16/LO16 pair. */ value = mips_elf_high (value) << 16; } g = mips_elf_got_info (elf_hash_table (info)->dynobj, &sgot); entry = mips_elf_create_local_got_entry (abfd, ibfd, g, sgot, value, 0, NULL, R_MIPS_GOT16); if (entry) return entry->gotidx; else return MINUS_ONE; } /* Returns the offset for the entry at the INDEXth position in the GOT. */ static bfd_vma mips_elf_got_offset_from_index (bfd *dynobj, bfd *output_bfd, bfd *input_bfd, bfd_vma index) { asection *sgot; bfd_vma gp; struct mips_got_info *g; g = mips_elf_got_info (dynobj, &sgot); gp = _bfd_get_gp_value (output_bfd) + mips_elf_adjust_gp (output_bfd, g, input_bfd); return sgot->output_section->vma + sgot->output_offset + index - gp; } /* Create a local GOT entry for VALUE. Return the index of the entry, or -1 if it could not be created. If R_SYMNDX refers to a TLS symbol, create a TLS entry instead. */ static struct mips_got_entry * mips_elf_create_local_got_entry (bfd *abfd, bfd *ibfd, struct mips_got_info *gg, asection *sgot, bfd_vma value, unsigned long r_symndx, struct mips_elf_link_hash_entry *h, int r_type) { struct mips_got_entry entry, **loc; struct mips_got_info *g; entry.abfd = NULL; entry.symndx = -1; entry.d.address = value; entry.tls_type = 0; g = mips_elf_got_for_ibfd (gg, ibfd); if (g == NULL) { g = mips_elf_got_for_ibfd (gg, abfd); BFD_ASSERT (g != NULL); } /* We might have a symbol, H, if it has been forced local. Use the global entry then. It doesn't matter whether an entry is local or global for TLS, since the dynamic linker does not automatically relocate TLS GOT entries. */ BFD_ASSERT (h == NULL || h->root.forced_local); if (TLS_RELOC_P (r_type)) { struct mips_got_entry *p; entry.abfd = ibfd; if (r_type == R_MIPS_TLS_LDM) { entry.tls_type = GOT_TLS_LDM; entry.symndx = 0; entry.d.addend = 0; } else if (h == NULL) { entry.symndx = r_symndx; entry.d.addend = 0; } else entry.d.h = h; p = (struct mips_got_entry *) htab_find (g->got_entries, &entry); BFD_ASSERT (p); return p; } loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry, INSERT); if (*loc) return *loc; entry.gotidx = MIPS_ELF_GOT_SIZE (abfd) * g->assigned_gotno++; entry.tls_type = 0; *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry); if (! *loc) return NULL; memcpy (*loc, &entry, sizeof entry); if (g->assigned_gotno >= g->local_gotno) { (*loc)->gotidx = -1; /* We didn't allocate enough space in the GOT. */ (*_bfd_error_handler) (_("not enough GOT space for local GOT entries")); bfd_set_error (bfd_error_bad_value); return NULL; } MIPS_ELF_PUT_WORD (abfd, value, (sgot->contents + entry.gotidx)); return *loc; } /* Sort the dynamic symbol table so that symbols that need GOT entries appear towards the end. This reduces the amount of GOT space required. MAX_LOCAL is used to set the number of local symbols known to be in the dynamic symbol table. During _bfd_mips_elf_size_dynamic_sections, this value is 1. Afterward, the section symbols are added and the count is higher. */ static bfd_boolean mips_elf_sort_hash_table (struct bfd_link_info *info, unsigned long max_local) { struct mips_elf_hash_sort_data hsd; struct mips_got_info *g; bfd *dynobj; dynobj = elf_hash_table (info)->dynobj; g = mips_elf_got_info (dynobj, NULL); hsd.low = NULL; hsd.max_unref_got_dynindx = hsd.min_got_dynindx = elf_hash_table (info)->dynsymcount /* In the multi-got case, assigned_gotno of the master got_info indicate the number of entries that aren't referenced in the primary GOT, but that must have entries because there are dynamic relocations that reference it. Since they aren't referenced, we move them to the end of the GOT, so that they don't prevent other entries that are referenced from getting too large offsets. */ - (g->next ? g->assigned_gotno : 0); hsd.max_non_got_dynindx = max_local; mips_elf_link_hash_traverse (((struct mips_elf_link_hash_table *) elf_hash_table (info)), mips_elf_sort_hash_table_f, &hsd); /* There should have been enough room in the symbol table to accommodate both the GOT and non-GOT symbols. */ BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx); BFD_ASSERT ((unsigned long)hsd.max_unref_got_dynindx <= elf_hash_table (info)->dynsymcount); /* Now we know which dynamic symbol has the lowest dynamic symbol table index in the GOT. */ g->global_gotsym = hsd.low; return TRUE; } /* If H needs a GOT entry, assign it the highest available dynamic index. Otherwise, assign it the lowest available dynamic index. */ static bfd_boolean mips_elf_sort_hash_table_f (struct mips_elf_link_hash_entry *h, void *data) { struct mips_elf_hash_sort_data *hsd = data; if (h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; /* Symbols without dynamic symbol table entries aren't interesting at all. */ if (h->root.dynindx == -1) return TRUE; /* Global symbols that need GOT entries that are not explicitly referenced are marked with got offset 2. Those that are referenced get a 1, and those that don't need GOT entries get -1. */ if (h->root.got.offset == 2) { BFD_ASSERT (h->tls_type == GOT_NORMAL); if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx) hsd->low = (struct elf_link_hash_entry *) h; h->root.dynindx = hsd->max_unref_got_dynindx++; } else if (h->root.got.offset != 1) h->root.dynindx = hsd->max_non_got_dynindx++; else { BFD_ASSERT (h->tls_type == GOT_NORMAL); h->root.dynindx = --hsd->min_got_dynindx; hsd->low = (struct elf_link_hash_entry *) h; } return TRUE; } /* If H is a symbol that needs a global GOT entry, but has a dynamic symbol table index lower than any we've seen to date, record it for posterity. */ static bfd_boolean mips_elf_record_global_got_symbol (struct elf_link_hash_entry *h, bfd *abfd, struct bfd_link_info *info, struct mips_got_info *g, unsigned char tls_flag) { struct mips_got_entry entry, **loc; /* A global symbol in the GOT must also be in the dynamic symbol table. */ if (h->dynindx == -1) { switch (ELF_ST_VISIBILITY (h->other)) { case STV_INTERNAL: case STV_HIDDEN: _bfd_mips_elf_hide_symbol (info, h, TRUE); break; } if (!bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } entry.abfd = abfd; entry.symndx = -1; entry.d.h = (struct mips_elf_link_hash_entry *) h; entry.tls_type = 0; loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry, INSERT); /* If we've already marked this entry as needing GOT space, we don't need to do it again. */ if (*loc) { (*loc)->tls_type |= tls_flag; return TRUE; } *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry); if (! *loc) return FALSE; entry.gotidx = -1; entry.tls_type = tls_flag; memcpy (*loc, &entry, sizeof entry); if (h->got.offset != MINUS_ONE) return TRUE; /* By setting this to a value other than -1, we are indicating that there needs to be a GOT entry for H. Avoid using zero, as the generic ELF copy_indirect_symbol tests for <= 0. */ if (tls_flag == 0) h->got.offset = 1; return TRUE; } /* Reserve space in G for a GOT entry containing the value of symbol SYMNDX in input bfd ABDF, plus ADDEND. */ static bfd_boolean mips_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend, struct mips_got_info *g, unsigned char tls_flag) { struct mips_got_entry entry, **loc; entry.abfd = abfd; entry.symndx = symndx; entry.d.addend = addend; entry.tls_type = tls_flag; loc = (struct mips_got_entry **) htab_find_slot (g->got_entries, &entry, INSERT); if (*loc) { if (tls_flag == GOT_TLS_GD && !((*loc)->tls_type & GOT_TLS_GD)) { g->tls_gotno += 2; (*loc)->tls_type |= tls_flag; } else if (tls_flag == GOT_TLS_IE && !((*loc)->tls_type & GOT_TLS_IE)) { g->tls_gotno += 1; (*loc)->tls_type |= tls_flag; } return TRUE; } if (tls_flag != 0) { entry.gotidx = -1; entry.tls_type = tls_flag; if (tls_flag == GOT_TLS_IE) g->tls_gotno += 1; else if (tls_flag == GOT_TLS_GD) g->tls_gotno += 2; else if (g->tls_ldm_offset == MINUS_ONE) { g->tls_ldm_offset = MINUS_TWO; g->tls_gotno += 2; } } else { entry.gotidx = g->local_gotno++; entry.tls_type = 0; } *loc = (struct mips_got_entry *)bfd_alloc (abfd, sizeof entry); if (! *loc) return FALSE; memcpy (*loc, &entry, sizeof entry); return TRUE; } /* Compute the hash value of the bfd in a bfd2got hash entry. */ static hashval_t mips_elf_bfd2got_entry_hash (const void *entry_) { const struct mips_elf_bfd2got_hash *entry = (struct mips_elf_bfd2got_hash *)entry_; return entry->bfd->id; } /* Check whether two hash entries have the same bfd. */ static int mips_elf_bfd2got_entry_eq (const void *entry1, const void *entry2) { const struct mips_elf_bfd2got_hash *e1 = (const struct mips_elf_bfd2got_hash *)entry1; const struct mips_elf_bfd2got_hash *e2 = (const struct mips_elf_bfd2got_hash *)entry2; return e1->bfd == e2->bfd; } /* In a multi-got link, determine the GOT to be used for IBDF. G must be the master GOT data. */ static struct mips_got_info * mips_elf_got_for_ibfd (struct mips_got_info *g, bfd *ibfd) { struct mips_elf_bfd2got_hash e, *p; if (! g->bfd2got) return g; e.bfd = ibfd; p = htab_find (g->bfd2got, &e); return p ? p->g : NULL; } /* Create one separate got for each bfd that has entries in the global got, such that we can tell how many local and global entries each bfd requires. */ static int mips_elf_make_got_per_bfd (void **entryp, void *p) { struct mips_got_entry *entry = (struct mips_got_entry *)*entryp; struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p; htab_t bfd2got = arg->bfd2got; struct mips_got_info *g; struct mips_elf_bfd2got_hash bfdgot_entry, *bfdgot; void **bfdgotp; /* Find the got_info for this GOT entry's input bfd. Create one if none exists. */ bfdgot_entry.bfd = entry->abfd; bfdgotp = htab_find_slot (bfd2got, &bfdgot_entry, INSERT); bfdgot = (struct mips_elf_bfd2got_hash *)*bfdgotp; if (bfdgot != NULL) g = bfdgot->g; else { bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc (arg->obfd, sizeof (struct mips_elf_bfd2got_hash)); if (bfdgot == NULL) { arg->obfd = 0; return 0; } *bfdgotp = bfdgot; bfdgot->bfd = entry->abfd; bfdgot->g = g = (struct mips_got_info *) bfd_alloc (arg->obfd, sizeof (struct mips_got_info)); if (g == NULL) { arg->obfd = 0; return 0; } g->global_gotsym = NULL; g->global_gotno = 0; g->local_gotno = 0; g->assigned_gotno = -1; g->tls_gotno = 0; g->tls_assigned_gotno = 0; g->tls_ldm_offset = MINUS_ONE; g->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash, mips_elf_multi_got_entry_eq, NULL); if (g->got_entries == NULL) { arg->obfd = 0; return 0; } g->bfd2got = NULL; g->next = NULL; } /* Insert the GOT entry in the bfd's got entry hash table. */ entryp = htab_find_slot (g->got_entries, entry, INSERT); if (*entryp != NULL) return 1; *entryp = entry; if (entry->tls_type) { if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM)) g->tls_gotno += 2; if (entry->tls_type & GOT_TLS_IE) g->tls_gotno += 1; } else if (entry->symndx >= 0 || entry->d.h->forced_local) ++g->local_gotno; else ++g->global_gotno; return 1; } /* Attempt to merge gots of different input bfds. Try to use as much as possible of the primary got, since it doesn't require explicit dynamic relocations, but don't use bfds that would reference global symbols out of the addressable range. Failing the primary got, attempt to merge with the current got, or finish the current got and then make make the new got current. */ static int mips_elf_merge_gots (void **bfd2got_, void *p) { struct mips_elf_bfd2got_hash *bfd2got = (struct mips_elf_bfd2got_hash *)*bfd2got_; struct mips_elf_got_per_bfd_arg *arg = (struct mips_elf_got_per_bfd_arg *)p; unsigned int lcount = bfd2got->g->local_gotno; unsigned int gcount = bfd2got->g->global_gotno; unsigned int tcount = bfd2got->g->tls_gotno; unsigned int maxcnt = arg->max_count; bfd_boolean too_many_for_tls = FALSE; /* We place TLS GOT entries after both locals and globals. The globals for the primary GOT may overflow the normal GOT size limit, so be sure not to merge a GOT which requires TLS with the primary GOT in that case. This doesn't affect non-primary GOTs. */ if (tcount > 0) { unsigned int primary_total = lcount + tcount + arg->global_count; if (primary_total * MIPS_ELF_GOT_SIZE (bfd2got->bfd) >= MIPS_ELF_GOT_MAX_SIZE (bfd2got->bfd)) too_many_for_tls = TRUE; } /* If we don't have a primary GOT and this is not too big, use it as a starting point for the primary GOT. */ if (! arg->primary && lcount + gcount + tcount <= maxcnt && ! too_many_for_tls) { arg->primary = bfd2got->g; arg->primary_count = lcount + gcount; } /* If it looks like we can merge this bfd's entries with those of the primary, merge them. The heuristics is conservative, but we don't have to squeeze it too hard. */ else if (arg->primary && ! too_many_for_tls && (arg->primary_count + lcount + gcount + tcount) <= maxcnt) { struct mips_got_info *g = bfd2got->g; int old_lcount = arg->primary->local_gotno; int old_gcount = arg->primary->global_gotno; int old_tcount = arg->primary->tls_gotno; bfd2got->g = arg->primary; htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, arg); if (arg->obfd == NULL) return 0; htab_delete (g->got_entries); /* We don't have to worry about releasing memory of the actual got entries, since they're all in the master got_entries hash table anyway. */ BFD_ASSERT (old_lcount + lcount >= arg->primary->local_gotno); BFD_ASSERT (old_gcount + gcount >= arg->primary->global_gotno); BFD_ASSERT (old_tcount + tcount >= arg->primary->tls_gotno); arg->primary_count = arg->primary->local_gotno + arg->primary->global_gotno + arg->primary->tls_gotno; } /* If we can merge with the last-created got, do it. */ else if (arg->current && arg->current_count + lcount + gcount + tcount <= maxcnt) { struct mips_got_info *g = bfd2got->g; int old_lcount = arg->current->local_gotno; int old_gcount = arg->current->global_gotno; int old_tcount = arg->current->tls_gotno; bfd2got->g = arg->current; htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, arg); if (arg->obfd == NULL) return 0; htab_delete (g->got_entries); BFD_ASSERT (old_lcount + lcount >= arg->current->local_gotno); BFD_ASSERT (old_gcount + gcount >= arg->current->global_gotno); BFD_ASSERT (old_tcount + tcount >= arg->current->tls_gotno); arg->current_count = arg->current->local_gotno + arg->current->global_gotno + arg->current->tls_gotno; } /* Well, we couldn't merge, so create a new GOT. Don't check if it fits; if it turns out that it doesn't, we'll get relocation overflows anyway. */ else { bfd2got->g->next = arg->current; arg->current = bfd2got->g; arg->current_count = lcount + gcount + 2 * tcount; } return 1; } /* Set the TLS GOT index for the GOT entry in ENTRYP. */ static int mips_elf_initialize_tls_index (void **entryp, void *p) { struct mips_got_entry *entry = (struct mips_got_entry *)*entryp; struct mips_got_info *g = p; /* We're only interested in TLS symbols. */ if (entry->tls_type == 0) return 1; if (entry->symndx == -1) { /* There may be multiple mips_got_entry structs for a global variable if there is just one GOT. Just do this once. */ if (g->next == NULL) { if (entry->d.h->tls_type & GOT_TLS_OFFSET_DONE) return 1; entry->d.h->tls_type |= GOT_TLS_OFFSET_DONE; } } else if (entry->tls_type & GOT_TLS_LDM) { /* Similarly, there may be multiple structs for the LDM entry. */ if (g->tls_ldm_offset != MINUS_TWO && g->tls_ldm_offset != MINUS_ONE) { entry->gotidx = g->tls_ldm_offset; return 1; } } /* Initialize the GOT offset. */ entry->gotidx = MIPS_ELF_GOT_SIZE (entry->abfd) * (long) g->tls_assigned_gotno; if (g->next == NULL && entry->symndx == -1) entry->d.h->tls_got_offset = entry->gotidx; if (entry->tls_type & (GOT_TLS_GD | GOT_TLS_LDM)) g->tls_assigned_gotno += 2; if (entry->tls_type & GOT_TLS_IE) g->tls_assigned_gotno += 1; if (entry->tls_type & GOT_TLS_LDM) g->tls_ldm_offset = entry->gotidx; return 1; } /* If passed a NULL mips_got_info in the argument, set the marker used to tell whether a global symbol needs a got entry (in the primary got) to the given VALUE. If passed a pointer G to a mips_got_info in the argument (it must not be the primary GOT), compute the offset from the beginning of the (primary) GOT section to the entry in G corresponding to the global symbol. G's assigned_gotno must contain the index of the first available global GOT entry in G. VALUE must contain the size of a GOT entry in bytes. For each global GOT entry that requires a dynamic relocation, NEEDED_RELOCS is incremented, and the symbol is marked as not eligible for lazy resolution through a function stub. */ static int mips_elf_set_global_got_offset (void **entryp, void *p) { struct mips_got_entry *entry = (struct mips_got_entry *)*entryp; struct mips_elf_set_global_got_offset_arg *arg = (struct mips_elf_set_global_got_offset_arg *)p; struct mips_got_info *g = arg->g; if (g && entry->tls_type != GOT_NORMAL) arg->needed_relocs += mips_tls_got_relocs (arg->info, entry->tls_type, entry->symndx == -1 ? &entry->d.h->root : NULL); if (entry->abfd != NULL && entry->symndx == -1 && entry->d.h->root.dynindx != -1 && entry->d.h->tls_type == GOT_NORMAL) { if (g) { BFD_ASSERT (g->global_gotsym == NULL); entry->gotidx = arg->value * (long) g->assigned_gotno++; if (arg->info->shared || (elf_hash_table (arg->info)->dynamic_sections_created && entry->d.h->root.def_dynamic && !entry->d.h->root.def_regular)) ++arg->needed_relocs; } else entry->d.h->root.got.offset = arg->value; } return 1; } /* Mark any global symbols referenced in the GOT we are iterating over as inelligible for lazy resolution stubs. */ static int mips_elf_set_no_stub (void **entryp, void *p ATTRIBUTE_UNUSED) { struct mips_got_entry *entry = (struct mips_got_entry *)*entryp; if (entry->abfd != NULL && entry->symndx == -1 && entry->d.h->root.dynindx != -1) entry->d.h->no_fn_stub = TRUE; return 1; } /* Follow indirect and warning hash entries so that each got entry points to the final symbol definition. P must point to a pointer to the hash table we're traversing. Since this traversal may modify the hash table, we set this pointer to NULL to indicate we've made a potentially-destructive change to the hash table, so the traversal must be restarted. */ static int mips_elf_resolve_final_got_entry (void **entryp, void *p) { struct mips_got_entry *entry = (struct mips_got_entry *)*entryp; htab_t got_entries = *(htab_t *)p; if (entry->abfd != NULL && entry->symndx == -1) { struct mips_elf_link_hash_entry *h = entry->d.h; while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; if (entry->d.h == h) return 1; entry->d.h = h; /* If we can't find this entry with the new bfd hash, re-insert it, and get the traversal restarted. */ if (! htab_find (got_entries, entry)) { htab_clear_slot (got_entries, entryp); entryp = htab_find_slot (got_entries, entry, INSERT); if (! *entryp) *entryp = entry; /* Abort the traversal, since the whole table may have moved, and leave it up to the parent to restart the process. */ *(htab_t *)p = NULL; return 0; } /* We might want to decrement the global_gotno count, but it's either too early or too late for that at this point. */ } return 1; } /* Turn indirect got entries in a got_entries table into their final locations. */ static void mips_elf_resolve_final_got_entries (struct mips_got_info *g) { htab_t got_entries; do { got_entries = g->got_entries; htab_traverse (got_entries, mips_elf_resolve_final_got_entry, &got_entries); } while (got_entries == NULL); } /* Return the offset of an input bfd IBFD's GOT from the beginning of the primary GOT. */ static bfd_vma mips_elf_adjust_gp (bfd *abfd, struct mips_got_info *g, bfd *ibfd) { if (g->bfd2got == NULL) return 0; g = mips_elf_got_for_ibfd (g, ibfd); if (! g) return 0; BFD_ASSERT (g->next); g = g->next; return (g->local_gotno + g->global_gotno + g->tls_gotno) * MIPS_ELF_GOT_SIZE (abfd); } /* Turn a single GOT that is too big for 16-bit addressing into a sequence of GOTs, each one 16-bit addressable. */ static bfd_boolean mips_elf_multi_got (bfd *abfd, struct bfd_link_info *info, struct mips_got_info *g, asection *got, bfd_size_type pages) { struct mips_elf_got_per_bfd_arg got_per_bfd_arg; struct mips_elf_set_global_got_offset_arg set_got_offset_arg; struct mips_got_info *gg; unsigned int assign; g->bfd2got = htab_try_create (1, mips_elf_bfd2got_entry_hash, mips_elf_bfd2got_entry_eq, NULL); if (g->bfd2got == NULL) return FALSE; got_per_bfd_arg.bfd2got = g->bfd2got; got_per_bfd_arg.obfd = abfd; got_per_bfd_arg.info = info; /* Count how many GOT entries each input bfd requires, creating a map from bfd to got info while at that. */ htab_traverse (g->got_entries, mips_elf_make_got_per_bfd, &got_per_bfd_arg); if (got_per_bfd_arg.obfd == NULL) return FALSE; got_per_bfd_arg.current = NULL; got_per_bfd_arg.primary = NULL; /* Taking out PAGES entries is a worst-case estimate. We could compute the maximum number of pages that each separate input bfd uses, but it's probably not worth it. */ got_per_bfd_arg.max_count = ((MIPS_ELF_GOT_MAX_SIZE (abfd) / MIPS_ELF_GOT_SIZE (abfd)) - MIPS_RESERVED_GOTNO - pages); /* The number of globals that will be included in the primary GOT. See the calls to mips_elf_set_global_got_offset below for more information. */ got_per_bfd_arg.global_count = g->global_gotno; /* Try to merge the GOTs of input bfds together, as long as they don't seem to exceed the maximum GOT size, choosing one of them to be the primary GOT. */ htab_traverse (g->bfd2got, mips_elf_merge_gots, &got_per_bfd_arg); if (got_per_bfd_arg.obfd == NULL) return FALSE; /* If we do not find any suitable primary GOT, create an empty one. */ if (got_per_bfd_arg.primary == NULL) { g->next = (struct mips_got_info *) bfd_alloc (abfd, sizeof (struct mips_got_info)); if (g->next == NULL) return FALSE; g->next->global_gotsym = NULL; g->next->global_gotno = 0; g->next->local_gotno = 0; g->next->tls_gotno = 0; g->next->assigned_gotno = 0; g->next->tls_assigned_gotno = 0; g->next->tls_ldm_offset = MINUS_ONE; g->next->got_entries = htab_try_create (1, mips_elf_multi_got_entry_hash, mips_elf_multi_got_entry_eq, NULL); if (g->next->got_entries == NULL) return FALSE; g->next->bfd2got = NULL; } else g->next = got_per_bfd_arg.primary; g->next->next = got_per_bfd_arg.current; /* GG is now the master GOT, and G is the primary GOT. */ gg = g; g = g->next; /* Map the output bfd to the primary got. That's what we're going to use for bfds that use GOT16 or GOT_PAGE relocations that we didn't mark in check_relocs, and we want a quick way to find it. We can't just use gg->next because we're going to reverse the list. */ { struct mips_elf_bfd2got_hash *bfdgot; void **bfdgotp; bfdgot = (struct mips_elf_bfd2got_hash *)bfd_alloc (abfd, sizeof (struct mips_elf_bfd2got_hash)); if (bfdgot == NULL) return FALSE; bfdgot->bfd = abfd; bfdgot->g = g; bfdgotp = htab_find_slot (gg->bfd2got, bfdgot, INSERT); BFD_ASSERT (*bfdgotp == NULL); *bfdgotp = bfdgot; } /* The IRIX dynamic linker requires every symbol that is referenced in a dynamic relocation to be present in the primary GOT, so arrange for them to appear after those that are actually referenced. GNU/Linux could very well do without it, but it would slow down the dynamic linker, since it would have to resolve every dynamic symbol referenced in other GOTs more than once, without help from the cache. Also, knowing that every external symbol has a GOT helps speed up the resolution of local symbols too, so GNU/Linux follows IRIX's practice. The number 2 is used by mips_elf_sort_hash_table_f to count global GOT symbols that are unreferenced in the primary GOT, with an initial dynamic index computed from gg->assigned_gotno, where the number of unreferenced global entries in the primary GOT is preserved. */ if (1) { gg->assigned_gotno = gg->global_gotno - g->global_gotno; g->global_gotno = gg->global_gotno; set_got_offset_arg.value = 2; } else { /* This could be used for dynamic linkers that don't optimize symbol resolution while applying relocations so as to use primary GOT entries or assuming the symbol is locally-defined. With this code, we assign lower dynamic indices to global symbols that are not referenced in the primary GOT, so that their entries can be omitted. */ gg->assigned_gotno = 0; set_got_offset_arg.value = -1; } /* Reorder dynamic symbols as described above (which behavior depends on the setting of VALUE). */ set_got_offset_arg.g = NULL; htab_traverse (gg->got_entries, mips_elf_set_global_got_offset, &set_got_offset_arg); set_got_offset_arg.value = 1; htab_traverse (g->got_entries, mips_elf_set_global_got_offset, &set_got_offset_arg); if (! mips_elf_sort_hash_table (info, 1)) return FALSE; /* Now go through the GOTs assigning them offset ranges. [assigned_gotno, local_gotno[ will be set to the range of local entries in each GOT. We can then compute the end of a GOT by adding local_gotno to global_gotno. We reverse the list and make it circular since then we'll be able to quickly compute the beginning of a GOT, by computing the end of its predecessor. To avoid special cases for the primary GOT, while still preserving assertions that are valid for both single- and multi-got links, we arrange for the main got struct to have the right number of global entries, but set its local_gotno such that the initial offset of the primary GOT is zero. Remember that the primary GOT will become the last item in the circular linked list, so it points back to the master GOT. */ gg->local_gotno = -g->global_gotno; gg->global_gotno = g->global_gotno; gg->tls_gotno = 0; assign = 0; gg->next = gg; do { struct mips_got_info *gn; assign += MIPS_RESERVED_GOTNO; g->assigned_gotno = assign; g->local_gotno += assign + pages; assign = g->local_gotno + g->global_gotno + g->tls_gotno; /* Set up any TLS entries. We always place the TLS entries after all non-TLS entries. */ g->tls_assigned_gotno = g->local_gotno + g->global_gotno; htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g); /* Take g out of the direct list, and push it onto the reversed list that gg points to. */ gn = g->next; g->next = gg->next; gg->next = g; g = gn; /* Mark global symbols in every non-primary GOT as ineligible for stubs. */ if (g) htab_traverse (g->got_entries, mips_elf_set_no_stub, NULL); } while (g); got->size = (gg->next->local_gotno + gg->next->global_gotno + gg->next->tls_gotno) * MIPS_ELF_GOT_SIZE (abfd); return TRUE; } /* Returns the first relocation of type r_type found, beginning with RELOCATION. RELEND is one-past-the-end of the relocation table. */ static const Elf_Internal_Rela * mips_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type, const Elf_Internal_Rela *relocation, const Elf_Internal_Rela *relend) { while (relocation < relend) { if (ELF_R_TYPE (abfd, relocation->r_info) == r_type) return relocation; ++relocation; } /* We didn't find it. */ bfd_set_error (bfd_error_bad_value); return NULL; } /* Return whether a relocation is against a local symbol. */ static bfd_boolean mips_elf_local_relocation_p (bfd *input_bfd, const Elf_Internal_Rela *relocation, asection **local_sections, bfd_boolean check_forced) { unsigned long r_symndx; Elf_Internal_Shdr *symtab_hdr; struct mips_elf_link_hash_entry *h; size_t extsymoff; r_symndx = ELF_R_SYM (input_bfd, relocation->r_info); symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info; if (r_symndx < extsymoff) return TRUE; if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL) return TRUE; if (check_forced) { /* Look up the hash table to check whether the symbol was forced local. */ h = (struct mips_elf_link_hash_entry *) elf_sym_hashes (input_bfd) [r_symndx - extsymoff]; /* Find the real hash-table entry for this symbol. */ while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; if (h->root.forced_local) return TRUE; } return FALSE; } /* Sign-extend VALUE, which has the indicated number of BITS. */ bfd_vma _bfd_mips_elf_sign_extend (bfd_vma value, int bits) { if (value & ((bfd_vma) 1 << (bits - 1))) /* VALUE is negative. */ value |= ((bfd_vma) - 1) << bits; return value; } /* Return non-zero if the indicated VALUE has overflowed the maximum range expressible by a signed number with the indicated number of BITS. */ static bfd_boolean mips_elf_overflow_p (bfd_vma value, int bits) { bfd_signed_vma svalue = (bfd_signed_vma) value; if (svalue > (1 << (bits - 1)) - 1) /* The value is too big. */ return TRUE; else if (svalue < -(1 << (bits - 1))) /* The value is too small. */ return TRUE; /* All is well. */ return FALSE; } /* Calculate the %high function. */ static bfd_vma mips_elf_high (bfd_vma value) { return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff; } /* Calculate the %higher function. */ static bfd_vma mips_elf_higher (bfd_vma value ATTRIBUTE_UNUSED) { #ifdef BFD64 return ((value + (bfd_vma) 0x80008000) >> 32) & 0xffff; #else abort (); return MINUS_ONE; #endif } /* Calculate the %highest function. */ static bfd_vma mips_elf_highest (bfd_vma value ATTRIBUTE_UNUSED) { #ifdef BFD64 return ((value + (((bfd_vma) 0x8000 << 32) | 0x80008000)) >> 48) & 0xffff; #else abort (); return MINUS_ONE; #endif } /* Create the .compact_rel section. */ static bfd_boolean mips_elf_create_compact_rel_section (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED) { flagword flags; register asection *s; if (bfd_get_section_by_name (abfd, ".compact_rel") == NULL) { flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY); s = bfd_make_section_with_flags (abfd, ".compact_rel", flags); if (s == NULL || ! bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd))) return FALSE; s->size = sizeof (Elf32_External_compact_rel); } return TRUE; } /* Create the .got section to hold the global offset table. */ static bfd_boolean mips_elf_create_got_section (bfd *abfd, struct bfd_link_info *info, bfd_boolean maybe_exclude) { flagword flags; register asection *s; struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; struct mips_got_info *g; bfd_size_type amt; /* This function may be called more than once. */ s = mips_elf_got_section (abfd, TRUE); if (s) { if (! maybe_exclude) s->flags &= ~SEC_EXCLUDE; return TRUE; } flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED); if (maybe_exclude) flags |= SEC_EXCLUDE; /* We have to use an alignment of 2**4 here because this is hardcoded in the function stub generation and in the linker script. */ s = bfd_make_section_with_flags (abfd, ".got", flags); if (s == NULL || ! bfd_set_section_alignment (abfd, s, 4)) return FALSE; /* Define the symbol _GLOBAL_OFFSET_TABLE_. We don't do this in the linker script because we don't want to define the symbol if we are not creating a global offset table. */ bh = NULL; if (! (_bfd_generic_link_add_one_symbol (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s, 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_OBJECT; if (info->shared && ! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; amt = sizeof (struct mips_got_info); g = bfd_alloc (abfd, amt); if (g == NULL) return FALSE; g->global_gotsym = NULL; g->global_gotno = 0; g->tls_gotno = 0; g->local_gotno = MIPS_RESERVED_GOTNO; g->assigned_gotno = MIPS_RESERVED_GOTNO; g->bfd2got = NULL; g->next = NULL; g->tls_ldm_offset = MINUS_ONE; g->got_entries = htab_try_create (1, mips_elf_got_entry_hash, mips_elf_got_entry_eq, NULL); if (g->got_entries == NULL) return FALSE; mips_elf_section_data (s)->u.got_info = g; mips_elf_section_data (s)->elf.this_hdr.sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL; return TRUE; } /* Calculate the value produced by the RELOCATION (which comes from the INPUT_BFD). The ADDEND is the addend to use for this RELOCATION; RELOCATION->R_ADDEND is ignored. The result of the relocation calculation is stored in VALUEP. REQUIRE_JALXP indicates whether or not the opcode used with this relocation must be JALX. This function returns bfd_reloc_continue if the caller need take no further action regarding this relocation, bfd_reloc_notsupported if something goes dramatically wrong, bfd_reloc_overflow if an overflow occurs, and bfd_reloc_ok to indicate success. */ static bfd_reloc_status_type mips_elf_calculate_relocation (bfd *abfd, bfd *input_bfd, asection *input_section, struct bfd_link_info *info, const Elf_Internal_Rela *relocation, bfd_vma addend, reloc_howto_type *howto, Elf_Internal_Sym *local_syms, asection **local_sections, bfd_vma *valuep, const char **namep, bfd_boolean *require_jalxp, bfd_boolean save_addend) { /* The eventual value we will return. */ bfd_vma value; /* The address of the symbol against which the relocation is occurring. */ bfd_vma symbol = 0; /* The final GP value to be used for the relocatable, executable, or shared object file being produced. */ bfd_vma gp = MINUS_ONE; /* The place (section offset or address) of the storage unit being relocated. */ bfd_vma p; /* The value of GP used to create the relocatable object. */ bfd_vma gp0 = MINUS_ONE; /* The offset into the global offset table at which the address of the relocation entry symbol, adjusted by the addend, resides during execution. */ bfd_vma g = MINUS_ONE; /* The section in which the symbol referenced by the relocation is located. */ asection *sec = NULL; struct mips_elf_link_hash_entry *h = NULL; /* TRUE if the symbol referred to by this relocation is a local symbol. */ bfd_boolean local_p, was_local_p; /* TRUE if the symbol referred to by this relocation is "_gp_disp". */ bfd_boolean gp_disp_p = FALSE; /* TRUE if the symbol referred to by this relocation is "__gnu_local_gp". */ bfd_boolean gnu_local_gp_p = FALSE; Elf_Internal_Shdr *symtab_hdr; size_t extsymoff; unsigned long r_symndx; int r_type; /* TRUE if overflow occurred during the calculation of the relocation value. */ bfd_boolean overflowed_p; /* TRUE if this relocation refers to a MIPS16 function. */ bfd_boolean target_is_16_bit_code_p = FALSE; /* Parse the relocation. */ r_symndx = ELF_R_SYM (input_bfd, relocation->r_info); r_type = ELF_R_TYPE (input_bfd, relocation->r_info); p = (input_section->output_section->vma + input_section->output_offset + relocation->r_offset); /* Assume that there will be no overflow. */ overflowed_p = FALSE; /* Figure out whether or not the symbol is local, and get the offset used in the array of hash table entries. */ symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; local_p = mips_elf_local_relocation_p (input_bfd, relocation, local_sections, FALSE); was_local_p = local_p; if (! elf_bad_symtab (input_bfd)) extsymoff = symtab_hdr->sh_info; else { /* The symbol table does not follow the rule that local symbols must come before globals. */ extsymoff = 0; } /* Figure out the value of the symbol. */ if (local_p) { Elf_Internal_Sym *sym; sym = local_syms + r_symndx; sec = local_sections[r_symndx]; symbol = sec->output_section->vma + sec->output_offset; if (ELF_ST_TYPE (sym->st_info) != STT_SECTION || (sec->flags & SEC_MERGE)) symbol += sym->st_value; if ((sec->flags & SEC_MERGE) && ELF_ST_TYPE (sym->st_info) == STT_SECTION) { addend = _bfd_elf_rel_local_sym (abfd, sym, &sec, addend); addend -= symbol; addend += sec->output_section->vma + sec->output_offset; } /* MIPS16 text labels should be treated as odd. */ if (sym->st_other == STO_MIPS16) ++symbol; /* Record the name of this symbol, for our caller. */ *namep = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link, sym->st_name); if (*namep == '\0') *namep = bfd_section_name (input_bfd, sec); target_is_16_bit_code_p = (sym->st_other == STO_MIPS16); } else { /* ??? Could we use RELOC_FOR_GLOBAL_SYMBOL here ? */ /* For global symbols we look up the symbol in the hash-table. */ h = ((struct mips_elf_link_hash_entry *) elf_sym_hashes (input_bfd) [r_symndx - extsymoff]); /* Find the real hash-table entry for this symbol. */ while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; /* Record the name of this symbol, for our caller. */ *namep = h->root.root.root.string; /* See if this is the special _gp_disp symbol. Note that such a symbol must always be a global symbol. */ if (strcmp (*namep, "_gp_disp") == 0 && ! NEWABI_P (input_bfd)) { /* Relocations against _gp_disp are permitted only with R_MIPS_HI16 and R_MIPS_LO16 relocations. */ if (r_type != R_MIPS_HI16 && r_type != R_MIPS_LO16 && r_type != R_MIPS16_HI16 && r_type != R_MIPS16_LO16) return bfd_reloc_notsupported; gp_disp_p = TRUE; } /* See if this is the special _gp symbol. Note that such a symbol must always be a global symbol. */ else if (strcmp (*namep, "__gnu_local_gp") == 0) gnu_local_gp_p = TRUE; /* If this symbol is defined, calculate its address. Note that _gp_disp is a magic symbol, always implicitly defined by the linker, so it's inappropriate to check to see whether or not its defined. */ else if ((h->root.root.type == bfd_link_hash_defined || h->root.root.type == bfd_link_hash_defweak) && h->root.root.u.def.section) { sec = h->root.root.u.def.section; if (sec->output_section) symbol = (h->root.root.u.def.value + sec->output_section->vma + sec->output_offset); else symbol = h->root.root.u.def.value; } else if (h->root.root.type == bfd_link_hash_undefweak) /* We allow relocations against undefined weak symbols, giving it the value zero, so that you can undefined weak functions and check to see if they exist by looking at their addresses. */ symbol = 0; else if (info->unresolved_syms_in_objects == RM_IGNORE && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT) symbol = 0; else if (strcmp (*namep, SGI_COMPAT (input_bfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING") == 0) { /* If this is a dynamic link, we should have created a _DYNAMIC_LINK symbol or _DYNAMIC_LINKING(for normal mips) symbol in in _bfd_mips_elf_create_dynamic_sections. Otherwise, we should define the symbol with a value of 0. FIXME: It should probably get into the symbol table somehow as well. */ BFD_ASSERT (! info->shared); BFD_ASSERT (bfd_get_section_by_name (abfd, ".dynamic") == NULL); symbol = 0; } else if (ELF_MIPS_IS_OPTIONAL (h->root.other)) { /* This is an optional symbol - an Irix specific extension to the ELF spec. Ignore it for now. XXX - FIXME - there is more to the spec for OPTIONAL symbols than simply ignoring them, but we do not handle this for now. For information see the "64-bit ELF Object File Specification" which is available from here: http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf */ symbol = 0; } else { if (! ((*info->callbacks->undefined_symbol) (info, h->root.root.root.string, input_bfd, input_section, relocation->r_offset, (info->unresolved_syms_in_objects == RM_GENERATE_ERROR) || ELF_ST_VISIBILITY (h->root.other)))) return bfd_reloc_undefined; symbol = 0; } target_is_16_bit_code_p = (h->root.other == STO_MIPS16); } /* If this is a 32- or 64-bit call to a 16-bit function with a stub, we need to redirect the call to the stub, unless we're already *in* a stub. */ if (r_type != R_MIPS16_26 && !info->relocatable && ((h != NULL && h->fn_stub != NULL) || (local_p && elf_tdata (input_bfd)->local_stubs != NULL && elf_tdata (input_bfd)->local_stubs[r_symndx] != NULL)) && !mips_elf_stub_section_p (input_bfd, input_section)) { /* This is a 32- or 64-bit call to a 16-bit function. We should have already noticed that we were going to need the stub. */ if (local_p) sec = elf_tdata (input_bfd)->local_stubs[r_symndx]; else { BFD_ASSERT (h->need_fn_stub); sec = h->fn_stub; } symbol = sec->output_section->vma + sec->output_offset; } /* If this is a 16-bit call to a 32- or 64-bit function with a stub, we need to redirect the call to the stub. */ else if (r_type == R_MIPS16_26 && !info->relocatable && h != NULL && (h->call_stub != NULL || h->call_fp_stub != NULL) && !target_is_16_bit_code_p) { /* If both call_stub and call_fp_stub are defined, we can figure out which one to use by seeing which one appears in the input file. */ if (h->call_stub != NULL && h->call_fp_stub != NULL) { asection *o; sec = NULL; for (o = input_bfd->sections; o != NULL; o = o->next) { if (strncmp (bfd_get_section_name (input_bfd, o), CALL_FP_STUB, sizeof CALL_FP_STUB - 1) == 0) { sec = h->call_fp_stub; break; } } if (sec == NULL) sec = h->call_stub; } else if (h->call_stub != NULL) sec = h->call_stub; else sec = h->call_fp_stub; BFD_ASSERT (sec->size > 0); symbol = sec->output_section->vma + sec->output_offset; } /* Calls from 16-bit code to 32-bit code and vice versa require the special jalx instruction. */ *require_jalxp = (!info->relocatable && (((r_type == R_MIPS16_26) && !target_is_16_bit_code_p) || ((r_type == R_MIPS_26) && target_is_16_bit_code_p))); local_p = mips_elf_local_relocation_p (input_bfd, relocation, local_sections, TRUE); /* If we haven't already determined the GOT offset, or the GP value, and we're going to need it, get it now. */ switch (r_type) { case R_MIPS_GOT_PAGE: case R_MIPS_GOT_OFST: /* We need to decay to GOT_DISP/addend if the symbol doesn't bind locally. */ local_p = local_p || _bfd_elf_symbol_refs_local_p (&h->root, info, 1); if (local_p || r_type == R_MIPS_GOT_OFST) break; /* Fall through. */ case R_MIPS_CALL16: case R_MIPS_GOT16: case R_MIPS_GOT_DISP: case R_MIPS_GOT_HI16: case R_MIPS_CALL_HI16: case R_MIPS_GOT_LO16: case R_MIPS_CALL_LO16: case R_MIPS_TLS_GD: case R_MIPS_TLS_GOTTPREL: case R_MIPS_TLS_LDM: /* Find the index into the GOT where this value is located. */ if (r_type == R_MIPS_TLS_LDM) { g = mips_elf_local_got_index (abfd, input_bfd, info, 0, 0, NULL, r_type); if (g == MINUS_ONE) return bfd_reloc_outofrange; } else if (!local_p) { /* GOT_PAGE may take a non-zero addend, that is ignored in a GOT_PAGE relocation that decays to GOT_DISP because the symbol turns out to be global. The addend is then added as GOT_OFST. */ BFD_ASSERT (addend == 0 || r_type == R_MIPS_GOT_PAGE); g = mips_elf_global_got_index (elf_hash_table (info)->dynobj, input_bfd, (struct elf_link_hash_entry *) h, r_type, info); if (h->tls_type == GOT_NORMAL && (! elf_hash_table(info)->dynamic_sections_created || (info->shared && (info->symbolic || h->root.forced_local) && h->root.def_regular))) { /* This is a static link or a -Bsymbolic link. The symbol is defined locally, or was forced to be local. We must initialize this entry in the GOT. */ bfd *tmpbfd = elf_hash_table (info)->dynobj; asection *sgot = mips_elf_got_section (tmpbfd, FALSE); MIPS_ELF_PUT_WORD (tmpbfd, symbol, sgot->contents + g); } } else if (r_type == R_MIPS_GOT16 || r_type == R_MIPS_CALL16) /* There's no need to create a local GOT entry here; the calculation for a local GOT16 entry does not involve G. */ break; else { g = mips_elf_local_got_index (abfd, input_bfd, info, symbol + addend, r_symndx, h, r_type); if (g == MINUS_ONE) return bfd_reloc_outofrange; } /* Convert GOT indices to actual offsets. */ g = mips_elf_got_offset_from_index (elf_hash_table (info)->dynobj, abfd, input_bfd, g); break; case R_MIPS_HI16: case R_MIPS_LO16: case R_MIPS_GPREL16: case R_MIPS_GPREL32: case R_MIPS_LITERAL: case R_MIPS16_HI16: case R_MIPS16_LO16: case R_MIPS16_GPREL: gp0 = _bfd_get_gp_value (input_bfd); gp = _bfd_get_gp_value (abfd); if (elf_hash_table (info)->dynobj) gp += mips_elf_adjust_gp (abfd, mips_elf_got_info (elf_hash_table (info)->dynobj, NULL), input_bfd); break; default: break; } if (gnu_local_gp_p) symbol = gp; /* Figure out what kind of relocation is being performed. */ switch (r_type) { case R_MIPS_NONE: return bfd_reloc_continue; case R_MIPS_16: value = symbol + _bfd_mips_elf_sign_extend (addend, 16); overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_32: case R_MIPS_REL32: case R_MIPS_64: if ((info->shared || (elf_hash_table (info)->dynamic_sections_created && h != NULL && h->root.def_dynamic && !h->root.def_regular)) && r_symndx != 0 && (input_section->flags & SEC_ALLOC) != 0) { /* If we're creating a shared library, or this relocation is against a symbol in a shared library, then we can't know where the symbol will end up. So, we create a relocation record in the output, and leave the job up to the dynamic linker. */ value = addend; if (!mips_elf_create_dynamic_relocation (abfd, info, relocation, h, sec, symbol, &value, input_section)) return bfd_reloc_undefined; } else { if (r_type != R_MIPS_REL32) value = symbol + addend; else value = addend; } value &= howto->dst_mask; break; case R_MIPS_PC32: value = symbol + addend - p; value &= howto->dst_mask; break; case R_MIPS_GNU_REL16_S2: value = symbol + _bfd_mips_elf_sign_extend (addend, 18) - p; overflowed_p = mips_elf_overflow_p (value, 18); value = (value >> 2) & howto->dst_mask; break; case R_MIPS16_26: /* The calculation for R_MIPS16_26 is just the same as for an R_MIPS_26. It's only the storage of the relocated field into the output file that's different. That's handled in mips_elf_perform_relocation. So, we just fall through to the R_MIPS_26 case here. */ case R_MIPS_26: if (local_p) value = ((addend | ((p + 4) & 0xf0000000)) + symbol) >> 2; else { value = (_bfd_mips_elf_sign_extend (addend, 28) + symbol) >> 2; if (h->root.root.type != bfd_link_hash_undefweak) overflowed_p = (value >> 26) != ((p + 4) >> 28); } value &= howto->dst_mask; break; case R_MIPS_TLS_DTPREL_HI16: value = (mips_elf_high (addend + symbol - dtprel_base (info)) & howto->dst_mask); break; case R_MIPS_TLS_DTPREL_LO16: value = (symbol + addend - dtprel_base (info)) & howto->dst_mask; break; case R_MIPS_TLS_TPREL_HI16: value = (mips_elf_high (addend + symbol - tprel_base (info)) & howto->dst_mask); break; case R_MIPS_TLS_TPREL_LO16: value = (symbol + addend - tprel_base (info)) & howto->dst_mask; break; case R_MIPS_HI16: case R_MIPS16_HI16: if (!gp_disp_p) { value = mips_elf_high (addend + symbol); value &= howto->dst_mask; } else { /* For MIPS16 ABI code we generate this sequence 0: li $v0,%hi(_gp_disp) 4: addiupc $v1,%lo(_gp_disp) 8: sll $v0,16 12: addu $v0,$v1 14: move $gp,$v0 So the offsets of hi and lo relocs are the same, but the $pc is four higher than $t9 would be, so reduce both reloc addends by 4. */ if (r_type == R_MIPS16_HI16) value = mips_elf_high (addend + gp - p - 4); else value = mips_elf_high (addend + gp - p); overflowed_p = mips_elf_overflow_p (value, 16); } break; case R_MIPS_LO16: case R_MIPS16_LO16: if (!gp_disp_p) value = (symbol + addend) & howto->dst_mask; else { /* See the comment for R_MIPS16_HI16 above for the reason for this conditional. */ if (r_type == R_MIPS16_LO16) value = addend + gp - p; else value = addend + gp - p + 4; /* The MIPS ABI requires checking the R_MIPS_LO16 relocation for overflow. But, on, say, IRIX5, relocations against _gp_disp are normally generated from the .cpload pseudo-op. It generates code that normally looks like this: lui $gp,%hi(_gp_disp) addiu $gp,$gp,%lo(_gp_disp) addu $gp,$gp,$t9 Here $t9 holds the address of the function being called, as required by the MIPS ELF ABI. The R_MIPS_LO16 relocation can easily overflow in this situation, but the R_MIPS_HI16 relocation will handle the overflow. Therefore, we consider this a bug in the MIPS ABI, and do not check for overflow here. */ } break; case R_MIPS_LITERAL: /* Because we don't merge literal sections, we can handle this just like R_MIPS_GPREL16. In the long run, we should merge shared literals, and then we will need to additional work here. */ /* Fall through. */ case R_MIPS16_GPREL: /* The R_MIPS16_GPREL performs the same calculation as R_MIPS_GPREL16, but stores the relocated bits in a different order. We don't need to do anything special here; the differences are handled in mips_elf_perform_relocation. */ case R_MIPS_GPREL16: /* Only sign-extend the addend if it was extracted from the instruction. If the addend was separate, leave it alone, otherwise we may lose significant bits. */ if (howto->partial_inplace) addend = _bfd_mips_elf_sign_extend (addend, 16); value = symbol + addend - gp; /* If the symbol was local, any earlier relocatable links will have adjusted its addend with the gp offset, so compensate for that now. Don't do it for symbols forced local in this link, though, since they won't have had the gp offset applied to them before. */ if (was_local_p) value += gp0; overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_GOT16: case R_MIPS_CALL16: if (local_p) { bfd_boolean forced; /* The special case is when the symbol is forced to be local. We need the full address in the GOT since no R_MIPS_LO16 relocation follows. */ forced = ! mips_elf_local_relocation_p (input_bfd, relocation, local_sections, FALSE); value = mips_elf_got16_entry (abfd, input_bfd, info, symbol + addend, forced); if (value == MINUS_ONE) return bfd_reloc_outofrange; value = mips_elf_got_offset_from_index (elf_hash_table (info)->dynobj, abfd, input_bfd, value); overflowed_p = mips_elf_overflow_p (value, 16); break; } /* Fall through. */ case R_MIPS_TLS_GD: case R_MIPS_TLS_GOTTPREL: case R_MIPS_TLS_LDM: case R_MIPS_GOT_DISP: got_disp: value = g; overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_GPREL32: value = (addend + symbol + gp0 - gp); if (!save_addend) value &= howto->dst_mask; break; case R_MIPS_PC16: value = _bfd_mips_elf_sign_extend (addend, 16) + symbol - p; overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_GOT_HI16: case R_MIPS_CALL_HI16: /* We're allowed to handle these two relocations identically. The dynamic linker is allowed to handle the CALL relocations differently by creating a lazy evaluation stub. */ value = g; value = mips_elf_high (value); value &= howto->dst_mask; break; case R_MIPS_GOT_LO16: case R_MIPS_CALL_LO16: value = g & howto->dst_mask; break; case R_MIPS_GOT_PAGE: /* GOT_PAGE relocations that reference non-local symbols decay to GOT_DISP. The corresponding GOT_OFST relocation decays to 0. */ if (! local_p) goto got_disp; value = mips_elf_got_page (abfd, input_bfd, info, symbol + addend, NULL); if (value == MINUS_ONE) return bfd_reloc_outofrange; value = mips_elf_got_offset_from_index (elf_hash_table (info)->dynobj, abfd, input_bfd, value); overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_GOT_OFST: if (local_p) mips_elf_got_page (abfd, input_bfd, info, symbol + addend, &value); else value = addend; overflowed_p = mips_elf_overflow_p (value, 16); break; case R_MIPS_SUB: value = symbol - addend; value &= howto->dst_mask; break; case R_MIPS_HIGHER: value = mips_elf_higher (addend + symbol); value &= howto->dst_mask; break; case R_MIPS_HIGHEST: value = mips_elf_highest (addend + symbol); value &= howto->dst_mask; break; case R_MIPS_SCN_DISP: value = symbol + addend - sec->output_offset; value &= howto->dst_mask; break; case R_MIPS_JALR: /* This relocation is only a hint. In some cases, we optimize it into a bal instruction. But we don't try to optimize branches to the PLT; that will wind up wasting time. */ if (h != NULL && h->root.plt.offset != (bfd_vma) -1) return bfd_reloc_continue; value = symbol + addend; break; case R_MIPS_PJUMP: case R_MIPS_GNU_VTINHERIT: case R_MIPS_GNU_VTENTRY: /* We don't do anything with these at present. */ return bfd_reloc_continue; default: /* An unrecognized relocation type. */ return bfd_reloc_notsupported; } /* Store the VALUE for our caller. */ *valuep = value; return overflowed_p ? bfd_reloc_overflow : bfd_reloc_ok; } /* Obtain the field relocated by RELOCATION. */ static bfd_vma mips_elf_obtain_contents (reloc_howto_type *howto, const Elf_Internal_Rela *relocation, bfd *input_bfd, bfd_byte *contents) { bfd_vma x; bfd_byte *location = contents + relocation->r_offset; /* Obtain the bytes. */ x = bfd_get ((8 * bfd_get_reloc_size (howto)), input_bfd, location); return x; } /* It has been determined that the result of the RELOCATION is the VALUE. Use HOWTO to place VALUE into the output file at the appropriate position. The SECTION is the section to which the relocation applies. If REQUIRE_JALX is TRUE, then the opcode used for the relocation must be either JAL or JALX, and it is unconditionally converted to JALX. Returns FALSE if anything goes wrong. */ static bfd_boolean mips_elf_perform_relocation (struct bfd_link_info *info, reloc_howto_type *howto, const Elf_Internal_Rela *relocation, bfd_vma value, bfd *input_bfd, asection *input_section, bfd_byte *contents, bfd_boolean require_jalx) { bfd_vma x; bfd_byte *location; int r_type = ELF_R_TYPE (input_bfd, relocation->r_info); /* Figure out where the relocation is occurring. */ location = contents + relocation->r_offset; _bfd_mips16_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location); /* Obtain the current value. */ x = mips_elf_obtain_contents (howto, relocation, input_bfd, contents); /* Clear the field we are setting. */ x &= ~howto->dst_mask; /* Set the field. */ x |= (value & howto->dst_mask); /* If required, turn JAL into JALX. */ if (require_jalx) { bfd_boolean ok; bfd_vma opcode = x >> 26; bfd_vma jalx_opcode; /* Check to see if the opcode is already JAL or JALX. */ if (r_type == R_MIPS16_26) { ok = ((opcode == 0x6) || (opcode == 0x7)); jalx_opcode = 0x7; } else { ok = ((opcode == 0x3) || (opcode == 0x1d)); jalx_opcode = 0x1d; } /* If the opcode is not JAL or JALX, there's a problem. */ if (!ok) { (*_bfd_error_handler) (_("%B: %A+0x%lx: jump to stub routine which is not jal"), input_bfd, input_section, (unsigned long) relocation->r_offset); bfd_set_error (bfd_error_bad_value); return FALSE; } /* Make this the JALX opcode. */ x = (x & ~(0x3f << 26)) | (jalx_opcode << 26); } /* On the RM9000, bal is faster than jal, because bal uses branch prediction hardware. If we are linking for the RM9000, and we see jal, and bal fits, use it instead. Note that this transformation should be safe for all architectures. */ if (bfd_get_mach (input_bfd) == bfd_mach_mips9000 && !info->relocatable && !require_jalx && ((r_type == R_MIPS_26 && (x >> 26) == 0x3) /* jal addr */ || (r_type == R_MIPS_JALR && x == 0x0320f809))) /* jalr t9 */ { bfd_vma addr; bfd_vma dest; bfd_signed_vma off; addr = (input_section->output_section->vma + input_section->output_offset + relocation->r_offset + 4); if (r_type == R_MIPS_26) dest = (value << 2) | ((addr >> 28) << 28); else dest = value; off = dest - addr; if (off <= 0x1ffff && off >= -0x20000) x = 0x04110000 | (((bfd_vma) off >> 2) & 0xffff); /* bal addr */ } /* Put the value into the output. */ bfd_put (8 * bfd_get_reloc_size (howto), input_bfd, x, location); _bfd_mips16_elf_reloc_shuffle(input_bfd, r_type, !info->relocatable, location); return TRUE; } /* Returns TRUE if SECTION is a MIPS16 stub section. */ static bfd_boolean mips_elf_stub_section_p (bfd *abfd ATTRIBUTE_UNUSED, asection *section) { const char *name = bfd_get_section_name (abfd, section); return (strncmp (name, FN_STUB, sizeof FN_STUB - 1) == 0 || strncmp (name, CALL_STUB, sizeof CALL_STUB - 1) == 0 || strncmp (name, CALL_FP_STUB, sizeof CALL_FP_STUB - 1) == 0); } /* Add room for N relocations to the .rel.dyn section in ABFD. */ static void mips_elf_allocate_dynamic_relocations (bfd *abfd, unsigned int n) { asection *s; s = mips_elf_rel_dyn_section (abfd, FALSE); BFD_ASSERT (s != NULL); if (s->size == 0) { /* Make room for a null element. */ s->size += MIPS_ELF_REL_SIZE (abfd); ++s->reloc_count; } s->size += n * MIPS_ELF_REL_SIZE (abfd); } /* Create a rel.dyn relocation for the dynamic linker to resolve. REL is the original relocation, which is now being transformed into a dynamic relocation. The ADDENDP is adjusted if necessary; the caller should store the result in place of the original addend. */ static bfd_boolean mips_elf_create_dynamic_relocation (bfd *output_bfd, struct bfd_link_info *info, const Elf_Internal_Rela *rel, struct mips_elf_link_hash_entry *h, asection *sec, bfd_vma symbol, bfd_vma *addendp, asection *input_section) { Elf_Internal_Rela outrel[3]; asection *sreloc; bfd *dynobj; int r_type; long indx; bfd_boolean defined_p; r_type = ELF_R_TYPE (output_bfd, rel->r_info); dynobj = elf_hash_table (info)->dynobj; sreloc = mips_elf_rel_dyn_section (dynobj, FALSE); BFD_ASSERT (sreloc != NULL); BFD_ASSERT (sreloc->contents != NULL); BFD_ASSERT (sreloc->reloc_count * MIPS_ELF_REL_SIZE (output_bfd) < sreloc->size); outrel[0].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset); outrel[1].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset); outrel[2].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset); if (outrel[0].r_offset == MINUS_ONE) /* The relocation field has been deleted. */ return TRUE; if (outrel[0].r_offset == MINUS_TWO) { /* The relocation field has been converted into a relative value of some sort. Functions like _bfd_elf_write_section_eh_frame expect the field to be fully relocated, so add in the symbol's value. */ *addendp += symbol; return TRUE; } /* We must now calculate the dynamic symbol table index to use in the relocation. */ if (h != NULL && (!h->root.def_regular || (info->shared && !info->symbolic && !h->root.forced_local))) { indx = h->root.dynindx; if (SGI_COMPAT (output_bfd)) defined_p = h->root.def_regular; else /* ??? glibc's ld.so just adds the final GOT entry to the relocation field. It therefore treats relocs against defined symbols in the same way as relocs against undefined symbols. */ defined_p = FALSE; } else { if (sec != NULL && bfd_is_abs_section (sec)) indx = 0; else if (sec == NULL || sec->owner == NULL) { bfd_set_error (bfd_error_bad_value); return FALSE; } else { indx = elf_section_data (sec->output_section)->dynindx; if (indx == 0) abort (); } /* Instead of generating a relocation using the section symbol, we may as well make it a fully relative relocation. We want to avoid generating relocations to local symbols because we used to generate them incorrectly, without adding the original symbol value, which is mandated by the ABI for section symbols. In order to give dynamic loaders and applications time to phase out the incorrect use, we refrain from emitting section-relative relocations. It's not like they're useful, after all. This should be a bit more efficient as well. */ /* ??? Although this behavior is compatible with glibc's ld.so, the ABI says that relocations against STN_UNDEF should have a symbol value of 0. Irix rld honors this, so relocations against STN_UNDEF have no effect. */ if (!SGI_COMPAT (output_bfd)) indx = 0; defined_p = TRUE; } /* If the relocation was previously an absolute relocation and this symbol will not be referred to by the relocation, we must adjust it by the value we give it in the dynamic symbol table. Otherwise leave the job up to the dynamic linker. */ if (defined_p && r_type != R_MIPS_REL32) *addendp += symbol; /* The relocation is always an REL32 relocation because we don't know where the shared library will wind up at load-time. */ outrel[0].r_info = ELF_R_INFO (output_bfd, (unsigned long) indx, R_MIPS_REL32); /* For strict adherence to the ABI specification, we should generate a R_MIPS_64 relocation record by itself before the _REL32/_64 record as well, such that the addend is read in as a 64-bit value (REL32 is a 32-bit relocation, after all). However, since none of the existing ELF64 MIPS dynamic loaders seems to care, we don't waste space with these artificial relocations. If this turns out to not be true, mips_elf_allocate_dynamic_relocation() should be tweaked so as to make room for a pair of dynamic relocations per invocation if ABI_64_P, and here we should generate an additional relocation record with R_MIPS_64 by itself for a NULL symbol before this relocation record. */ outrel[1].r_info = ELF_R_INFO (output_bfd, 0, ABI_64_P (output_bfd) ? R_MIPS_64 : R_MIPS_NONE); outrel[2].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_NONE); /* Adjust the output offset of the relocation to reference the correct location in the output file. */ outrel[0].r_offset += (input_section->output_section->vma + input_section->output_offset); outrel[1].r_offset += (input_section->output_section->vma + input_section->output_offset); outrel[2].r_offset += (input_section->output_section->vma + input_section->output_offset); /* Put the relocation back out. We have to use the special relocation outputter in the 64-bit case since the 64-bit relocation format is non-standard. */ if (ABI_64_P (output_bfd)) { (*get_elf_backend_data (output_bfd)->s->swap_reloc_out) (output_bfd, &outrel[0], (sreloc->contents + sreloc->reloc_count * sizeof (Elf64_Mips_External_Rel))); } else bfd_elf32_swap_reloc_out (output_bfd, &outrel[0], (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel))); /* We've now added another relocation. */ ++sreloc->reloc_count; /* Make sure the output section is writable. The dynamic linker will be writing to it. */ elf_section_data (input_section->output_section)->this_hdr.sh_flags |= SHF_WRITE; /* On IRIX5, make an entry of compact relocation info. */ if (IRIX_COMPAT (output_bfd) == ict_irix5) { asection *scpt = bfd_get_section_by_name (dynobj, ".compact_rel"); bfd_byte *cr; if (scpt) { Elf32_crinfo cptrel; mips_elf_set_cr_format (cptrel, CRF_MIPS_LONG); cptrel.vaddr = (rel->r_offset + input_section->output_section->vma + input_section->output_offset); if (r_type == R_MIPS_REL32) mips_elf_set_cr_type (cptrel, CRT_MIPS_REL32); else mips_elf_set_cr_type (cptrel, CRT_MIPS_WORD); mips_elf_set_cr_dist2to (cptrel, 0); cptrel.konst = *addendp; cr = (scpt->contents + sizeof (Elf32_External_compact_rel)); mips_elf_set_cr_relvaddr (cptrel, 0); bfd_elf32_swap_crinfo_out (output_bfd, &cptrel, ((Elf32_External_crinfo *) cr + scpt->reloc_count)); ++scpt->reloc_count; } } return TRUE; } /* Return the MACH for a MIPS e_flags value. */ unsigned long _bfd_elf_mips_mach (flagword flags) { switch (flags & EF_MIPS_MACH) { case E_MIPS_MACH_3900: return bfd_mach_mips3900; case E_MIPS_MACH_4010: return bfd_mach_mips4010; case E_MIPS_MACH_4100: return bfd_mach_mips4100; case E_MIPS_MACH_4111: return bfd_mach_mips4111; case E_MIPS_MACH_4120: return bfd_mach_mips4120; case E_MIPS_MACH_4650: return bfd_mach_mips4650; case E_MIPS_MACH_5400: return bfd_mach_mips5400; case E_MIPS_MACH_5500: return bfd_mach_mips5500; case E_MIPS_MACH_9000: return bfd_mach_mips9000; case E_MIPS_MACH_SB1: return bfd_mach_mips_sb1; default: switch (flags & EF_MIPS_ARCH) { default: case E_MIPS_ARCH_1: return bfd_mach_mips3000; break; case E_MIPS_ARCH_2: return bfd_mach_mips6000; break; case E_MIPS_ARCH_3: return bfd_mach_mips4000; break; case E_MIPS_ARCH_4: return bfd_mach_mips8000; break; case E_MIPS_ARCH_5: return bfd_mach_mips5; break; case E_MIPS_ARCH_32: return bfd_mach_mipsisa32; break; case E_MIPS_ARCH_64: return bfd_mach_mipsisa64; break; case E_MIPS_ARCH_32R2: return bfd_mach_mipsisa32r2; break; case E_MIPS_ARCH_64R2: return bfd_mach_mipsisa64r2; break; } } return 0; } /* Return printable name for ABI. */ static INLINE char * elf_mips_abi_name (bfd *abfd) { flagword flags; flags = elf_elfheader (abfd)->e_flags; switch (flags & EF_MIPS_ABI) { case 0: if (ABI_N32_P (abfd)) return "N32"; else if (ABI_64_P (abfd)) return "64"; else return "none"; case E_MIPS_ABI_O32: return "O32"; case E_MIPS_ABI_O64: return "O64"; case E_MIPS_ABI_EABI32: return "EABI32"; case E_MIPS_ABI_EABI64: return "EABI64"; default: return "unknown abi"; } } /* MIPS ELF uses two common sections. One is the usual one, and the other is for small objects. All the small objects are kept together, and then referenced via the gp pointer, which yields faster assembler code. This is what we use for the small common section. This approach is copied from ecoff.c. */ static asection mips_elf_scom_section; static asymbol mips_elf_scom_symbol; static asymbol *mips_elf_scom_symbol_ptr; /* MIPS ELF also uses an acommon section, which represents an allocated common symbol which may be overridden by a definition in a shared library. */ static asection mips_elf_acom_section; static asymbol mips_elf_acom_symbol; static asymbol *mips_elf_acom_symbol_ptr; /* Handle the special MIPS section numbers that a symbol may use. This is used for both the 32-bit and the 64-bit ABI. */ void _bfd_mips_elf_symbol_processing (bfd *abfd, asymbol *asym) { elf_symbol_type *elfsym; elfsym = (elf_symbol_type *) asym; switch (elfsym->internal_elf_sym.st_shndx) { case SHN_MIPS_ACOMMON: /* This section is used in a dynamically linked executable file. It is an allocated common section. The dynamic linker can either resolve these symbols to something in a shared library, or it can just leave them here. For our purposes, we can consider these symbols to be in a new section. */ if (mips_elf_acom_section.name == NULL) { /* Initialize the acommon section. */ mips_elf_acom_section.name = ".acommon"; mips_elf_acom_section.flags = SEC_ALLOC; mips_elf_acom_section.output_section = &mips_elf_acom_section; mips_elf_acom_section.symbol = &mips_elf_acom_symbol; mips_elf_acom_section.symbol_ptr_ptr = &mips_elf_acom_symbol_ptr; mips_elf_acom_symbol.name = ".acommon"; mips_elf_acom_symbol.flags = BSF_SECTION_SYM; mips_elf_acom_symbol.section = &mips_elf_acom_section; mips_elf_acom_symbol_ptr = &mips_elf_acom_symbol; } asym->section = &mips_elf_acom_section; break; case SHN_COMMON: /* Common symbols less than the GP size are automatically treated as SHN_MIPS_SCOMMON symbols on IRIX5. */ if (asym->value > elf_gp_size (abfd) || IRIX_COMPAT (abfd) == ict_irix6) break; /* Fall through. */ case SHN_MIPS_SCOMMON: if (mips_elf_scom_section.name == NULL) { /* Initialize the small common section. */ mips_elf_scom_section.name = ".scommon"; mips_elf_scom_section.flags = SEC_IS_COMMON; mips_elf_scom_section.output_section = &mips_elf_scom_section; mips_elf_scom_section.symbol = &mips_elf_scom_symbol; mips_elf_scom_section.symbol_ptr_ptr = &mips_elf_scom_symbol_ptr; mips_elf_scom_symbol.name = ".scommon"; mips_elf_scom_symbol.flags = BSF_SECTION_SYM; mips_elf_scom_symbol.section = &mips_elf_scom_section; mips_elf_scom_symbol_ptr = &mips_elf_scom_symbol; } asym->section = &mips_elf_scom_section; asym->value = elfsym->internal_elf_sym.st_size; break; case SHN_MIPS_SUNDEFINED: asym->section = bfd_und_section_ptr; break; case SHN_MIPS_TEXT: { asection *section = bfd_get_section_by_name (abfd, ".text"); BFD_ASSERT (SGI_COMPAT (abfd)); if (section != NULL) { asym->section = section; /* MIPS_TEXT is a bit special, the address is not an offset to the base of the .text section. So substract the section base address to make it an offset. */ asym->value -= section->vma; } } break; case SHN_MIPS_DATA: { asection *section = bfd_get_section_by_name (abfd, ".data"); BFD_ASSERT (SGI_COMPAT (abfd)); if (section != NULL) { asym->section = section; /* MIPS_DATA is a bit special, the address is not an offset to the base of the .data section. So substract the section base address to make it an offset. */ asym->value -= section->vma; } } break; } } /* Implement elf_backend_eh_frame_address_size. This differs from the default in the way it handles EABI64. EABI64 was originally specified as an LP64 ABI, and that is what -mabi=eabi normally gives on a 64-bit target. However, gcc has historically accepted the combination of -mabi=eabi and -mlong32, and this ILP32 variation has become semi-official over time. Both forms use elf32 and have pointer-sized FDE addresses. If an EABI object was generated by GCC 4.0 or above, it will have an empty .gcc_compiled_longXX section, where XX is the size of longs in bits. Unfortunately, ILP32 objects generated by earlier compilers have no special marking to distinguish them from LP64 objects. We don't want users of the official LP64 ABI to be punished for the existence of the ILP32 variant, but at the same time, we don't want to mistakenly interpret pre-4.0 ILP32 objects as being LP64 objects. We therefore take the following approach: - If ABFD contains a .gcc_compiled_longXX section, use it to determine the pointer size. - Otherwise check the type of the first relocation. Assume that the LP64 ABI is being used if the relocation is of type R_MIPS_64. - Otherwise punt. The second check is enough to detect LP64 objects generated by pre-4.0 compilers because, in the kind of output generated by those compilers, the first relocation will be associated with either a CIE personality routine or an FDE start address. Furthermore, the compilers never used a special (non-pointer) encoding for this ABI. Checking the relocation type should also be safe because there is no reason to use R_MIPS_64 in an ILP32 object. Pre-4.0 compilers never did so. */ unsigned int _bfd_mips_elf_eh_frame_address_size (bfd *abfd, asection *sec) { if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64) return 8; if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64) { bfd_boolean long32_p, long64_p; long32_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long32") != 0; long64_p = bfd_get_section_by_name (abfd, ".gcc_compiled_long64") != 0; if (long32_p && long64_p) return 0; if (long32_p) return 4; if (long64_p) return 8; if (sec->reloc_count > 0 && elf_section_data (sec)->relocs != NULL && (ELF32_R_TYPE (elf_section_data (sec)->relocs[0].r_info) == R_MIPS_64)) return 8; return 0; } return 4; } /* There appears to be a bug in the MIPSpro linker that causes GOT_DISP relocations against two unnamed section symbols to resolve to the same address. For example, if we have code like: lw $4,%got_disp(.data)($gp) lw $25,%got_disp(.text)($gp) jalr $25 then the linker will resolve both relocations to .data and the program will jump there rather than to .text. We can work around this problem by giving names to local section symbols. This is also what the MIPSpro tools do. */ bfd_boolean _bfd_mips_elf_name_local_section_symbols (bfd *abfd) { return SGI_COMPAT (abfd); } /* Work over a section just before writing it out. This routine is used by both the 32-bit and the 64-bit ABI. FIXME: We recognize sections that need the SHF_MIPS_GPREL flag by name; there has to be a better way. */ bfd_boolean _bfd_mips_elf_section_processing (bfd *abfd, Elf_Internal_Shdr *hdr) { if (hdr->sh_type == SHT_MIPS_REGINFO && hdr->sh_size > 0) { bfd_byte buf[4]; BFD_ASSERT (hdr->sh_size == sizeof (Elf32_External_RegInfo)); BFD_ASSERT (hdr->contents == NULL); if (bfd_seek (abfd, hdr->sh_offset + sizeof (Elf32_External_RegInfo) - 4, SEEK_SET) != 0) return FALSE; H_PUT_32 (abfd, elf_gp (abfd), buf); if (bfd_bwrite (buf, 4, abfd) != 4) return FALSE; } if (hdr->sh_type == SHT_MIPS_OPTIONS && hdr->bfd_section != NULL && mips_elf_section_data (hdr->bfd_section) != NULL && mips_elf_section_data (hdr->bfd_section)->u.tdata != NULL) { bfd_byte *contents, *l, *lend; /* We stored the section contents in the tdata field in the set_section_contents routine. We save the section contents so that we don't have to read them again. At this point we know that elf_gp is set, so we can look through the section contents to see if there is an ODK_REGINFO structure. */ contents = mips_elf_section_data (hdr->bfd_section)->u.tdata; l = contents; lend = contents + hdr->sh_size; while (l + sizeof (Elf_External_Options) <= lend) { Elf_Internal_Options intopt; bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l, &intopt); if (intopt.size < sizeof (Elf_External_Options)) { (*_bfd_error_handler) (_("%B: Warning: bad `%s' option size %u smaller than its header"), abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size); break; } if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO) { bfd_byte buf[8]; if (bfd_seek (abfd, (hdr->sh_offset + (l - contents) + sizeof (Elf_External_Options) + (sizeof (Elf64_External_RegInfo) - 8)), SEEK_SET) != 0) return FALSE; H_PUT_64 (abfd, elf_gp (abfd), buf); if (bfd_bwrite (buf, 8, abfd) != 8) return FALSE; } else if (intopt.kind == ODK_REGINFO) { bfd_byte buf[4]; if (bfd_seek (abfd, (hdr->sh_offset + (l - contents) + sizeof (Elf_External_Options) + (sizeof (Elf32_External_RegInfo) - 4)), SEEK_SET) != 0) return FALSE; H_PUT_32 (abfd, elf_gp (abfd), buf); if (bfd_bwrite (buf, 4, abfd) != 4) return FALSE; } l += intopt.size; } } if (hdr->bfd_section != NULL) { const char *name = bfd_get_section_name (abfd, hdr->bfd_section); if (strcmp (name, ".sdata") == 0 || strcmp (name, ".lit8") == 0 || strcmp (name, ".lit4") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL; hdr->sh_type = SHT_PROGBITS; } else if (strcmp (name, ".sbss") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL; hdr->sh_type = SHT_NOBITS; } else if (strcmp (name, ".srdata") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_MIPS_GPREL; hdr->sh_type = SHT_PROGBITS; } else if (strcmp (name, ".compact_rel") == 0) { hdr->sh_flags = 0; hdr->sh_type = SHT_PROGBITS; } else if (strcmp (name, ".rtproc") == 0) { if (hdr->sh_addralign != 0 && hdr->sh_entsize == 0) { unsigned int adjust; adjust = hdr->sh_size % hdr->sh_addralign; if (adjust != 0) hdr->sh_size += hdr->sh_addralign - adjust; } } } return TRUE; } /* Handle a MIPS specific section when reading an object file. This is called when elfcode.h finds a section with an unknown type. This routine supports both the 32-bit and 64-bit ELF ABI. FIXME: We need to handle the SHF_MIPS_GPREL flag, but I'm not sure how to. */ bfd_boolean _bfd_mips_elf_section_from_shdr (bfd *abfd, Elf_Internal_Shdr *hdr, const char *name, int shindex) { flagword flags = 0; /* There ought to be a place to keep ELF backend specific flags, but at the moment there isn't one. We just keep track of the sections by their name, instead. Fortunately, the ABI gives suggested names for all the MIPS specific sections, so we will probably get away with this. */ switch (hdr->sh_type) { case SHT_MIPS_LIBLIST: if (strcmp (name, ".liblist") != 0) return FALSE; break; case SHT_MIPS_MSYM: if (strcmp (name, ".msym") != 0) return FALSE; break; case SHT_MIPS_CONFLICT: if (strcmp (name, ".conflict") != 0) return FALSE; break; case SHT_MIPS_GPTAB: if (strncmp (name, ".gptab.", sizeof ".gptab." - 1) != 0) return FALSE; break; case SHT_MIPS_UCODE: if (strcmp (name, ".ucode") != 0) return FALSE; break; case SHT_MIPS_DEBUG: if (strcmp (name, ".mdebug") != 0) return FALSE; flags = SEC_DEBUGGING; break; case SHT_MIPS_REGINFO: if (strcmp (name, ".reginfo") != 0 || hdr->sh_size != sizeof (Elf32_External_RegInfo)) return FALSE; flags = (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_SAME_SIZE); break; case SHT_MIPS_IFACE: if (strcmp (name, ".MIPS.interfaces") != 0) return FALSE; break; case SHT_MIPS_CONTENT: if (strncmp (name, ".MIPS.content", sizeof ".MIPS.content" - 1) != 0) return FALSE; break; case SHT_MIPS_OPTIONS: if (!MIPS_ELF_OPTIONS_SECTION_NAME_P (name)) return FALSE; break; case SHT_MIPS_DWARF: if (strncmp (name, ".debug_", sizeof ".debug_" - 1) != 0) return FALSE; break; case SHT_MIPS_SYMBOL_LIB: if (strcmp (name, ".MIPS.symlib") != 0) return FALSE; break; case SHT_MIPS_EVENTS: if (strncmp (name, ".MIPS.events", sizeof ".MIPS.events" - 1) != 0 && strncmp (name, ".MIPS.post_rel", sizeof ".MIPS.post_rel" - 1) != 0) return FALSE; break; default: break; } if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex)) return FALSE; if (flags) { if (! bfd_set_section_flags (abfd, hdr->bfd_section, (bfd_get_section_flags (abfd, hdr->bfd_section) | flags))) return FALSE; } /* FIXME: We should record sh_info for a .gptab section. */ /* For a .reginfo section, set the gp value in the tdata information from the contents of this section. We need the gp value while processing relocs, so we just get it now. The .reginfo section is not used in the 64-bit MIPS ELF ABI. */ if (hdr->sh_type == SHT_MIPS_REGINFO) { Elf32_External_RegInfo ext; Elf32_RegInfo s; if (! bfd_get_section_contents (abfd, hdr->bfd_section, &ext, 0, sizeof ext)) return FALSE; bfd_mips_elf32_swap_reginfo_in (abfd, &ext, &s); elf_gp (abfd) = s.ri_gp_value; } /* For a SHT_MIPS_OPTIONS section, look for a ODK_REGINFO entry, and set the gp value based on what we find. We may see both SHT_MIPS_REGINFO and SHT_MIPS_OPTIONS/ODK_REGINFO; in that case, they should agree. */ if (hdr->sh_type == SHT_MIPS_OPTIONS) { bfd_byte *contents, *l, *lend; contents = bfd_malloc (hdr->sh_size); if (contents == NULL) return FALSE; if (! bfd_get_section_contents (abfd, hdr->bfd_section, contents, 0, hdr->sh_size)) { free (contents); return FALSE; } l = contents; lend = contents + hdr->sh_size; while (l + sizeof (Elf_External_Options) <= lend) { Elf_Internal_Options intopt; bfd_mips_elf_swap_options_in (abfd, (Elf_External_Options *) l, &intopt); if (intopt.size < sizeof (Elf_External_Options)) { (*_bfd_error_handler) (_("%B: Warning: bad `%s' option size %u smaller than its header"), abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd), intopt.size); break; } if (ABI_64_P (abfd) && intopt.kind == ODK_REGINFO) { Elf64_Internal_RegInfo intreg; bfd_mips_elf64_swap_reginfo_in (abfd, ((Elf64_External_RegInfo *) (l + sizeof (Elf_External_Options))), &intreg); elf_gp (abfd) = intreg.ri_gp_value; } else if (intopt.kind == ODK_REGINFO) { Elf32_RegInfo intreg; bfd_mips_elf32_swap_reginfo_in (abfd, ((Elf32_External_RegInfo *) (l + sizeof (Elf_External_Options))), &intreg); elf_gp (abfd) = intreg.ri_gp_value; } l += intopt.size; } free (contents); } return TRUE; } /* Set the correct type for a MIPS ELF section. We do this by the section name, which is a hack, but ought to work. This routine is used by both the 32-bit and the 64-bit ABI. */ bfd_boolean _bfd_mips_elf_fake_sections (bfd *abfd, Elf_Internal_Shdr *hdr, asection *sec) { register const char *name; unsigned int sh_type; name = bfd_get_section_name (abfd, sec); sh_type = hdr->sh_type; if (strcmp (name, ".liblist") == 0) { hdr->sh_type = SHT_MIPS_LIBLIST; hdr->sh_info = sec->size / sizeof (Elf32_Lib); /* The sh_link field is set in final_write_processing. */ } else if (strcmp (name, ".conflict") == 0) hdr->sh_type = SHT_MIPS_CONFLICT; else if (strncmp (name, ".gptab.", sizeof ".gptab." - 1) == 0) { hdr->sh_type = SHT_MIPS_GPTAB; hdr->sh_entsize = sizeof (Elf32_External_gptab); /* The sh_info field is set in final_write_processing. */ } else if (strcmp (name, ".ucode") == 0) hdr->sh_type = SHT_MIPS_UCODE; else if (strcmp (name, ".mdebug") == 0) { hdr->sh_type = SHT_MIPS_DEBUG; /* In a shared object on IRIX 5.3, the .mdebug section has an entsize of 0. FIXME: Does this matter? */ if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0) hdr->sh_entsize = 0; else hdr->sh_entsize = 1; } else if (strcmp (name, ".reginfo") == 0) { hdr->sh_type = SHT_MIPS_REGINFO; /* In a shared object on IRIX 5.3, the .reginfo section has an entsize of 0x18. FIXME: Does this matter? */ if (SGI_COMPAT (abfd)) { if ((abfd->flags & DYNAMIC) != 0) hdr->sh_entsize = sizeof (Elf32_External_RegInfo); else hdr->sh_entsize = 1; } else hdr->sh_entsize = sizeof (Elf32_External_RegInfo); } else if (SGI_COMPAT (abfd) && (strcmp (name, ".hash") == 0 || strcmp (name, ".dynamic") == 0 || strcmp (name, ".dynstr") == 0)) { if (SGI_COMPAT (abfd)) hdr->sh_entsize = 0; #if 0 /* This isn't how the IRIX6 linker behaves. */ hdr->sh_info = SIZEOF_MIPS_DYNSYM_SECNAMES; #endif } else if (strcmp (name, ".got") == 0 || strcmp (name, ".srdata") == 0 || strcmp (name, ".sdata") == 0 || strcmp (name, ".sbss") == 0 || strcmp (name, ".lit4") == 0 || strcmp (name, ".lit8") == 0) hdr->sh_flags |= SHF_MIPS_GPREL; else if (strcmp (name, ".MIPS.interfaces") == 0) { hdr->sh_type = SHT_MIPS_IFACE; hdr->sh_flags |= SHF_MIPS_NOSTRIP; } else if (strncmp (name, ".MIPS.content", strlen (".MIPS.content")) == 0) { hdr->sh_type = SHT_MIPS_CONTENT; hdr->sh_flags |= SHF_MIPS_NOSTRIP; /* The sh_info field is set in final_write_processing. */ } else if (MIPS_ELF_OPTIONS_SECTION_NAME_P (name)) { hdr->sh_type = SHT_MIPS_OPTIONS; hdr->sh_entsize = 1; hdr->sh_flags |= SHF_MIPS_NOSTRIP; } else if (strncmp (name, ".debug_", sizeof ".debug_" - 1) == 0) hdr->sh_type = SHT_MIPS_DWARF; else if (strcmp (name, ".MIPS.symlib") == 0) { hdr->sh_type = SHT_MIPS_SYMBOL_LIB; /* The sh_link and sh_info fields are set in final_write_processing. */ } else if (strncmp (name, ".MIPS.events", sizeof ".MIPS.events" - 1) == 0 || strncmp (name, ".MIPS.post_rel", sizeof ".MIPS.post_rel" - 1) == 0) { hdr->sh_type = SHT_MIPS_EVENTS; hdr->sh_flags |= SHF_MIPS_NOSTRIP; /* The sh_link field is set in final_write_processing. */ } else if (strcmp (name, ".msym") == 0) { hdr->sh_type = SHT_MIPS_MSYM; hdr->sh_flags |= SHF_ALLOC; hdr->sh_entsize = 8; } /* In the unlikely event a special section is empty it has to lose its special meaning. This may happen e.g. when using `strip' with the "--only-keep-debug" option. */ if (sec->size > 0 && !(sec->flags & SEC_HAS_CONTENTS)) hdr->sh_type = sh_type; /* The generic elf_fake_sections will set up REL_HDR using the default kind of relocations. We used to set up a second header for the non-default kind of relocations here, but only NewABI would use these, and the IRIX ld doesn't like resulting empty RELA sections. Thus we create those header only on demand now. */ return TRUE; } /* Given a BFD section, try to locate the corresponding ELF section index. This is used by both the 32-bit and the 64-bit ABI. Actually, it's not clear to me that the 64-bit ABI supports these, but for non-PIC objects we will certainly want support for at least the .scommon section. */ bfd_boolean _bfd_mips_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, int *retval) { if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0) { *retval = SHN_MIPS_SCOMMON; return TRUE; } if (strcmp (bfd_get_section_name (abfd, sec), ".acommon") == 0) { *retval = SHN_MIPS_ACOMMON; return TRUE; } return FALSE; } /* Hook called by the linker routine which adds symbols from an object file. We must handle the special MIPS section numbers here. */ bfd_boolean _bfd_mips_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info, Elf_Internal_Sym *sym, const char **namep, flagword *flagsp ATTRIBUTE_UNUSED, asection **secp, bfd_vma *valp) { if (SGI_COMPAT (abfd) && (abfd->flags & DYNAMIC) != 0 && strcmp (*namep, "_rld_new_interface") == 0) { /* Skip IRIX5 rld entry name. */ *namep = NULL; return TRUE; } /* Shared objects may have a dynamic symbol '_gp_disp' defined as a SECTION *ABS*. This causes ld to think it can resolve _gp_disp by setting a DT_NEEDED for the shared object. Since _gp_disp is a magic symbol resolved by the linker, we ignore this bogus definition of _gp_disp. New ABI objects do not suffer from this problem so this is not done for them. */ if (!NEWABI_P(abfd) && (sym->st_shndx == SHN_ABS) && (strcmp (*namep, "_gp_disp") == 0)) { *namep = NULL; return TRUE; } switch (sym->st_shndx) { case SHN_COMMON: /* Common symbols less than the GP size are automatically treated as SHN_MIPS_SCOMMON symbols. */ if (sym->st_size > elf_gp_size (abfd) || IRIX_COMPAT (abfd) == ict_irix6) break; /* Fall through. */ case SHN_MIPS_SCOMMON: *secp = bfd_make_section_old_way (abfd, ".scommon"); (*secp)->flags |= SEC_IS_COMMON; *valp = sym->st_size; break; case SHN_MIPS_TEXT: /* This section is used in a shared object. */ if (elf_tdata (abfd)->elf_text_section == NULL) { asymbol *elf_text_symbol; asection *elf_text_section; bfd_size_type amt = sizeof (asection); elf_text_section = bfd_zalloc (abfd, amt); if (elf_text_section == NULL) return FALSE; amt = sizeof (asymbol); elf_text_symbol = bfd_zalloc (abfd, amt); if (elf_text_symbol == NULL) return FALSE; /* Initialize the section. */ elf_tdata (abfd)->elf_text_section = elf_text_section; elf_tdata (abfd)->elf_text_symbol = elf_text_symbol; elf_text_section->symbol = elf_text_symbol; elf_text_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_text_symbol; elf_text_section->name = ".text"; elf_text_section->flags = SEC_NO_FLAGS; elf_text_section->output_section = NULL; elf_text_section->owner = abfd; elf_text_symbol->name = ".text"; elf_text_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC; elf_text_symbol->section = elf_text_section; } /* This code used to do *secp = bfd_und_section_ptr if info->shared. I don't know why, and that doesn't make sense, so I took it out. */ *secp = elf_tdata (abfd)->elf_text_section; break; case SHN_MIPS_ACOMMON: /* Fall through. XXX Can we treat this as allocated data? */ case SHN_MIPS_DATA: /* This section is used in a shared object. */ if (elf_tdata (abfd)->elf_data_section == NULL) { asymbol *elf_data_symbol; asection *elf_data_section; bfd_size_type amt = sizeof (asection); elf_data_section = bfd_zalloc (abfd, amt); if (elf_data_section == NULL) return FALSE; amt = sizeof (asymbol); elf_data_symbol = bfd_zalloc (abfd, amt); if (elf_data_symbol == NULL) return FALSE; /* Initialize the section. */ elf_tdata (abfd)->elf_data_section = elf_data_section; elf_tdata (abfd)->elf_data_symbol = elf_data_symbol; elf_data_section->symbol = elf_data_symbol; elf_data_section->symbol_ptr_ptr = &elf_tdata (abfd)->elf_data_symbol; elf_data_section->name = ".data"; elf_data_section->flags = SEC_NO_FLAGS; elf_data_section->output_section = NULL; elf_data_section->owner = abfd; elf_data_symbol->name = ".data"; elf_data_symbol->flags = BSF_SECTION_SYM | BSF_DYNAMIC; elf_data_symbol->section = elf_data_section; } /* This code used to do *secp = bfd_und_section_ptr if info->shared. I don't know why, and that doesn't make sense, so I took it out. */ *secp = elf_tdata (abfd)->elf_data_section; break; case SHN_MIPS_SUNDEFINED: *secp = bfd_und_section_ptr; break; } if (SGI_COMPAT (abfd) && ! info->shared && info->hash->creator == abfd->xvec && strcmp (*namep, "__rld_obj_head") == 0) { struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; /* Mark __rld_obj_head as dynamic. */ bh = NULL; if (! (_bfd_generic_link_add_one_symbol (info, abfd, *namep, BSF_GLOBAL, *secp, *valp, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_OBJECT; if (! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; mips_elf_hash_table (info)->use_rld_obj_head = TRUE; } /* If this is a mips16 text symbol, add 1 to the value to make it odd. This will cause something like .word SYM to come up with the right value when it is loaded into the PC. */ if (sym->st_other == STO_MIPS16) ++*valp; return TRUE; } /* This hook function is called before the linker writes out a global symbol. We mark symbols as small common if appropriate. This is also where we undo the increment of the value for a mips16 symbol. */ bfd_boolean _bfd_mips_elf_link_output_symbol_hook (struct bfd_link_info *info ATTRIBUTE_UNUSED, const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym, asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED) { /* If we see a common symbol, which implies a relocatable link, then if a symbol was small common in an input file, mark it as small common in the output file. */ if (sym->st_shndx == SHN_COMMON && strcmp (input_sec->name, ".scommon") == 0) sym->st_shndx = SHN_MIPS_SCOMMON; if (sym->st_other == STO_MIPS16) sym->st_value &= ~1; return TRUE; } /* Functions for the dynamic linker. */ /* Create dynamic sections when linking against a dynamic object. */ bfd_boolean _bfd_mips_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info) { struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; flagword flags; register asection *s; const char * const *namep; flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY); /* Mips ABI requests the .dynamic section to be read only. */ s = bfd_get_section_by_name (abfd, ".dynamic"); if (s != NULL) { if (! bfd_set_section_flags (abfd, s, flags)) return FALSE; } /* We need to create .got section. */ if (! mips_elf_create_got_section (abfd, info, FALSE)) return FALSE; if (! mips_elf_rel_dyn_section (elf_hash_table (info)->dynobj, TRUE)) return FALSE; /* Create .stub section. */ if (bfd_get_section_by_name (abfd, MIPS_ELF_STUB_SECTION_NAME (abfd)) == NULL) { s = bfd_make_section_with_flags (abfd, MIPS_ELF_STUB_SECTION_NAME (abfd), flags | SEC_CODE); if (s == NULL || ! bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd))) return FALSE; } if ((IRIX_COMPAT (abfd) == ict_irix5 || IRIX_COMPAT (abfd) == ict_none) && !info->shared && bfd_get_section_by_name (abfd, ".rld_map") == NULL) { s = bfd_make_section_with_flags (abfd, ".rld_map", flags &~ (flagword) SEC_READONLY); if (s == NULL || ! bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd))) return FALSE; } /* On IRIX5, we adjust add some additional symbols and change the alignments of several sections. There is no ABI documentation indicating that this is necessary on IRIX6, nor any evidence that the linker takes such action. */ if (IRIX_COMPAT (abfd) == ict_irix5) { for (namep = mips_elf_dynsym_rtproc_names; *namep != NULL; namep++) { bh = NULL; if (! (_bfd_generic_link_add_one_symbol (info, abfd, *namep, BSF_GLOBAL, bfd_und_section_ptr, 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_SECTION; if (! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } /* We need to create a .compact_rel section. */ if (SGI_COMPAT (abfd)) { if (!mips_elf_create_compact_rel_section (abfd, info)) return FALSE; } /* Change alignments of some sections. */ s = bfd_get_section_by_name (abfd, ".hash"); if (s != NULL) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd)); s = bfd_get_section_by_name (abfd, ".dynsym"); if (s != NULL) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd)); s = bfd_get_section_by_name (abfd, ".dynstr"); if (s != NULL) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd)); s = bfd_get_section_by_name (abfd, ".reginfo"); if (s != NULL) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd)); s = bfd_get_section_by_name (abfd, ".dynamic"); if (s != NULL) bfd_set_section_alignment (abfd, s, MIPS_ELF_LOG_FILE_ALIGN (abfd)); } if (!info->shared) { const char *name; name = SGI_COMPAT (abfd) ? "_DYNAMIC_LINK" : "_DYNAMIC_LINKING"; bh = NULL; if (!(_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_SECTION; if (! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; if (! mips_elf_hash_table (info)->use_rld_obj_head) { /* __rld_map is a four byte word located in the .data section and is filled in by the rtld to contain a pointer to the _r_debug structure. Its symbol value will be set in _bfd_mips_elf_finish_dynamic_symbol. */ s = bfd_get_section_by_name (abfd, ".rld_map"); BFD_ASSERT (s != NULL); name = SGI_COMPAT (abfd) ? "__rld_map" : "__RLD_MAP"; bh = NULL; if (!(_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL, s, 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_OBJECT; if (! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } } return TRUE; } /* Look through the relocs for a section during the first phase, and allocate space in the global offset table. */ bfd_boolean _bfd_mips_elf_check_relocs (bfd *abfd, struct bfd_link_info *info, asection *sec, const Elf_Internal_Rela *relocs) { const char *name; bfd *dynobj; Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; struct mips_got_info *g; size_t extsymoff; const Elf_Internal_Rela *rel; const Elf_Internal_Rela *rel_end; asection *sgot; asection *sreloc; const struct elf_backend_data *bed; if (info->relocatable) return TRUE; dynobj = elf_hash_table (info)->dynobj; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info; /* Check for the mips16 stub sections. */ name = bfd_get_section_name (abfd, sec); if (strncmp (name, FN_STUB, sizeof FN_STUB - 1) == 0) { unsigned long r_symndx; /* Look at the relocation information to figure out which symbol this is for. */ r_symndx = ELF_R_SYM (abfd, relocs->r_info); if (r_symndx < extsymoff || sym_hashes[r_symndx - extsymoff] == NULL) { asection *o; /* This stub is for a local symbol. This stub will only be needed if there is some relocation in this BFD, other than a 16 bit function call, which refers to this symbol. */ for (o = abfd->sections; o != NULL; o = o->next) { Elf_Internal_Rela *sec_relocs; const Elf_Internal_Rela *r, *rend; /* We can ignore stub sections when looking for relocs. */ if ((o->flags & SEC_RELOC) == 0 || o->reloc_count == 0 || strncmp (bfd_get_section_name (abfd, o), FN_STUB, sizeof FN_STUB - 1) == 0 || strncmp (bfd_get_section_name (abfd, o), CALL_STUB, sizeof CALL_STUB - 1) == 0 || strncmp (bfd_get_section_name (abfd, o), CALL_FP_STUB, sizeof CALL_FP_STUB - 1) == 0) continue; sec_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL, info->keep_memory); if (sec_relocs == NULL) return FALSE; rend = sec_relocs + o->reloc_count; for (r = sec_relocs; r < rend; r++) if (ELF_R_SYM (abfd, r->r_info) == r_symndx && ELF_R_TYPE (abfd, r->r_info) != R_MIPS16_26) break; if (elf_section_data (o)->relocs != sec_relocs) free (sec_relocs); if (r < rend) break; } if (o == NULL) { /* There is no non-call reloc for this stub, so we do not need it. Since this function is called before the linker maps input sections to output sections, we can easily discard it by setting the SEC_EXCLUDE flag. */ sec->flags |= SEC_EXCLUDE; return TRUE; } /* Record this stub in an array of local symbol stubs for this BFD. */ if (elf_tdata (abfd)->local_stubs == NULL) { unsigned long symcount; asection **n; bfd_size_type amt; if (elf_bad_symtab (abfd)) symcount = NUM_SHDR_ENTRIES (symtab_hdr); else symcount = symtab_hdr->sh_info; amt = symcount * sizeof (asection *); n = bfd_zalloc (abfd, amt); if (n == NULL) return FALSE; elf_tdata (abfd)->local_stubs = n; } elf_tdata (abfd)->local_stubs[r_symndx] = sec; /* We don't need to set mips16_stubs_seen in this case. That flag is used to see whether we need to look through the global symbol table for stubs. We don't need to set it here, because we just have a local stub. */ } else { struct mips_elf_link_hash_entry *h; h = ((struct mips_elf_link_hash_entry *) sym_hashes[r_symndx - extsymoff]); while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; /* H is the symbol this stub is for. */ h->fn_stub = sec; mips_elf_hash_table (info)->mips16_stubs_seen = TRUE; } } else if (strncmp (name, CALL_STUB, sizeof CALL_STUB - 1) == 0 || strncmp (name, CALL_FP_STUB, sizeof CALL_FP_STUB - 1) == 0) { unsigned long r_symndx; struct mips_elf_link_hash_entry *h; asection **loc; /* Look at the relocation information to figure out which symbol this is for. */ r_symndx = ELF_R_SYM (abfd, relocs->r_info); if (r_symndx < extsymoff || sym_hashes[r_symndx - extsymoff] == NULL) { /* This stub was actually built for a static symbol defined in the same file. We assume that all static symbols in mips16 code are themselves mips16, so we can simply discard this stub. Since this function is called before the linker maps input sections to output sections, we can easily discard it by setting the SEC_EXCLUDE flag. */ sec->flags |= SEC_EXCLUDE; return TRUE; } h = ((struct mips_elf_link_hash_entry *) sym_hashes[r_symndx - extsymoff]); /* H is the symbol this stub is for. */ if (strncmp (name, CALL_FP_STUB, sizeof CALL_FP_STUB - 1) == 0) loc = &h->call_fp_stub; else loc = &h->call_stub; /* If we already have an appropriate stub for this function, we don't need another one, so we can discard this one. Since this function is called before the linker maps input sections to output sections, we can easily discard it by setting the SEC_EXCLUDE flag. We can also discard this section if we happen to already know that this is a mips16 function; it is not necessary to check this here, as it is checked later, but it is slightly faster to check now. */ if (*loc != NULL || h->root.other == STO_MIPS16) { sec->flags |= SEC_EXCLUDE; return TRUE; } *loc = sec; mips_elf_hash_table (info)->mips16_stubs_seen = TRUE; } if (dynobj == NULL) { sgot = NULL; g = NULL; } else { sgot = mips_elf_got_section (dynobj, FALSE); if (sgot == NULL) g = NULL; else { BFD_ASSERT (mips_elf_section_data (sgot) != NULL); g = mips_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); } } sreloc = NULL; bed = get_elf_backend_data (abfd); rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel; for (rel = relocs; rel < rel_end; ++rel) { unsigned long r_symndx; unsigned int r_type; struct elf_link_hash_entry *h; r_symndx = ELF_R_SYM (abfd, rel->r_info); r_type = ELF_R_TYPE (abfd, rel->r_info); if (r_symndx < extsymoff) h = NULL; else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr)) { (*_bfd_error_handler) (_("%B: Malformed reloc detected for section %s"), abfd, name); bfd_set_error (bfd_error_bad_value); return FALSE; } else { h = sym_hashes[r_symndx - extsymoff]; /* This may be an indirect symbol created because of a version. */ if (h != NULL) { while (h->root.type == bfd_link_hash_indirect) h = (struct elf_link_hash_entry *) h->root.u.i.link; } } /* Some relocs require a global offset table. */ if (dynobj == NULL || sgot == NULL) { switch (r_type) { case R_MIPS_GOT16: case R_MIPS_CALL16: case R_MIPS_CALL_HI16: case R_MIPS_CALL_LO16: case R_MIPS_GOT_HI16: case R_MIPS_GOT_LO16: case R_MIPS_GOT_PAGE: case R_MIPS_GOT_OFST: case R_MIPS_GOT_DISP: case R_MIPS_TLS_GD: case R_MIPS_TLS_LDM: if (dynobj == NULL) elf_hash_table (info)->dynobj = dynobj = abfd; if (! mips_elf_create_got_section (dynobj, info, FALSE)) return FALSE; g = mips_elf_got_info (dynobj, &sgot); break; case R_MIPS_32: case R_MIPS_REL32: case R_MIPS_64: if (dynobj == NULL && (info->shared || h != NULL) && (sec->flags & SEC_ALLOC) != 0) elf_hash_table (info)->dynobj = dynobj = abfd; break; default: break; } } if (!h && (r_type == R_MIPS_CALL_LO16 || r_type == R_MIPS_GOT_LO16 || r_type == R_MIPS_GOT_DISP)) { /* We may need a local GOT entry for this relocation. We don't count R_MIPS_GOT_PAGE because we can estimate the maximum number of pages needed by looking at the size of the segment. Similar comments apply to R_MIPS_GOT16 and R_MIPS_CALL16. We don't count R_MIPS_GOT_HI16, or R_MIPS_CALL_HI16 because these are always followed by an R_MIPS_GOT_LO16 or R_MIPS_CALL_LO16. */ if (! mips_elf_record_local_got_symbol (abfd, r_symndx, rel->r_addend, g, 0)) return FALSE; } switch (r_type) { case R_MIPS_CALL16: if (h == NULL) { (*_bfd_error_handler) (_("%B: CALL16 reloc at 0x%lx not against global symbol"), abfd, (unsigned long) rel->r_offset); bfd_set_error (bfd_error_bad_value); return FALSE; } /* Fall through. */ case R_MIPS_CALL_HI16: case R_MIPS_CALL_LO16: if (h != NULL) { /* This symbol requires a global offset table entry. */ if (! mips_elf_record_global_got_symbol (h, abfd, info, g, 0)) return FALSE; /* We need a stub, not a plt entry for the undefined function. But we record it as if it needs plt. See _bfd_elf_adjust_dynamic_symbol. */ h->needs_plt = 1; h->type = STT_FUNC; } break; case R_MIPS_GOT_PAGE: /* If this is a global, overridable symbol, GOT_PAGE will decay to GOT_DISP, so we'll need a GOT entry for it. */ if (h == NULL) break; else { struct mips_elf_link_hash_entry *hmips = (struct mips_elf_link_hash_entry *) h; while (hmips->root.root.type == bfd_link_hash_indirect || hmips->root.root.type == bfd_link_hash_warning) hmips = (struct mips_elf_link_hash_entry *) hmips->root.root.u.i.link; if (hmips->root.def_regular && ! (info->shared && ! info->symbolic && ! hmips->root.forced_local)) break; } /* Fall through. */ case R_MIPS_GOT16: case R_MIPS_GOT_HI16: case R_MIPS_GOT_LO16: case R_MIPS_GOT_DISP: if (h && ! mips_elf_record_global_got_symbol (h, abfd, info, g, 0)) return FALSE; break; case R_MIPS_TLS_GOTTPREL: if (info->shared) info->flags |= DF_STATIC_TLS; /* Fall through */ case R_MIPS_TLS_LDM: if (r_type == R_MIPS_TLS_LDM) { r_symndx = 0; h = NULL; } /* Fall through */ case R_MIPS_TLS_GD: /* This symbol requires a global offset table entry, or two for TLS GD relocations. */ { unsigned char flag = (r_type == R_MIPS_TLS_GD ? GOT_TLS_GD : r_type == R_MIPS_TLS_LDM ? GOT_TLS_LDM : GOT_TLS_IE); if (h != NULL) { struct mips_elf_link_hash_entry *hmips = (struct mips_elf_link_hash_entry *) h; hmips->tls_type |= flag; if (h && ! mips_elf_record_global_got_symbol (h, abfd, info, g, flag)) return FALSE; } else { BFD_ASSERT (flag == GOT_TLS_LDM || r_symndx != 0); if (! mips_elf_record_local_got_symbol (abfd, r_symndx, rel->r_addend, g, flag)) return FALSE; } } break; case R_MIPS_32: case R_MIPS_REL32: case R_MIPS_64: if ((info->shared || h != NULL) && (sec->flags & SEC_ALLOC) != 0) { if (sreloc == NULL) { sreloc = mips_elf_rel_dyn_section (dynobj, TRUE); if (sreloc == NULL) return FALSE; } #define MIPS_READONLY_SECTION (SEC_ALLOC | SEC_LOAD | SEC_READONLY) if (info->shared) { /* When creating a shared object, we must copy these reloc types into the output file as R_MIPS_REL32 relocs. We make room for this reloc in the .rel.dyn reloc section. */ mips_elf_allocate_dynamic_relocations (dynobj, 1); if ((sec->flags & MIPS_READONLY_SECTION) == MIPS_READONLY_SECTION) /* We tell the dynamic linker that there are relocations against the text segment. */ info->flags |= DF_TEXTREL; } else { struct mips_elf_link_hash_entry *hmips; /* We only need to copy this reloc if the symbol is defined in a dynamic object. */ hmips = (struct mips_elf_link_hash_entry *) h; ++hmips->possibly_dynamic_relocs; if ((sec->flags & MIPS_READONLY_SECTION) == MIPS_READONLY_SECTION) /* We need it to tell the dynamic linker if there are relocations against the text segment. */ hmips->readonly_reloc = TRUE; } /* Even though we don't directly need a GOT entry for this symbol, a symbol must have a dynamic symbol table index greater that DT_MIPS_GOTSYM if there are dynamic relocations against it. */ if (h != NULL) { if (dynobj == NULL) elf_hash_table (info)->dynobj = dynobj = abfd; if (! mips_elf_create_got_section (dynobj, info, TRUE)) return FALSE; g = mips_elf_got_info (dynobj, &sgot); if (! mips_elf_record_global_got_symbol (h, abfd, info, g, 0)) return FALSE; } } if (SGI_COMPAT (abfd)) mips_elf_hash_table (info)->compact_rel_size += sizeof (Elf32_External_crinfo); break; case R_MIPS_26: case R_MIPS_GPREL16: case R_MIPS_LITERAL: case R_MIPS_GPREL32: if (SGI_COMPAT (abfd)) mips_elf_hash_table (info)->compact_rel_size += sizeof (Elf32_External_crinfo); break; /* This relocation describes the C++ object vtable hierarchy. Reconstruct it for later use during GC. */ case R_MIPS_GNU_VTINHERIT: if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset)) return FALSE; break; /* This relocation describes which C++ vtable entries are actually used. Record for later use during GC. */ case R_MIPS_GNU_VTENTRY: if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset)) return FALSE; break; default: break; } /* We must not create a stub for a symbol that has relocations related to taking the function's address. */ switch (r_type) { default: if (h != NULL) { struct mips_elf_link_hash_entry *mh; mh = (struct mips_elf_link_hash_entry *) h; mh->no_fn_stub = TRUE; } break; case R_MIPS_CALL16: case R_MIPS_CALL_HI16: case R_MIPS_CALL_LO16: case R_MIPS_JALR: break; } /* If this reloc is not a 16 bit call, and it has a global symbol, then we will need the fn_stub if there is one. References from a stub section do not count. */ if (h != NULL && r_type != R_MIPS16_26 && strncmp (bfd_get_section_name (abfd, sec), FN_STUB, sizeof FN_STUB - 1) != 0 && strncmp (bfd_get_section_name (abfd, sec), CALL_STUB, sizeof CALL_STUB - 1) != 0 && strncmp (bfd_get_section_name (abfd, sec), CALL_FP_STUB, sizeof CALL_FP_STUB - 1) != 0) { struct mips_elf_link_hash_entry *mh; mh = (struct mips_elf_link_hash_entry *) h; mh->need_fn_stub = TRUE; } } return TRUE; } bfd_boolean _bfd_mips_relax_section (bfd *abfd, asection *sec, struct bfd_link_info *link_info, bfd_boolean *again) { Elf_Internal_Rela *internal_relocs; Elf_Internal_Rela *irel, *irelend; Elf_Internal_Shdr *symtab_hdr; bfd_byte *contents = NULL; size_t extsymoff; bfd_boolean changed_contents = FALSE; bfd_vma sec_start = sec->output_section->vma + sec->output_offset; Elf_Internal_Sym *isymbuf = NULL; /* We are not currently changing any sizes, so only one pass. */ *again = FALSE; if (link_info->relocatable) return TRUE; internal_relocs = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL, link_info->keep_memory); if (internal_relocs == NULL) return TRUE; irelend = internal_relocs + sec->reloc_count * get_elf_backend_data (abfd)->s->int_rels_per_ext_rel; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info; for (irel = internal_relocs; irel < irelend; irel++) { bfd_vma symval; bfd_signed_vma sym_offset; unsigned int r_type; unsigned long r_symndx; asection *sym_sec; unsigned long instruction; /* Turn jalr into bgezal, and jr into beq, if they're marked with a JALR relocation, that indicate where they jump to. This saves some pipeline bubbles. */ r_type = ELF_R_TYPE (abfd, irel->r_info); if (r_type != R_MIPS_JALR) continue; r_symndx = ELF_R_SYM (abfd, irel->r_info); /* Compute the address of the jump target. */ if (r_symndx >= extsymoff) { struct mips_elf_link_hash_entry *h = ((struct mips_elf_link_hash_entry *) elf_sym_hashes (abfd) [r_symndx - extsymoff]); while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct mips_elf_link_hash_entry *) h->root.root.u.i.link; /* If a symbol is undefined, or if it may be overridden, skip it. */ if (! ((h->root.root.type == bfd_link_hash_defined || h->root.root.type == bfd_link_hash_defweak) && h->root.root.u.def.section) || (link_info->shared && ! link_info->symbolic && !h->root.forced_local)) continue; sym_sec = h->root.root.u.def.section; if (sym_sec->output_section) symval = (h->root.root.u.def.value + sym_sec->output_section->vma + sym_sec->output_offset); else symval = h->root.root.u.def.value; } else { Elf_Internal_Sym *isym; /* Read this BFD's symbols if we haven't done so already. */ if (isymbuf == NULL && symtab_hdr->sh_info != 0) { isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents; if (isymbuf == NULL) isymbuf = bfd_elf_get_elf_syms (abfd, symtab_hdr, symtab_hdr->sh_info, 0, NULL, NULL, NULL); if (isymbuf == NULL) goto relax_return; } isym = isymbuf + r_symndx; if (isym->st_shndx == SHN_UNDEF) continue; else if (isym->st_shndx == SHN_ABS) sym_sec = bfd_abs_section_ptr; else if (isym->st_shndx == SHN_COMMON) sym_sec = bfd_com_section_ptr; else sym_sec = bfd_section_from_elf_index (abfd, isym->st_shndx); symval = isym->st_value + sym_sec->output_section->vma + sym_sec->output_offset; } /* Compute branch offset, from delay slot of the jump to the branch target. */ sym_offset = (symval + irel->r_addend) - (sec_start + irel->r_offset + 4); /* Branch offset must be properly aligned. */ if ((sym_offset & 3) != 0) continue; sym_offset >>= 2; /* Check that it's in range. */ if (sym_offset < -0x8000 || sym_offset >= 0x8000) continue; /* Get the section contents if we haven't done so already. */ if (contents == NULL) { /* Get cached copy if it exists. */ if (elf_section_data (sec)->this_hdr.contents != NULL) contents = elf_section_data (sec)->this_hdr.contents; else { if (!bfd_malloc_and_get_section (abfd, sec, &contents)) goto relax_return; } } instruction = bfd_get_32 (abfd, contents + irel->r_offset); /* If it was jalr <reg>, turn it into bgezal $zero, <target>. */ if ((instruction & 0xfc1fffff) == 0x0000f809) instruction = 0x04110000; /* If it was jr <reg>, turn it into b <target>. */ else if ((instruction & 0xfc1fffff) == 0x00000008) instruction = 0x10000000; else continue; instruction |= (sym_offset & 0xffff); bfd_put_32 (abfd, instruction, contents + irel->r_offset); changed_contents = TRUE; } if (contents != NULL && elf_section_data (sec)->this_hdr.contents != contents) { if (!changed_contents && !link_info->keep_memory) free (contents); else { /* Cache the section contents for elf_link_input_bfd. */ elf_section_data (sec)->this_hdr.contents = contents; } } return TRUE; relax_return: if (contents != NULL && elf_section_data (sec)->this_hdr.contents != contents) free (contents); return FALSE; } /* Adjust a symbol defined by a dynamic object and referenced by a regular object. The current definition is in some section of the dynamic object, but we're not including those sections. We have to change the definition to something the rest of the link can understand. */ bfd_boolean _bfd_mips_elf_adjust_dynamic_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h) { bfd *dynobj; struct mips_elf_link_hash_entry *hmips; asection *s; dynobj = elf_hash_table (info)->dynobj; /* Make sure we know what is going on here. */ BFD_ASSERT (dynobj != NULL && (h->needs_plt || h->u.weakdef != NULL || (h->def_dynamic && h->ref_regular && !h->def_regular))); /* If this symbol is defined in a dynamic object, we need to copy any R_MIPS_32 or R_MIPS_REL32 relocs against it into the output file. */ hmips = (struct mips_elf_link_hash_entry *) h; if (! info->relocatable && hmips->possibly_dynamic_relocs != 0 && (h->root.type == bfd_link_hash_defweak || !h->def_regular)) { mips_elf_allocate_dynamic_relocations (dynobj, hmips->possibly_dynamic_relocs); if (hmips->readonly_reloc) /* We tell the dynamic linker that there are relocations against the text segment. */ info->flags |= DF_TEXTREL; } /* For a function, create a stub, if allowed. */ if (! hmips->no_fn_stub && h->needs_plt) { if (! elf_hash_table (info)->dynamic_sections_created) return TRUE; /* If this symbol is not defined in a regular file, then set the symbol to the stub location. This is required to make function pointers compare as equal between the normal executable and the shared library. */ if (!h->def_regular) { /* We need .stub section. */ s = bfd_get_section_by_name (dynobj, MIPS_ELF_STUB_SECTION_NAME (dynobj)); BFD_ASSERT (s != NULL); h->root.u.def.section = s; h->root.u.def.value = s->size; /* XXX Write this stub address somewhere. */ h->plt.offset = s->size; /* Make room for this stub code. */ s->size += MIPS_FUNCTION_STUB_SIZE; /* The last half word of the stub will be filled with the index of this symbol in .dynsym section. */ return TRUE; } } else if ((h->type == STT_FUNC) && !h->needs_plt) { /* This will set the entry for this symbol in the GOT to 0, and the dynamic linker will take care of this. */ h->root.u.def.value = 0; return TRUE; } /* If this is a weak symbol, and there is a real definition, the processor independent code will have arranged for us to see the real definition first, and we can just use the same value. */ if (h->u.weakdef != NULL) { BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined || h->u.weakdef->root.type == bfd_link_hash_defweak); h->root.u.def.section = h->u.weakdef->root.u.def.section; h->root.u.def.value = h->u.weakdef->root.u.def.value; return TRUE; } /* This is a reference to a symbol defined by a dynamic object which is not a function. */ return TRUE; } /* This function is called after all the input files have been read, and the input sections have been assigned to output sections. We check for any mips16 stub sections that we can discard. */ bfd_boolean _bfd_mips_elf_always_size_sections (bfd *output_bfd, struct bfd_link_info *info) { asection *ri; bfd *dynobj; asection *s; struct mips_got_info *g; int i; bfd_size_type loadable_size = 0; bfd_size_type local_gotno; bfd *sub; struct mips_elf_count_tls_arg count_tls_arg; /* The .reginfo section has a fixed size. */ ri = bfd_get_section_by_name (output_bfd, ".reginfo"); if (ri != NULL) bfd_set_section_size (output_bfd, ri, sizeof (Elf32_External_RegInfo)); if (! (info->relocatable || ! mips_elf_hash_table (info)->mips16_stubs_seen)) mips_elf_link_hash_traverse (mips_elf_hash_table (info), mips_elf_check_mips16_stubs, NULL); dynobj = elf_hash_table (info)->dynobj; if (dynobj == NULL) /* Relocatable links don't have it. */ return TRUE; g = mips_elf_got_info (dynobj, &s); if (s == NULL) return TRUE; /* Calculate the total loadable size of the output. That will give us the maximum number of GOT_PAGE entries required. */ for (sub = info->input_bfds; sub; sub = sub->link_next) { asection *subsection; for (subsection = sub->sections; subsection; subsection = subsection->next) { if ((subsection->flags & SEC_ALLOC) == 0) continue; loadable_size += ((subsection->size + 0xf) &~ (bfd_size_type) 0xf); } } /* There has to be a global GOT entry for every symbol with a dynamic symbol table index of DT_MIPS_GOTSYM or higher. Therefore, it make sense to put those symbols that need GOT entries at the end of the symbol table. We do that here. */ if (! mips_elf_sort_hash_table (info, 1)) return FALSE; if (g->global_gotsym != NULL) i = elf_hash_table (info)->dynsymcount - g->global_gotsym->dynindx; else /* If there are no global symbols, or none requiring relocations, then GLOBAL_GOTSYM will be NULL. */ i = 0; /* In the worst case, we'll get one stub per dynamic symbol, plus one to account for the dummy entry at the end required by IRIX rld. */ loadable_size += MIPS_FUNCTION_STUB_SIZE * (i + 1); /* Assume there are two loadable segments consisting of contiguous sections. Is 5 enough? */ local_gotno = (loadable_size >> 16) + 5; g->local_gotno += local_gotno; s->size += g->local_gotno * MIPS_ELF_GOT_SIZE (output_bfd); g->global_gotno = i; s->size += i * MIPS_ELF_GOT_SIZE (output_bfd); /* We need to calculate tls_gotno for global symbols at this point instead of building it up earlier, to avoid doublecounting entries for one global symbol from multiple input files. */ count_tls_arg.info = info; count_tls_arg.needed = 0; elf_link_hash_traverse (elf_hash_table (info), mips_elf_count_global_tls_entries, &count_tls_arg); g->tls_gotno += count_tls_arg.needed; s->size += g->tls_gotno * MIPS_ELF_GOT_SIZE (output_bfd); mips_elf_resolve_final_got_entries (g); if (s->size > MIPS_ELF_GOT_MAX_SIZE (output_bfd)) { if (! mips_elf_multi_got (output_bfd, info, g, s, local_gotno)) return FALSE; } else { /* Set up TLS entries for the first GOT. */ g->tls_assigned_gotno = g->global_gotno + g->local_gotno; htab_traverse (g->got_entries, mips_elf_initialize_tls_index, g); } return TRUE; } /* Set the sizes of the dynamic sections. */ bfd_boolean _bfd_mips_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *s; bfd_boolean reltext; dynobj = elf_hash_table (info)->dynobj; BFD_ASSERT (dynobj != NULL); if (elf_hash_table (info)->dynamic_sections_created) { /* Set the contents of the .interp section to the interpreter. */ if (info->executable) { s = bfd_get_section_by_name (dynobj, ".interp"); BFD_ASSERT (s != NULL); s->size = strlen (ELF_DYNAMIC_INTERPRETER (output_bfd)) + 1; s->contents = (bfd_byte *) ELF_DYNAMIC_INTERPRETER (output_bfd); } } /* The check_relocs and adjust_dynamic_symbol entry points have determined the sizes of the various dynamic sections. Allocate memory for them. */ reltext = FALSE; for (s = dynobj->sections; s != NULL; s = s->next) { const char *name; /* It's OK to base decisions on the section name, because none of the dynobj section names depend upon the input files. */ name = bfd_get_section_name (dynobj, s); if ((s->flags & SEC_LINKER_CREATED) == 0) continue; if (strncmp (name, ".rel", 4) == 0) { if (s->size != 0) { const char *outname; asection *target; /* If this relocation section applies to a read only section, then we probably need a DT_TEXTREL entry. If the relocation section is .rel.dyn, we always assert a DT_TEXTREL entry rather than testing whether there exists a relocation to a read only section or not. */ outname = bfd_get_section_name (output_bfd, s->output_section); target = bfd_get_section_by_name (output_bfd, outname + 4); if ((target != NULL && (target->flags & SEC_READONLY) != 0 && (target->flags & SEC_ALLOC) != 0) || strcmp (outname, ".rel.dyn") == 0) reltext = TRUE; /* We use the reloc_count field as a counter if we need to copy relocs into the output file. */ if (strcmp (name, ".rel.dyn") != 0) s->reloc_count = 0; /* If combreloc is enabled, elf_link_sort_relocs() will sort relocations, but in a different way than we do, and before we're done creating relocations. Also, it will move them around between input sections' relocation's contents, so our sorting would be broken, so don't let it run. */ info->combreloc = 0; } } else if (strncmp (name, ".got", 4) == 0) { /* _bfd_mips_elf_always_size_sections() has already done most of the work, but some symbols may have been mapped to versions that we must now resolve in the got_entries hash tables. */ struct mips_got_info *gg = mips_elf_got_info (dynobj, NULL); struct mips_got_info *g = gg; struct mips_elf_set_global_got_offset_arg set_got_offset_arg; unsigned int needed_relocs = 0; if (gg->next) { set_got_offset_arg.value = MIPS_ELF_GOT_SIZE (output_bfd); set_got_offset_arg.info = info; /* NOTE 2005-02-03: How can this call, or the next, ever find any indirect entries to resolve? They were all resolved in mips_elf_multi_got. */ mips_elf_resolve_final_got_entries (gg); for (g = gg->next; g && g->next != gg; g = g->next) { unsigned int save_assign; mips_elf_resolve_final_got_entries (g); /* Assign offsets to global GOT entries. */ save_assign = g->assigned_gotno; g->assigned_gotno = g->local_gotno; set_got_offset_arg.g = g; set_got_offset_arg.needed_relocs = 0; htab_traverse (g->got_entries, mips_elf_set_global_got_offset, &set_got_offset_arg); needed_relocs += set_got_offset_arg.needed_relocs; BFD_ASSERT (g->assigned_gotno - g->local_gotno <= g->global_gotno); g->assigned_gotno = save_assign; if (info->shared) { needed_relocs += g->local_gotno - g->assigned_gotno; BFD_ASSERT (g->assigned_gotno == g->next->local_gotno + g->next->global_gotno + g->next->tls_gotno + MIPS_RESERVED_GOTNO); } } } else { struct mips_elf_count_tls_arg arg; arg.info = info; arg.needed = 0; htab_traverse (gg->got_entries, mips_elf_count_local_tls_relocs, &arg); elf_link_hash_traverse (elf_hash_table (info), mips_elf_count_global_tls_relocs, &arg); needed_relocs += arg.needed; } if (needed_relocs) mips_elf_allocate_dynamic_relocations (dynobj, needed_relocs); } else if (strcmp (name, MIPS_ELF_STUB_SECTION_NAME (output_bfd)) == 0) { /* IRIX rld assumes that the function stub isn't at the end of .text section. So put a dummy. XXX */ s->size += MIPS_FUNCTION_STUB_SIZE; } else if (! info->shared && ! mips_elf_hash_table (info)->use_rld_obj_head && strncmp (name, ".rld_map", 8) == 0) { /* We add a room for __rld_map. It will be filled in by the rtld to contain a pointer to the _r_debug structure. */ s->size += 4; } else if (SGI_COMPAT (output_bfd) && strncmp (name, ".compact_rel", 12) == 0) s->size += mips_elf_hash_table (info)->compact_rel_size; else if (strncmp (name, ".init", 5) != 0) { /* It's not one of our sections, so don't allocate space. */ continue; } if (s->size == 0) { s->flags |= SEC_EXCLUDE; continue; } if ((s->flags & SEC_HAS_CONTENTS) == 0) continue; /* Allocate memory for the section contents. */ s->contents = bfd_zalloc (dynobj, s->size); if (s->contents == NULL) { bfd_set_error (bfd_error_no_memory); return FALSE; } } if (elf_hash_table (info)->dynamic_sections_created) { /* Add some entries to the .dynamic section. We fill in the values later, in _bfd_mips_elf_finish_dynamic_sections, but we must add the entries now so that we get the correct size for the .dynamic section. The DT_DEBUG entry is filled in by the dynamic linker and used by the debugger. */ if (! info->shared) { /* SGI object has the equivalence of DT_DEBUG in the DT_MIPS_RLD_MAP entry. */ if (!MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_MAP, 0)) return FALSE; if (!SGI_COMPAT (output_bfd)) { if (!MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0)) return FALSE; } } else { /* Shared libraries on traditional mips have DT_DEBUG. */ if (!SGI_COMPAT (output_bfd)) { if (!MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0)) return FALSE; } } if (reltext && SGI_COMPAT (output_bfd)) info->flags |= DF_TEXTREL; if ((info->flags & DF_TEXTREL) != 0) { if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0)) return FALSE; } if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0)) return FALSE; if (mips_elf_rel_dyn_section (dynobj, FALSE)) { if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0)) return FALSE; } if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_RLD_VERSION, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_FLAGS, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_BASE_ADDRESS, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_LOCAL_GOTNO, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_SYMTABNO, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_UNREFEXTNO, 0)) return FALSE; if (! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_GOTSYM, 0)) return FALSE; if (IRIX_COMPAT (dynobj) == ict_irix5 && ! MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_HIPAGENO, 0)) return FALSE; if (IRIX_COMPAT (dynobj) == ict_irix6 && (bfd_get_section_by_name (dynobj, MIPS_ELF_OPTIONS_SECTION_NAME (dynobj))) && !MIPS_ELF_ADD_DYNAMIC_ENTRY (info, DT_MIPS_OPTIONS, 0)) return FALSE; } return TRUE; } /* Relocate a MIPS ELF section. */ bfd_boolean _bfd_mips_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info, bfd *input_bfd, asection *input_section, bfd_byte *contents, Elf_Internal_Rela *relocs, Elf_Internal_Sym *local_syms, asection **local_sections) { Elf_Internal_Rela *rel; const Elf_Internal_Rela *relend; bfd_vma addend = 0; bfd_boolean use_saved_addend_p = FALSE; const struct elf_backend_data *bed; bed = get_elf_backend_data (output_bfd); relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel; for (rel = relocs; rel < relend; ++rel) { const char *name; bfd_vma value = 0; reloc_howto_type *howto; bfd_boolean require_jalx; /* TRUE if the relocation is a RELA relocation, rather than a REL relocation. */ bfd_boolean rela_relocation_p = TRUE; unsigned int r_type = ELF_R_TYPE (output_bfd, rel->r_info); const char *msg; /* Find the relocation howto for this relocation. */ if (r_type == R_MIPS_64 && ! NEWABI_P (input_bfd)) { /* Some 32-bit code uses R_MIPS_64. In particular, people use 64-bit code, but make sure all their addresses are in the lowermost or uppermost 32-bit section of the 64-bit address space. Thus, when they use an R_MIPS_64 they mean what is usually meant by R_MIPS_32, with the exception that the stored value is sign-extended to 64 bits. */ howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, R_MIPS_32, FALSE); /* On big-endian systems, we need to lie about the position of the reloc. */ if (bfd_big_endian (input_bfd)) rel->r_offset += 4; } else /* NewABI defaults to RELA relocations. */ howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, r_type, NEWABI_P (input_bfd) && (MIPS_RELOC_RELA_P (input_bfd, input_section, rel - relocs))); if (!use_saved_addend_p) { Elf_Internal_Shdr *rel_hdr; /* If these relocations were originally of the REL variety, we must pull the addend out of the field that will be relocated. Otherwise, we simply use the contents of the RELA relocation. To determine which flavor or relocation this is, we depend on the fact that the INPUT_SECTION's REL_HDR is read before its REL_HDR2. */ rel_hdr = &elf_section_data (input_section)->rel_hdr; if ((size_t) (rel - relocs) >= (NUM_SHDR_ENTRIES (rel_hdr) * bed->s->int_rels_per_ext_rel)) rel_hdr = elf_section_data (input_section)->rel_hdr2; if (rel_hdr->sh_entsize == MIPS_ELF_REL_SIZE (input_bfd)) { bfd_byte *location = contents + rel->r_offset; /* Note that this is a REL relocation. */ rela_relocation_p = FALSE; /* Get the addend, which is stored in the input file. */ _bfd_mips16_elf_reloc_unshuffle (input_bfd, r_type, FALSE, location); addend = mips_elf_obtain_contents (howto, rel, input_bfd, contents); _bfd_mips16_elf_reloc_shuffle(input_bfd, r_type, FALSE, location); addend &= howto->src_mask; /* For some kinds of relocations, the ADDEND is a combination of the addend stored in two different relocations. */ if (r_type == R_MIPS_HI16 || r_type == R_MIPS16_HI16 || (r_type == R_MIPS_GOT16 && mips_elf_local_relocation_p (input_bfd, rel, local_sections, FALSE))) { bfd_vma l; const Elf_Internal_Rela *lo16_relocation; reloc_howto_type *lo16_howto; bfd_byte *lo16_location; int lo16_type; if (r_type == R_MIPS16_HI16) lo16_type = R_MIPS16_LO16; else lo16_type = R_MIPS_LO16; /* The combined value is the sum of the HI16 addend, left-shifted by sixteen bits, and the LO16 addend, sign extended. (Usually, the code does a `lui' of the HI16 value, and then an `addiu' of the LO16 value.) Scan ahead to find a matching LO16 relocation. According to the MIPS ELF ABI, the R_MIPS_LO16 relocation must be immediately following. However, for the IRIX6 ABI, the next relocation may be a composed relocation consisting of several relocations for the same address. In that case, the R_MIPS_LO16 relocation may occur as one of these. We permit a similar extension in general, as that is useful for GCC. */ lo16_relocation = mips_elf_next_relocation (input_bfd, lo16_type, rel, relend); if (lo16_relocation == NULL) return FALSE; lo16_location = contents + lo16_relocation->r_offset; /* Obtain the addend kept there. */ lo16_howto = MIPS_ELF_RTYPE_TO_HOWTO (input_bfd, lo16_type, FALSE); _bfd_mips16_elf_reloc_unshuffle (input_bfd, lo16_type, FALSE, lo16_location); l = mips_elf_obtain_contents (lo16_howto, lo16_relocation, input_bfd, contents); _bfd_mips16_elf_reloc_shuffle (input_bfd, lo16_type, FALSE, lo16_location); l &= lo16_howto->src_mask; l <<= lo16_howto->rightshift; l = _bfd_mips_elf_sign_extend (l, 16); addend <<= 16; /* Compute the combined addend. */ addend += l; } else addend <<= howto->rightshift; } else addend = rel->r_addend; } if (info->relocatable) { Elf_Internal_Sym *sym; unsigned long r_symndx; if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd) && bfd_big_endian (input_bfd)) rel->r_offset -= 4; /* Since we're just relocating, all we need to do is copy the relocations back out to the object file, unless they're against a section symbol, in which case we need to adjust by the section offset, or unless they're GP relative in which case we need to adjust by the amount that we're adjusting GP in this relocatable object. */ if (! mips_elf_local_relocation_p (input_bfd, rel, local_sections, FALSE)) /* There's nothing to do for non-local relocations. */ continue; if (r_type == R_MIPS16_GPREL || r_type == R_MIPS_GPREL16 || r_type == R_MIPS_GPREL32 || r_type == R_MIPS_LITERAL) addend -= (_bfd_get_gp_value (output_bfd) - _bfd_get_gp_value (input_bfd)); r_symndx = ELF_R_SYM (output_bfd, rel->r_info); sym = local_syms + r_symndx; if (ELF_ST_TYPE (sym->st_info) == STT_SECTION) /* Adjust the addend appropriately. */ addend += local_sections[r_symndx]->output_offset; if (rela_relocation_p) /* If this is a RELA relocation, just update the addend. */ rel->r_addend = addend; else { if (r_type == R_MIPS_HI16 || r_type == R_MIPS_GOT16) addend = mips_elf_high (addend); else if (r_type == R_MIPS_HIGHER) addend = mips_elf_higher (addend); else if (r_type == R_MIPS_HIGHEST) addend = mips_elf_highest (addend); else addend >>= howto->rightshift; /* We use the source mask, rather than the destination mask because the place to which we are writing will be source of the addend in the final link. */ addend &= howto->src_mask; if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)) /* See the comment above about using R_MIPS_64 in the 32-bit ABI. Here, we need to update the addend. It would be possible to get away with just using the R_MIPS_32 reloc but for endianness. */ { bfd_vma sign_bits; bfd_vma low_bits; bfd_vma high_bits; if (addend & ((bfd_vma) 1 << 31)) #ifdef BFD64 sign_bits = ((bfd_vma) 1 << 32) - 1; #else sign_bits = -1; #endif else sign_bits = 0; /* If we don't know that we have a 64-bit type, do two separate stores. */ if (bfd_big_endian (input_bfd)) { /* Store the sign-bits (which are most significant) first. */ low_bits = sign_bits; high_bits = addend; } else { low_bits = addend; high_bits = sign_bits; } bfd_put_32 (input_bfd, low_bits, contents + rel->r_offset); bfd_put_32 (input_bfd, high_bits, contents + rel->r_offset + 4); continue; } if (! mips_elf_perform_relocation (info, howto, rel, addend, input_bfd, input_section, contents, FALSE)) return FALSE; } /* Go on to the next relocation. */ continue; } /* In the N32 and 64-bit ABIs there may be multiple consecutive relocations for the same offset. In that case we are supposed to treat the output of each relocation as the addend for the next. */ if (rel + 1 < relend && rel->r_offset == rel[1].r_offset && ELF_R_TYPE (input_bfd, rel[1].r_info) != R_MIPS_NONE) use_saved_addend_p = TRUE; else use_saved_addend_p = FALSE; /* Figure out what value we are supposed to relocate. */ switch (mips_elf_calculate_relocation (output_bfd, input_bfd, input_section, info, rel, addend, howto, local_syms, local_sections, &value, &name, &require_jalx, use_saved_addend_p)) { case bfd_reloc_continue: /* There's nothing to do. */ continue; case bfd_reloc_undefined: /* mips_elf_calculate_relocation already called the undefined_symbol callback. There's no real point in trying to perform the relocation at this point, so we just skip ahead to the next relocation. */ continue; case bfd_reloc_notsupported: msg = _("internal error: unsupported relocation error"); info->callbacks->warning (info, msg, name, input_bfd, input_section, rel->r_offset); return FALSE; case bfd_reloc_overflow: if (use_saved_addend_p) /* Ignore overflow until we reach the last relocation for a given location. */ ; else { BFD_ASSERT (name != NULL); if (! ((*info->callbacks->reloc_overflow) (info, NULL, name, howto->name, (bfd_vma) 0, input_bfd, input_section, rel->r_offset))) return FALSE; } break; case bfd_reloc_ok: break; default: abort (); break; } /* If we've got another relocation for the address, keep going until we reach the last one. */ if (use_saved_addend_p) { addend = value; continue; } if (r_type == R_MIPS_64 && ! NEWABI_P (output_bfd)) /* See the comment above about using R_MIPS_64 in the 32-bit ABI. Until now, we've been using the HOWTO for R_MIPS_32; that calculated the right value. Now, however, we sign-extend the 32-bit result to 64-bits, and store it as a 64-bit value. We are especially generous here in that we go to extreme lengths to support this usage on systems with only a 32-bit VMA. */ { bfd_vma sign_bits; bfd_vma low_bits; bfd_vma high_bits; if (value & ((bfd_vma) 1 << 31)) #ifdef BFD64 sign_bits = ((bfd_vma) 1 << 32) - 1; #else sign_bits = -1; #endif else sign_bits = 0; /* If we don't know that we have a 64-bit type, do two separate stores. */ if (bfd_big_endian (input_bfd)) { /* Undo what we did above. */ rel->r_offset -= 4; /* Store the sign-bits (which are most significant) first. */ low_bits = sign_bits; high_bits = value; } else { low_bits = value; high_bits = sign_bits; } bfd_put_32 (input_bfd, low_bits, contents + rel->r_offset); bfd_put_32 (input_bfd, high_bits, contents + rel->r_offset + 4); continue; } /* Actually perform the relocation. */ if (! mips_elf_perform_relocation (info, howto, rel, value, input_bfd, input_section, contents, require_jalx)) return FALSE; } return TRUE; } /* If NAME is one of the special IRIX6 symbols defined by the linker, adjust it appropriately now. */ static void mips_elf_irix6_finish_dynamic_symbol (bfd *abfd ATTRIBUTE_UNUSED, const char *name, Elf_Internal_Sym *sym) { /* The linker script takes care of providing names and values for these, but we must place them into the right sections. */ static const char* const text_section_symbols[] = { "_ftext", "_etext", "__dso_displacement", "__elf_header", "__program_header_table", NULL }; static const char* const data_section_symbols[] = { "_fdata", "_edata", "_end", "_fbss", NULL }; const char* const *p; int i; for (i = 0; i < 2; ++i) for (p = (i == 0) ? text_section_symbols : data_section_symbols; *p; ++p) if (strcmp (*p, name) == 0) { /* All of these symbols are given type STT_SECTION by the IRIX6 linker. */ sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_other = STO_PROTECTED; /* The IRIX linker puts these symbols in special sections. */ if (i == 0) sym->st_shndx = SHN_MIPS_TEXT; else sym->st_shndx = SHN_MIPS_DATA; break; } } /* Finish up dynamic symbol handling. We set the contents of various dynamic sections here. */ bfd_boolean _bfd_mips_elf_finish_dynamic_symbol (bfd *output_bfd, struct bfd_link_info *info, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { bfd *dynobj; asection *sgot; struct mips_got_info *g, *gg; const char *name; dynobj = elf_hash_table (info)->dynobj; if (h->plt.offset != MINUS_ONE) { asection *s; bfd_byte stub[MIPS_FUNCTION_STUB_SIZE]; /* This symbol has a stub. Set it up. */ BFD_ASSERT (h->dynindx != -1); s = bfd_get_section_by_name (dynobj, MIPS_ELF_STUB_SECTION_NAME (dynobj)); BFD_ASSERT (s != NULL); /* FIXME: Can h->dynindx be more than 64K? */ if (h->dynindx & 0xffff0000) return FALSE; /* Fill the stub. */ bfd_put_32 (output_bfd, STUB_LW (output_bfd), stub); bfd_put_32 (output_bfd, STUB_MOVE (output_bfd), stub + 4); bfd_put_32 (output_bfd, STUB_JALR, stub + 8); bfd_put_32 (output_bfd, STUB_LI16 (output_bfd) + h->dynindx, stub + 12); BFD_ASSERT (h->plt.offset <= s->size); memcpy (s->contents + h->plt.offset, stub, MIPS_FUNCTION_STUB_SIZE); /* Mark the symbol as undefined. plt.offset != -1 occurs only for the referenced symbol. */ sym->st_shndx = SHN_UNDEF; /* The run-time linker uses the st_value field of the symbol to reset the global offset table entry for this external to its stub address when unlinking a shared object. */ sym->st_value = (s->output_section->vma + s->output_offset + h->plt.offset); } BFD_ASSERT (h->dynindx != -1 || h->forced_local); sgot = mips_elf_got_section (dynobj, FALSE); BFD_ASSERT (sgot != NULL); BFD_ASSERT (mips_elf_section_data (sgot) != NULL); g = mips_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); /* Run through the global symbol table, creating GOT entries for all the symbols that need them. */ if (g->global_gotsym != NULL && h->dynindx >= g->global_gotsym->dynindx) { bfd_vma offset; bfd_vma value; value = sym->st_value; offset = mips_elf_global_got_index (dynobj, output_bfd, h, R_MIPS_GOT16, info); MIPS_ELF_PUT_WORD (output_bfd, value, sgot->contents + offset); } if (g->next && h->dynindx != -1 && h->type != STT_TLS) { struct mips_got_entry e, *p; bfd_vma entry; bfd_vma offset; gg = g; e.abfd = output_bfd; e.symndx = -1; e.d.h = (struct mips_elf_link_hash_entry *)h; e.tls_type = 0; for (g = g->next; g->next != gg; g = g->next) { if (g->got_entries && (p = (struct mips_got_entry *) htab_find (g->got_entries, &e))) { offset = p->gotidx; if (info->shared || (elf_hash_table (info)->dynamic_sections_created && p->d.h != NULL && p->d.h->root.def_dynamic && !p->d.h->root.def_regular)) { /* Create an R_MIPS_REL32 relocation for this entry. Due to the various compatibility problems, it's easier to mock up an R_MIPS_32 or R_MIPS_64 relocation and leave mips_elf_create_dynamic_relocation to calculate the appropriate addend. */ Elf_Internal_Rela rel[3]; memset (rel, 0, sizeof (rel)); if (ABI_64_P (output_bfd)) rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_64); else rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_32); rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = offset; entry = 0; if (! (mips_elf_create_dynamic_relocation (output_bfd, info, rel, e.d.h, NULL, sym->st_value, &entry, sgot))) return FALSE; } else entry = sym->st_value; MIPS_ELF_PUT_WORD (output_bfd, entry, sgot->contents + offset); } } } /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute. */ name = h->root.root.string; if (strcmp (name, "_DYNAMIC") == 0 || strcmp (name, "_GLOBAL_OFFSET_TABLE_") == 0) sym->st_shndx = SHN_ABS; else if (strcmp (name, "_DYNAMIC_LINK") == 0 || strcmp (name, "_DYNAMIC_LINKING") == 0) { sym->st_shndx = SHN_ABS; sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_value = 1; } else if (strcmp (name, "_gp_disp") == 0 && ! NEWABI_P (output_bfd)) { sym->st_shndx = SHN_ABS; sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_value = elf_gp (output_bfd); } else if (SGI_COMPAT (output_bfd)) { if (strcmp (name, mips_elf_dynsym_rtproc_names[0]) == 0 || strcmp (name, mips_elf_dynsym_rtproc_names[1]) == 0) { sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_other = STO_PROTECTED; sym->st_value = 0; sym->st_shndx = SHN_MIPS_DATA; } else if (strcmp (name, mips_elf_dynsym_rtproc_names[2]) == 0) { sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_other = STO_PROTECTED; sym->st_value = mips_elf_hash_table (info)->procedure_count; sym->st_shndx = SHN_ABS; } else if (sym->st_shndx != SHN_UNDEF && sym->st_shndx != SHN_ABS) { if (h->type == STT_FUNC) sym->st_shndx = SHN_MIPS_TEXT; else if (h->type == STT_OBJECT) sym->st_shndx = SHN_MIPS_DATA; } } /* Handle the IRIX6-specific symbols. */ if (IRIX_COMPAT (output_bfd) == ict_irix6) mips_elf_irix6_finish_dynamic_symbol (output_bfd, name, sym); if (! info->shared) { if (! mips_elf_hash_table (info)->use_rld_obj_head && (strcmp (name, "__rld_map") == 0 || strcmp (name, "__RLD_MAP") == 0)) { asection *s = bfd_get_section_by_name (dynobj, ".rld_map"); BFD_ASSERT (s != NULL); sym->st_value = s->output_section->vma + s->output_offset; bfd_put_32 (output_bfd, 0, s->contents); if (mips_elf_hash_table (info)->rld_value == 0) mips_elf_hash_table (info)->rld_value = sym->st_value; } else if (mips_elf_hash_table (info)->use_rld_obj_head && strcmp (name, "__rld_obj_head") == 0) { /* IRIX6 does not use a .rld_map section. */ if (IRIX_COMPAT (output_bfd) == ict_irix5 || IRIX_COMPAT (output_bfd) == ict_none) BFD_ASSERT (bfd_get_section_by_name (dynobj, ".rld_map") != NULL); mips_elf_hash_table (info)->rld_value = sym->st_value; } } /* If this is a mips16 symbol, force the value to be even. */ if (sym->st_other == STO_MIPS16) sym->st_value &= ~1; return TRUE; } /* Finish up the dynamic sections. */ bfd_boolean _bfd_mips_elf_finish_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *sdyn; asection *sgot; struct mips_got_info *gg, *g; dynobj = elf_hash_table (info)->dynobj; sdyn = bfd_get_section_by_name (dynobj, ".dynamic"); sgot = mips_elf_got_section (dynobj, FALSE); if (sgot == NULL) gg = g = NULL; else { BFD_ASSERT (mips_elf_section_data (sgot) != NULL); gg = mips_elf_section_data (sgot)->u.got_info; BFD_ASSERT (gg != NULL); g = mips_elf_got_for_ibfd (gg, output_bfd); BFD_ASSERT (g != NULL); } if (elf_hash_table (info)->dynamic_sections_created) { bfd_byte *b; BFD_ASSERT (sdyn != NULL); BFD_ASSERT (g != NULL); for (b = sdyn->contents; b < sdyn->contents + sdyn->size; b += MIPS_ELF_DYN_SIZE (dynobj)) { Elf_Internal_Dyn dyn; const char *name; size_t elemsize; asection *s; bfd_boolean swap_out_p; /* Read in the current dynamic entry. */ (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn); /* Assume that we're going to modify it and write it out. */ swap_out_p = TRUE; switch (dyn.d_tag) { case DT_RELENT: s = mips_elf_rel_dyn_section (dynobj, FALSE); BFD_ASSERT (s != NULL); dyn.d_un.d_val = MIPS_ELF_REL_SIZE (dynobj); break; case DT_STRSZ: /* Rewrite DT_STRSZ. */ dyn.d_un.d_val = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr); break; case DT_PLTGOT: name = ".got"; s = bfd_get_section_by_name (output_bfd, name); BFD_ASSERT (s != NULL); dyn.d_un.d_ptr = s->vma; break; case DT_MIPS_RLD_VERSION: dyn.d_un.d_val = 1; /* XXX */ break; case DT_MIPS_FLAGS: dyn.d_un.d_val = RHF_NOTPOT; /* XXX */ break; case DT_MIPS_TIME_STAMP: { time_t t; time (&t); dyn.d_un.d_val = t; } break; case DT_MIPS_ICHECKSUM: /* XXX FIXME: */ swap_out_p = FALSE; break; case DT_MIPS_IVERSION: /* XXX FIXME: */ swap_out_p = FALSE; break; case DT_MIPS_BASE_ADDRESS: s = output_bfd->sections; BFD_ASSERT (s != NULL); dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff; break; case DT_MIPS_LOCAL_GOTNO: dyn.d_un.d_val = g->local_gotno; break; case DT_MIPS_UNREFEXTNO: /* The index into the dynamic symbol table which is the entry of the first external symbol that is not referenced within the same object. */ dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1; break; case DT_MIPS_GOTSYM: if (gg->global_gotsym) { dyn.d_un.d_val = gg->global_gotsym->dynindx; break; } /* In case if we don't have global got symbols we default to setting DT_MIPS_GOTSYM to the same value as DT_MIPS_SYMTABNO, so we just fall through. */ case DT_MIPS_SYMTABNO: name = ".dynsym"; elemsize = MIPS_ELF_SYM_SIZE (output_bfd); s = bfd_get_section_by_name (output_bfd, name); BFD_ASSERT (s != NULL); dyn.d_un.d_val = s->size / elemsize; break; case DT_MIPS_HIPAGENO: dyn.d_un.d_val = g->local_gotno - MIPS_RESERVED_GOTNO; break; case DT_MIPS_RLD_MAP: dyn.d_un.d_ptr = mips_elf_hash_table (info)->rld_value; break; case DT_MIPS_OPTIONS: s = (bfd_get_section_by_name (output_bfd, MIPS_ELF_OPTIONS_SECTION_NAME (output_bfd))); dyn.d_un.d_ptr = s->vma; break; default: swap_out_p = FALSE; break; } if (swap_out_p) (*get_elf_backend_data (dynobj)->s->swap_dyn_out) (dynobj, &dyn, b); } } /* The first entry of the global offset table will be filled at runtime. The second entry will be used by some runtime loaders. This isn't the case of IRIX rld. */ if (sgot != NULL && sgot->size > 0) { MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents); MIPS_ELF_PUT_WORD (output_bfd, 0x80000000, sgot->contents + MIPS_ELF_GOT_SIZE (output_bfd)); } if (sgot != NULL) elf_section_data (sgot->output_section)->this_hdr.sh_entsize = MIPS_ELF_GOT_SIZE (output_bfd); /* Generate dynamic relocations for the non-primary gots. */ if (gg != NULL && gg->next) { Elf_Internal_Rela rel[3]; bfd_vma addend = 0; memset (rel, 0, sizeof (rel)); rel[0].r_info = ELF_R_INFO (output_bfd, 0, R_MIPS_REL32); for (g = gg->next; g->next != gg; g = g->next) { bfd_vma index = g->next->local_gotno + g->next->global_gotno + g->next->tls_gotno; MIPS_ELF_PUT_WORD (output_bfd, 0, sgot->contents + index++ * MIPS_ELF_GOT_SIZE (output_bfd)); MIPS_ELF_PUT_WORD (output_bfd, 0x80000000, sgot->contents + index++ * MIPS_ELF_GOT_SIZE (output_bfd)); if (! info->shared) continue; while (index < g->assigned_gotno) { rel[0].r_offset = rel[1].r_offset = rel[2].r_offset = index++ * MIPS_ELF_GOT_SIZE (output_bfd); if (!(mips_elf_create_dynamic_relocation (output_bfd, info, rel, NULL, bfd_abs_section_ptr, 0, &addend, sgot))) return FALSE; BFD_ASSERT (addend == 0); } } } /* The generation of dynamic relocations for the non-primary gots adds more dynamic relocations. We cannot count them until here. */ if (elf_hash_table (info)->dynamic_sections_created) { bfd_byte *b; bfd_boolean swap_out_p; BFD_ASSERT (sdyn != NULL); for (b = sdyn->contents; b < sdyn->contents + sdyn->size; b += MIPS_ELF_DYN_SIZE (dynobj)) { Elf_Internal_Dyn dyn; asection *s; /* Read in the current dynamic entry. */ (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn); /* Assume that we're going to modify it and write it out. */ swap_out_p = TRUE; switch (dyn.d_tag) { case DT_RELSZ: /* Reduce DT_RELSZ to account for any relocations we decided not to make. This is for the n64 irix rld, which doesn't seem to apply any relocations if there are trailing null entries. */ s = mips_elf_rel_dyn_section (dynobj, FALSE); dyn.d_un.d_val = (s->reloc_count * (ABI_64_P (output_bfd) ? sizeof (Elf64_Mips_External_Rel) : sizeof (Elf32_External_Rel))); break; default: swap_out_p = FALSE; break; } if (swap_out_p) (*get_elf_backend_data (dynobj)->s->swap_dyn_out) (dynobj, &dyn, b); } } { asection *s; Elf32_compact_rel cpt; if (SGI_COMPAT (output_bfd)) { /* Write .compact_rel section out. */ s = bfd_get_section_by_name (dynobj, ".compact_rel"); if (s != NULL) { cpt.id1 = 1; cpt.num = s->reloc_count; cpt.id2 = 2; cpt.offset = (s->output_section->filepos + sizeof (Elf32_External_compact_rel)); cpt.reserved0 = 0; cpt.reserved1 = 0; bfd_elf32_swap_compact_rel_out (output_bfd, &cpt, ((Elf32_External_compact_rel *) s->contents)); /* Clean up a dummy stub function entry in .text. */ s = bfd_get_section_by_name (dynobj, MIPS_ELF_STUB_SECTION_NAME (dynobj)); if (s != NULL) { file_ptr dummy_offset; BFD_ASSERT (s->size >= MIPS_FUNCTION_STUB_SIZE); dummy_offset = s->size - MIPS_FUNCTION_STUB_SIZE; memset (s->contents + dummy_offset, 0, MIPS_FUNCTION_STUB_SIZE); } } } /* We need to sort the entries of the dynamic relocation section. */ s = mips_elf_rel_dyn_section (dynobj, FALSE); if (s != NULL && s->size > (bfd_vma)2 * MIPS_ELF_REL_SIZE (output_bfd)) { reldyn_sorting_bfd = output_bfd; if (ABI_64_P (output_bfd)) qsort ((Elf64_External_Rel *) s->contents + 1, s->reloc_count - 1, sizeof (Elf64_Mips_External_Rel), sort_dynamic_relocs_64); else qsort ((Elf32_External_Rel *) s->contents + 1, s->reloc_count - 1, sizeof (Elf32_External_Rel), sort_dynamic_relocs); } } return TRUE; } /* Set ABFD's EF_MIPS_ARCH and EF_MIPS_MACH flags. */ static void mips_set_isa_flags (bfd *abfd) { flagword val; switch (bfd_get_mach (abfd)) { default: case bfd_mach_mips3000: val = E_MIPS_ARCH_1; break; case bfd_mach_mips3900: val = E_MIPS_ARCH_1 | E_MIPS_MACH_3900; break; case bfd_mach_mips6000: val = E_MIPS_ARCH_2; break; case bfd_mach_mips4000: case bfd_mach_mips4300: case bfd_mach_mips4400: case bfd_mach_mips4600: val = E_MIPS_ARCH_3; break; case bfd_mach_mips4010: val = E_MIPS_ARCH_3 | E_MIPS_MACH_4010; break; case bfd_mach_mips4100: val = E_MIPS_ARCH_3 | E_MIPS_MACH_4100; break; case bfd_mach_mips4111: val = E_MIPS_ARCH_3 | E_MIPS_MACH_4111; break; case bfd_mach_mips4120: val = E_MIPS_ARCH_3 | E_MIPS_MACH_4120; break; case bfd_mach_mips4650: val = E_MIPS_ARCH_3 | E_MIPS_MACH_4650; break; case bfd_mach_mips5400: val = E_MIPS_ARCH_4 | E_MIPS_MACH_5400; break; case bfd_mach_mips5500: val = E_MIPS_ARCH_4 | E_MIPS_MACH_5500; break; case bfd_mach_mips9000: val = E_MIPS_ARCH_4 | E_MIPS_MACH_9000; break; case bfd_mach_mips5000: case bfd_mach_mips7000: case bfd_mach_mips8000: case bfd_mach_mips10000: case bfd_mach_mips12000: val = E_MIPS_ARCH_4; break; case bfd_mach_mips5: val = E_MIPS_ARCH_5; break; case bfd_mach_mips_sb1: val = E_MIPS_ARCH_64 | E_MIPS_MACH_SB1; break; case bfd_mach_mipsisa32: val = E_MIPS_ARCH_32; break; case bfd_mach_mipsisa64: val = E_MIPS_ARCH_64; break; case bfd_mach_mipsisa32r2: val = E_MIPS_ARCH_32R2; break; case bfd_mach_mipsisa64r2: val = E_MIPS_ARCH_64R2; break; } elf_elfheader (abfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH); elf_elfheader (abfd)->e_flags |= val; } /* The final processing done just before writing out a MIPS ELF object file. This gets the MIPS architecture right based on the machine number. This is used by both the 32-bit and the 64-bit ABI. */ void _bfd_mips_elf_final_write_processing (bfd *abfd, bfd_boolean linker ATTRIBUTE_UNUSED) { unsigned int i; Elf_Internal_Shdr **hdrpp; const char *name; asection *sec; /* Keep the existing EF_MIPS_MACH and EF_MIPS_ARCH flags if the former is nonzero. This is for compatibility with old objects, which used a combination of a 32-bit EF_MIPS_ARCH and a 64-bit EF_MIPS_MACH. */ if ((elf_elfheader (abfd)->e_flags & EF_MIPS_MACH) == 0) mips_set_isa_flags (abfd); /* Set the sh_info field for .gptab sections and other appropriate info for each special section. */ for (i = 1, hdrpp = elf_elfsections (abfd) + 1; i < elf_numsections (abfd); i++, hdrpp++) { switch ((*hdrpp)->sh_type) { case SHT_MIPS_MSYM: case SHT_MIPS_LIBLIST: sec = bfd_get_section_by_name (abfd, ".dynstr"); if (sec != NULL) (*hdrpp)->sh_link = elf_section_data (sec)->this_idx; break; case SHT_MIPS_GPTAB: BFD_ASSERT ((*hdrpp)->bfd_section != NULL); name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section); BFD_ASSERT (name != NULL && strncmp (name, ".gptab.", sizeof ".gptab." - 1) == 0); sec = bfd_get_section_by_name (abfd, name + sizeof ".gptab" - 1); BFD_ASSERT (sec != NULL); (*hdrpp)->sh_info = elf_section_data (sec)->this_idx; break; case SHT_MIPS_CONTENT: BFD_ASSERT ((*hdrpp)->bfd_section != NULL); name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section); BFD_ASSERT (name != NULL && strncmp (name, ".MIPS.content", sizeof ".MIPS.content" - 1) == 0); sec = bfd_get_section_by_name (abfd, name + sizeof ".MIPS.content" - 1); BFD_ASSERT (sec != NULL); (*hdrpp)->sh_link = elf_section_data (sec)->this_idx; break; case SHT_MIPS_SYMBOL_LIB: sec = bfd_get_section_by_name (abfd, ".dynsym"); if (sec != NULL) (*hdrpp)->sh_link = elf_section_data (sec)->this_idx; sec = bfd_get_section_by_name (abfd, ".liblist"); if (sec != NULL) (*hdrpp)->sh_info = elf_section_data (sec)->this_idx; break; case SHT_MIPS_EVENTS: BFD_ASSERT ((*hdrpp)->bfd_section != NULL); name = bfd_get_section_name (abfd, (*hdrpp)->bfd_section); BFD_ASSERT (name != NULL); if (strncmp (name, ".MIPS.events", sizeof ".MIPS.events" - 1) == 0) sec = bfd_get_section_by_name (abfd, name + sizeof ".MIPS.events" - 1); else { BFD_ASSERT (strncmp (name, ".MIPS.post_rel", sizeof ".MIPS.post_rel" - 1) == 0); sec = bfd_get_section_by_name (abfd, (name + sizeof ".MIPS.post_rel" - 1)); } BFD_ASSERT (sec != NULL); (*hdrpp)->sh_link = elf_section_data (sec)->this_idx; break; } } } /* When creating an IRIX5 executable, we need REGINFO and RTPROC segments. */ int _bfd_mips_elf_additional_program_headers (bfd *abfd) { asection *s; int ret = 0; /* See if we need a PT_MIPS_REGINFO segment. */ s = bfd_get_section_by_name (abfd, ".reginfo"); if (s && (s->flags & SEC_LOAD)) ++ret; /* See if we need a PT_MIPS_OPTIONS segment. */ if (IRIX_COMPAT (abfd) == ict_irix6 && bfd_get_section_by_name (abfd, MIPS_ELF_OPTIONS_SECTION_NAME (abfd))) ++ret; /* See if we need a PT_MIPS_RTPROC segment. */ if (IRIX_COMPAT (abfd) == ict_irix5 && bfd_get_section_by_name (abfd, ".dynamic") && bfd_get_section_by_name (abfd, ".mdebug")) ++ret; return ret; } /* Modify the segment map for an IRIX5 executable. */ bfd_boolean _bfd_mips_elf_modify_segment_map (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED) { asection *s; struct elf_segment_map *m, **pm; bfd_size_type amt; /* If there is a .reginfo section, we need a PT_MIPS_REGINFO segment. */ s = bfd_get_section_by_name (abfd, ".reginfo"); if (s != NULL && (s->flags & SEC_LOAD) != 0) { for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next) if (m->p_type == PT_MIPS_REGINFO) break; if (m == NULL) { amt = sizeof *m; m = bfd_zalloc (abfd, amt); if (m == NULL) return FALSE; m->p_type = PT_MIPS_REGINFO; m->count = 1; m->sections[0] = s; /* We want to put it after the PHDR and INTERP segments. */ pm = &elf_tdata (abfd)->segment_map; while (*pm != NULL && ((*pm)->p_type == PT_PHDR || (*pm)->p_type == PT_INTERP)) pm = &(*pm)->next; m->next = *pm; *pm = m; } } /* For IRIX 6, we don't have .mdebug sections, nor does anything but .dynamic end up in PT_DYNAMIC. However, we do have to insert a PT_MIPS_OPTIONS segment immediately following the program header table. */ if (NEWABI_P (abfd) /* On non-IRIX6 new abi, we'll have already created a segment for this section, so don't create another. I'm not sure this is not also the case for IRIX 6, but I can't test it right now. */ && IRIX_COMPAT (abfd) == ict_irix6) { for (s = abfd->sections; s; s = s->next) if (elf_section_data (s)->this_hdr.sh_type == SHT_MIPS_OPTIONS) break; if (s) { struct elf_segment_map *options_segment; pm = &elf_tdata (abfd)->segment_map; while (*pm != NULL && ((*pm)->p_type == PT_PHDR || (*pm)->p_type == PT_INTERP)) pm = &(*pm)->next; amt = sizeof (struct elf_segment_map); options_segment = bfd_zalloc (abfd, amt); options_segment->next = *pm; options_segment->p_type = PT_MIPS_OPTIONS; options_segment->p_flags = PF_R; options_segment->p_flags_valid = TRUE; options_segment->count = 1; options_segment->sections[0] = s; *pm = options_segment; } } else { if (IRIX_COMPAT (abfd) == ict_irix5) { /* If there are .dynamic and .mdebug sections, we make a room for the RTPROC header. FIXME: Rewrite without section names. */ if (bfd_get_section_by_name (abfd, ".interp") == NULL && bfd_get_section_by_name (abfd, ".dynamic") != NULL && bfd_get_section_by_name (abfd, ".mdebug") != NULL) { for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next) if (m->p_type == PT_MIPS_RTPROC) break; if (m == NULL) { amt = sizeof *m; m = bfd_zalloc (abfd, amt); if (m == NULL) return FALSE; m->p_type = PT_MIPS_RTPROC; s = bfd_get_section_by_name (abfd, ".rtproc"); if (s == NULL) { m->count = 0; m->p_flags = 0; m->p_flags_valid = 1; } else { m->count = 1; m->sections[0] = s; } /* We want to put it after the DYNAMIC segment. */ pm = &elf_tdata (abfd)->segment_map; while (*pm != NULL && (*pm)->p_type != PT_DYNAMIC) pm = &(*pm)->next; if (*pm != NULL) pm = &(*pm)->next; m->next = *pm; *pm = m; } } } /* On IRIX5, the PT_DYNAMIC segment includes the .dynamic, .dynstr, .dynsym, and .hash sections, and everything in between. */ for (pm = &elf_tdata (abfd)->segment_map; *pm != NULL; pm = &(*pm)->next) if ((*pm)->p_type == PT_DYNAMIC) break; m = *pm; if (m != NULL && IRIX_COMPAT (abfd) == ict_none) { /* For a normal mips executable the permissions for the PT_DYNAMIC segment are read, write and execute. We do that here since the code in elf.c sets only the read permission. This matters sometimes for the dynamic linker. */ if (bfd_get_section_by_name (abfd, ".dynamic") != NULL) { m->p_flags = PF_R | PF_W | PF_X; m->p_flags_valid = 1; } } if (m != NULL && m->count == 1 && strcmp (m->sections[0]->name, ".dynamic") == 0) { static const char *sec_names[] = { ".dynamic", ".dynstr", ".dynsym", ".hash" }; bfd_vma low, high; unsigned int i, c; struct elf_segment_map *n; low = ~(bfd_vma) 0; high = 0; for (i = 0; i < sizeof sec_names / sizeof sec_names[0]; i++) { s = bfd_get_section_by_name (abfd, sec_names[i]); if (s != NULL && (s->flags & SEC_LOAD) != 0) { bfd_size_type sz; if (low > s->vma) low = s->vma; sz = s->size; if (high < s->vma + sz) high = s->vma + sz; } } c = 0; for (s = abfd->sections; s != NULL; s = s->next) if ((s->flags & SEC_LOAD) != 0 && s->vma >= low && s->vma + s->size <= high) ++c; amt = sizeof *n + (bfd_size_type) (c - 1) * sizeof (asection *); n = bfd_zalloc (abfd, amt); if (n == NULL) return FALSE; *n = *m; n->count = c; i = 0; for (s = abfd->sections; s != NULL; s = s->next) { if ((s->flags & SEC_LOAD) != 0 && s->vma >= low && s->vma + s->size <= high) { n->sections[i] = s; ++i; } } *pm = n; } } return TRUE; } /* Return the section that should be marked against GC for a given relocation. */ asection * _bfd_mips_elf_gc_mark_hook (asection *sec, struct bfd_link_info *info ATTRIBUTE_UNUSED, Elf_Internal_Rela *rel, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { /* ??? Do mips16 stub sections need to be handled special? */ if (h != NULL) { switch (ELF_R_TYPE (sec->owner, rel->r_info)) { case R_MIPS_GNU_VTINHERIT: case R_MIPS_GNU_VTENTRY: break; default: switch (h->root.type) { case bfd_link_hash_defined: case bfd_link_hash_defweak: return h->root.u.def.section; case bfd_link_hash_common: return h->root.u.c.p->section; default: break; } } } else return bfd_section_from_elf_index (sec->owner, sym->st_shndx); return NULL; } /* Update the got entry reference counts for the section being removed. */ bfd_boolean _bfd_mips_elf_gc_sweep_hook (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info ATTRIBUTE_UNUSED, asection *sec ATTRIBUTE_UNUSED, const Elf_Internal_Rela *relocs ATTRIBUTE_UNUSED) { #if 0 Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; bfd_signed_vma *local_got_refcounts; const Elf_Internal_Rela *rel, *relend; unsigned long r_symndx; struct elf_link_hash_entry *h; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); local_got_refcounts = elf_local_got_refcounts (abfd); relend = relocs + sec->reloc_count; for (rel = relocs; rel < relend; rel++) switch (ELF_R_TYPE (abfd, rel->r_info)) { case R_MIPS_GOT16: case R_MIPS_CALL16: case R_MIPS_CALL_HI16: case R_MIPS_CALL_LO16: case R_MIPS_GOT_HI16: case R_MIPS_GOT_LO16: case R_MIPS_GOT_DISP: case R_MIPS_GOT_PAGE: case R_MIPS_GOT_OFST: /* ??? It would seem that the existing MIPS code does no sort of reference counting or whatnot on its GOT and PLT entries, so it is not possible to garbage collect them at this time. */ break; default: break; } #endif return TRUE; } /* Copy data from a MIPS ELF indirect symbol to its direct symbol, hiding the old indirect symbol. Process additional relocation information. Also called for weakdefs, in which case we just let _bfd_elf_link_hash_copy_indirect copy the flags for us. */ void _bfd_mips_elf_copy_indirect_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *dir, struct elf_link_hash_entry *ind) { struct mips_elf_link_hash_entry *dirmips, *indmips; _bfd_elf_link_hash_copy_indirect (info, dir, ind); if (ind->root.type != bfd_link_hash_indirect) return; dirmips = (struct mips_elf_link_hash_entry *) dir; indmips = (struct mips_elf_link_hash_entry *) ind; dirmips->possibly_dynamic_relocs += indmips->possibly_dynamic_relocs; if (indmips->readonly_reloc) dirmips->readonly_reloc = TRUE; if (indmips->no_fn_stub) dirmips->no_fn_stub = TRUE; if (dirmips->tls_type == 0) dirmips->tls_type = indmips->tls_type; } void _bfd_mips_elf_hide_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *entry, bfd_boolean force_local) { bfd *dynobj; asection *got; struct mips_got_info *g; struct mips_elf_link_hash_entry *h; h = (struct mips_elf_link_hash_entry *) entry; if (h->forced_local) return; h->forced_local = force_local; dynobj = elf_hash_table (info)->dynobj; if (dynobj != NULL && force_local && h->root.type != STT_TLS && (got = mips_elf_got_section (dynobj, FALSE)) != NULL && (g = mips_elf_section_data (got)->u.got_info) != NULL) { if (g->next) { struct mips_got_entry e; struct mips_got_info *gg = g; /* Since we're turning what used to be a global symbol into a local one, bump up the number of local entries of each GOT that had an entry for it. This will automatically decrease the number of global entries, since global_gotno is actually the upper limit of global entries. */ e.abfd = dynobj; e.symndx = -1; e.d.h = h; e.tls_type = 0; for (g = g->next; g != gg; g = g->next) if (htab_find (g->got_entries, &e)) { BFD_ASSERT (g->global_gotno > 0); g->local_gotno++; g->global_gotno--; } /* If this was a global symbol forced into the primary GOT, we no longer need an entry for it. We can't release the entry at this point, but we must at least stop counting it as one of the symbols that required a forced got entry. */ if (h->root.got.offset == 2) { BFD_ASSERT (gg->assigned_gotno > 0); gg->assigned_gotno--; } } else if (g->global_gotno == 0 && g->global_gotsym == NULL) /* If we haven't got through GOT allocation yet, just bump up the number of local entries, as this symbol won't be counted as global. */ g->local_gotno++; else if (h->root.got.offset == 1) { /* If we're past non-multi-GOT allocation and this symbol had been marked for a global got entry, give it a local entry instead. */ BFD_ASSERT (g->global_gotno > 0); g->local_gotno++; g->global_gotno--; } } _bfd_elf_link_hash_hide_symbol (info, &h->root, force_local); } #define PDR_SIZE 32 bfd_boolean _bfd_mips_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie, struct bfd_link_info *info) { asection *o; bfd_boolean ret = FALSE; unsigned char *tdata; size_t i, skip; o = bfd_get_section_by_name (abfd, ".pdr"); if (! o) return FALSE; if (o->size == 0) return FALSE; if (o->size % PDR_SIZE != 0) return FALSE; if (o->output_section != NULL && bfd_is_abs_section (o->output_section)) return FALSE; tdata = bfd_zmalloc (o->size / PDR_SIZE); if (! tdata) return FALSE; cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL, info->keep_memory); if (!cookie->rels) { free (tdata); return FALSE; } cookie->rel = cookie->rels; cookie->relend = cookie->rels + o->reloc_count; for (i = 0, skip = 0; i < o->size / PDR_SIZE; i ++) { if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie)) { tdata[i] = 1; skip ++; } } if (skip != 0) { mips_elf_section_data (o)->u.tdata = tdata; o->size -= skip * PDR_SIZE; ret = TRUE; } else free (tdata); if (! info->keep_memory) free (cookie->rels); return ret; } bfd_boolean _bfd_mips_elf_ignore_discarded_relocs (asection *sec) { if (strcmp (sec->name, ".pdr") == 0) return TRUE; return FALSE; } bfd_boolean _bfd_mips_elf_write_section (bfd *output_bfd, asection *sec, bfd_byte *contents) { bfd_byte *to, *from, *end; int i; if (strcmp (sec->name, ".pdr") != 0) return FALSE; if (mips_elf_section_data (sec)->u.tdata == NULL) return FALSE; to = contents; end = contents + sec->size; for (from = contents, i = 0; from < end; from += PDR_SIZE, i++) { if ((mips_elf_section_data (sec)->u.tdata)[i] == 1) continue; if (to != from) memcpy (to, from, PDR_SIZE); to += PDR_SIZE; } bfd_set_section_contents (output_bfd, sec->output_section, contents, sec->output_offset, sec->size); return TRUE; } /* MIPS ELF uses a special find_nearest_line routine in order the handle the ECOFF debugging information. */ struct mips_elf_find_line { struct ecoff_debug_info d; struct ecoff_find_line i; }; bfd_boolean _bfd_mips_elf_find_nearest_line (bfd *abfd, asection *section, asymbol **symbols, bfd_vma offset, const char **filename_ptr, const char **functionname_ptr, unsigned int *line_ptr) { asection *msec; if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset, filename_ptr, functionname_ptr, line_ptr)) return TRUE; if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset, filename_ptr, functionname_ptr, line_ptr, ABI_64_P (abfd) ? 8 : 0, &elf_tdata (abfd)->dwarf2_find_line_info)) return TRUE; msec = bfd_get_section_by_name (abfd, ".mdebug"); if (msec != NULL) { flagword origflags; struct mips_elf_find_line *fi; const struct ecoff_debug_swap * const swap = get_elf_backend_data (abfd)->elf_backend_ecoff_debug_swap; /* If we are called during a link, mips_elf_final_link may have cleared the SEC_HAS_CONTENTS field. We force it back on here if appropriate (which it normally will be). */ origflags = msec->flags; if (elf_section_data (msec)->this_hdr.sh_type != SHT_NOBITS) msec->flags |= SEC_HAS_CONTENTS; fi = elf_tdata (abfd)->find_line_info; if (fi == NULL) { bfd_size_type external_fdr_size; char *fraw_src; char *fraw_end; struct fdr *fdr_ptr; bfd_size_type amt = sizeof (struct mips_elf_find_line); fi = bfd_zalloc (abfd, amt); if (fi == NULL) { msec->flags = origflags; return FALSE; } if (! _bfd_mips_elf_read_ecoff_info (abfd, msec, &fi->d)) { msec->flags = origflags; return FALSE; } /* Swap in the FDR information. */ amt = fi->d.symbolic_header.ifdMax * sizeof (struct fdr); fi->d.fdr = bfd_alloc (abfd, amt); if (fi->d.fdr == NULL) { msec->flags = origflags; return FALSE; } external_fdr_size = swap->external_fdr_size; fdr_ptr = fi->d.fdr; fraw_src = (char *) fi->d.external_fdr; fraw_end = (fraw_src + fi->d.symbolic_header.ifdMax * external_fdr_size); for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++) (*swap->swap_fdr_in) (abfd, fraw_src, fdr_ptr); elf_tdata (abfd)->find_line_info = fi; /* Note that we don't bother to ever free this information. find_nearest_line is either called all the time, as in objdump -l, so the information should be saved, or it is rarely called, as in ld error messages, so the memory wasted is unimportant. Still, it would probably be a good idea for free_cached_info to throw it away. */ } if (_bfd_ecoff_locate_line (abfd, section, offset, &fi->d, swap, &fi->i, filename_ptr, functionname_ptr, line_ptr)) { msec->flags = origflags; return TRUE; } msec->flags = origflags; } /* Fall back on the generic ELF find_nearest_line routine. */ return _bfd_elf_find_nearest_line (abfd, section, symbols, offset, filename_ptr, functionname_ptr, line_ptr); } bfd_boolean _bfd_mips_elf_find_inliner_info (bfd *abfd, const char **filename_ptr, const char **functionname_ptr, unsigned int *line_ptr) { bfd_boolean found; found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr, functionname_ptr, line_ptr, & elf_tdata (abfd)->dwarf2_find_line_info); return found; } /* When are writing out the .options or .MIPS.options section, remember the bytes we are writing out, so that we can install the GP value in the section_processing routine. */ bfd_boolean _bfd_mips_elf_set_section_contents (bfd *abfd, sec_ptr section, const void *location, file_ptr offset, bfd_size_type count) { if (MIPS_ELF_OPTIONS_SECTION_NAME_P (section->name)) { bfd_byte *c; if (elf_section_data (section) == NULL) { bfd_size_type amt = sizeof (struct bfd_elf_section_data); section->used_by_bfd = bfd_zalloc (abfd, amt); if (elf_section_data (section) == NULL) return FALSE; } c = mips_elf_section_data (section)->u.tdata; if (c == NULL) { c = bfd_zalloc (abfd, section->size); if (c == NULL) return FALSE; mips_elf_section_data (section)->u.tdata = c; } memcpy (c + offset, location, count); } return _bfd_elf_set_section_contents (abfd, section, location, offset, count); } /* This is almost identical to bfd_generic_get_... except that some MIPS relocations need to be handled specially. Sigh. */ bfd_byte * _bfd_elf_mips_get_relocated_section_contents (bfd *abfd, struct bfd_link_info *link_info, struct bfd_link_order *link_order, bfd_byte *data, bfd_boolean relocatable, asymbol **symbols) { /* Get enough memory to hold the stuff */ bfd *input_bfd = link_order->u.indirect.section->owner; asection *input_section = link_order->u.indirect.section; bfd_size_type sz; long reloc_size = bfd_get_reloc_upper_bound (input_bfd, input_section); arelent **reloc_vector = NULL; long reloc_count; if (reloc_size < 0) goto error_return; reloc_vector = bfd_malloc (reloc_size); if (reloc_vector == NULL && reloc_size != 0) goto error_return; /* read in the section */ sz = input_section->rawsize ? input_section->rawsize : input_section->size; if (!bfd_get_section_contents (input_bfd, input_section, data, 0, sz)) goto error_return; reloc_count = bfd_canonicalize_reloc (input_bfd, input_section, reloc_vector, symbols); if (reloc_count < 0) goto error_return; if (reloc_count > 0) { arelent **parent; /* for mips */ int gp_found; bfd_vma gp = 0x12345678; /* initialize just to shut gcc up */ { struct bfd_hash_entry *h; struct bfd_link_hash_entry *lh; /* Skip all this stuff if we aren't mixing formats. */ if (abfd && input_bfd && abfd->xvec == input_bfd->xvec) lh = 0; else { h = bfd_hash_lookup (&link_info->hash->table, "_gp", FALSE, FALSE); lh = (struct bfd_link_hash_entry *) h; } lookup: if (lh) { switch (lh->type) { case bfd_link_hash_undefined: case bfd_link_hash_undefweak: case bfd_link_hash_common: gp_found = 0; break; case bfd_link_hash_defined: case bfd_link_hash_defweak: gp_found = 1; gp = lh->u.def.value; break; case bfd_link_hash_indirect: case bfd_link_hash_warning: lh = lh->u.i.link; /* @@FIXME ignoring warning for now */ goto lookup; case bfd_link_hash_new: default: abort (); } } else gp_found = 0; } /* end mips */ for (parent = reloc_vector; *parent != NULL; parent++) { char *error_message = NULL; bfd_reloc_status_type r; /* Specific to MIPS: Deal with relocation types that require knowing the gp of the output bfd. */ asymbol *sym = *(*parent)->sym_ptr_ptr; /* If we've managed to find the gp and have a special function for the relocation then go ahead, else default to the generic handling. */ if (gp_found && (*parent)->howto->special_function == _bfd_mips_elf32_gprel16_reloc) r = _bfd_mips_elf_gprel16_with_gp (input_bfd, sym, *parent, input_section, relocatable, data, gp); else r = bfd_perform_relocation (input_bfd, *parent, data, input_section, relocatable ? abfd : NULL, &error_message); if (relocatable) { asection *os = input_section->output_section; /* A partial link, so keep the relocs */ os->orelocation[os->reloc_count] = *parent; os->reloc_count++; } if (r != bfd_reloc_ok) { switch (r) { case bfd_reloc_undefined: if (!((*link_info->callbacks->undefined_symbol) (link_info, bfd_asymbol_name (*(*parent)->sym_ptr_ptr), input_bfd, input_section, (*parent)->address, TRUE))) goto error_return; break; case bfd_reloc_dangerous: BFD_ASSERT (error_message != NULL); if (!((*link_info->callbacks->reloc_dangerous) (link_info, error_message, input_bfd, input_section, (*parent)->address))) goto error_return; break; case bfd_reloc_overflow: if (!((*link_info->callbacks->reloc_overflow) (link_info, NULL, bfd_asymbol_name (*(*parent)->sym_ptr_ptr), (*parent)->howto->name, (*parent)->addend, input_bfd, input_section, (*parent)->address))) goto error_return; break; case bfd_reloc_outofrange: default: abort (); break; } } } } if (reloc_vector != NULL) free (reloc_vector); return data; error_return: if (reloc_vector != NULL) free (reloc_vector); return NULL; } /* Create a MIPS ELF linker hash table. */ struct bfd_link_hash_table * _bfd_mips_elf_link_hash_table_create (bfd *abfd) { struct mips_elf_link_hash_table *ret; bfd_size_type amt = sizeof (struct mips_elf_link_hash_table); ret = bfd_malloc (amt); if (ret == NULL) return NULL; if (! _bfd_elf_link_hash_table_init (&ret->root, abfd, mips_elf_link_hash_newfunc)) { free (ret); return NULL; } #if 0 /* We no longer use this. */ for (i = 0; i < SIZEOF_MIPS_DYNSYM_SECNAMES; i++) ret->dynsym_sec_strindex[i] = (bfd_size_type) -1; #endif ret->procedure_count = 0; ret->compact_rel_size = 0; ret->use_rld_obj_head = FALSE; ret->rld_value = 0; ret->mips16_stubs_seen = FALSE; return &ret->root.root; } /* We need to use a special link routine to handle the .reginfo and the .mdebug sections. We need to merge all instances of these sections together, not write them all out sequentially. */ bfd_boolean _bfd_mips_elf_final_link (bfd *abfd, struct bfd_link_info *info) { asection *o; struct bfd_link_order *p; asection *reginfo_sec, *mdebug_sec, *gptab_data_sec, *gptab_bss_sec; asection *rtproc_sec; Elf32_RegInfo reginfo; struct ecoff_debug_info debug; const struct elf_backend_data *bed = get_elf_backend_data (abfd); const struct ecoff_debug_swap *swap = bed->elf_backend_ecoff_debug_swap; HDRR *symhdr = &debug.symbolic_header; void *mdebug_handle = NULL; asection *s; EXTR esym; unsigned int i; bfd_size_type amt; static const char * const secname[] = { ".text", ".init", ".fini", ".data", ".rodata", ".sdata", ".sbss", ".bss" }; static const int sc[] = { scText, scInit, scFini, scData, scRData, scSData, scSBss, scBss }; /* We'd carefully arranged the dynamic symbol indices, and then the generic size_dynamic_sections renumbered them out from under us. Rather than trying somehow to prevent the renumbering, just do the sort again. */ if (elf_hash_table (info)->dynamic_sections_created) { bfd *dynobj; asection *got; struct mips_got_info *g; bfd_size_type dynsecsymcount; /* When we resort, we must tell mips_elf_sort_hash_table what the lowest index it may use is. That's the number of section symbols we're going to add. The generic ELF linker only adds these symbols when building a shared object. Note that we count the sections after (possibly) removing the .options section above. */ dynsecsymcount = 0; if (info->shared) { asection * p; for (p = abfd->sections; p ; p = p->next) if ((p->flags & SEC_EXCLUDE) == 0 && (p->flags & SEC_ALLOC) != 0 && !(*bed->elf_backend_omit_section_dynsym) (abfd, info, p)) ++ dynsecsymcount; } if (! mips_elf_sort_hash_table (info, dynsecsymcount + 1)) return FALSE; /* Make sure we didn't grow the global .got region. */ dynobj = elf_hash_table (info)->dynobj; got = mips_elf_got_section (dynobj, FALSE); g = mips_elf_section_data (got)->u.got_info; if (g->global_gotsym != NULL) BFD_ASSERT ((elf_hash_table (info)->dynsymcount - g->global_gotsym->dynindx) <= g->global_gotno); } /* Get a value for the GP register. */ if (elf_gp (abfd) == 0) { struct bfd_link_hash_entry *h; h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE); if (h != NULL && h->type == bfd_link_hash_defined) elf_gp (abfd) = (h->u.def.value + h->u.def.section->output_section->vma + h->u.def.section->output_offset); else if (info->relocatable) { bfd_vma lo = MINUS_ONE; /* Find the GP-relative section with the lowest offset. */ for (o = abfd->sections; o != NULL; o = o->next) if (o->vma < lo && (elf_section_data (o)->this_hdr.sh_flags & SHF_MIPS_GPREL)) lo = o->vma; /* And calculate GP relative to that. */ elf_gp (abfd) = lo + ELF_MIPS_GP_OFFSET (abfd); } else { /* If the relocate_section function needs to do a reloc involving the GP value, it should make a reloc_dangerous callback to warn that GP is not defined. */ } } /* Go through the sections and collect the .reginfo and .mdebug information. */ reginfo_sec = NULL; mdebug_sec = NULL; gptab_data_sec = NULL; gptab_bss_sec = NULL; for (o = abfd->sections; o != NULL; o = o->next) { if (strcmp (o->name, ".reginfo") == 0) { memset (&reginfo, 0, sizeof reginfo); /* We have found the .reginfo section in the output file. Look through all the link_orders comprising it and merge the information together. */ for (p = o->map_head.link_order; p != NULL; p = p->next) { asection *input_section; bfd *input_bfd; Elf32_External_RegInfo ext; Elf32_RegInfo sub; if (p->type != bfd_indirect_link_order) { if (p->type == bfd_data_link_order) continue; abort (); } input_section = p->u.indirect.section; input_bfd = input_section->owner; if (! bfd_get_section_contents (input_bfd, input_section, &ext, 0, sizeof ext)) return FALSE; bfd_mips_elf32_swap_reginfo_in (input_bfd, &ext, &sub); reginfo.ri_gprmask |= sub.ri_gprmask; reginfo.ri_cprmask[0] |= sub.ri_cprmask[0]; reginfo.ri_cprmask[1] |= sub.ri_cprmask[1]; reginfo.ri_cprmask[2] |= sub.ri_cprmask[2]; reginfo.ri_cprmask[3] |= sub.ri_cprmask[3]; /* ri_gp_value is set by the function mips_elf32_section_processing when the section is finally written out. */ /* Hack: reset the SEC_HAS_CONTENTS flag so that elf_link_input_bfd ignores this section. */ input_section->flags &= ~SEC_HAS_CONTENTS; } /* Size has been set in _bfd_mips_elf_always_size_sections. */ BFD_ASSERT(o->size == sizeof (Elf32_External_RegInfo)); /* Skip this section later on (I don't think this currently matters, but someday it might). */ o->map_head.link_order = NULL; reginfo_sec = o; } if (strcmp (o->name, ".mdebug") == 0) { struct extsym_info einfo; bfd_vma last; /* We have found the .mdebug section in the output file. Look through all the link_orders comprising it and merge the information together. */ symhdr->magic = swap->sym_magic; /* FIXME: What should the version stamp be? */ symhdr->vstamp = 0; symhdr->ilineMax = 0; symhdr->cbLine = 0; symhdr->idnMax = 0; symhdr->ipdMax = 0; symhdr->isymMax = 0; symhdr->ioptMax = 0; symhdr->iauxMax = 0; symhdr->issMax = 0; symhdr->issExtMax = 0; symhdr->ifdMax = 0; symhdr->crfd = 0; symhdr->iextMax = 0; /* We accumulate the debugging information itself in the debug_info structure. */ debug.line = NULL; debug.external_dnr = NULL; debug.external_pdr = NULL; debug.external_sym = NULL; debug.external_opt = NULL; debug.external_aux = NULL; debug.ss = NULL; debug.ssext = debug.ssext_end = NULL; debug.external_fdr = NULL; debug.external_rfd = NULL; debug.external_ext = debug.external_ext_end = NULL; mdebug_handle = bfd_ecoff_debug_init (abfd, &debug, swap, info); if (mdebug_handle == NULL) return FALSE; esym.jmptbl = 0; esym.cobol_main = 0; esym.weakext = 0; esym.reserved = 0; esym.ifd = ifdNil; esym.asym.iss = issNil; esym.asym.st = stLocal; esym.asym.reserved = 0; esym.asym.index = indexNil; last = 0; for (i = 0; i < sizeof (secname) / sizeof (secname[0]); i++) { esym.asym.sc = sc[i]; s = bfd_get_section_by_name (abfd, secname[i]); if (s != NULL) { esym.asym.value = s->vma; last = s->vma + s->size; } else esym.asym.value = last; if (!bfd_ecoff_debug_one_external (abfd, &debug, swap, secname[i], &esym)) return FALSE; } for (p = o->map_head.link_order; p != NULL; p = p->next) { asection *input_section; bfd *input_bfd; const struct ecoff_debug_swap *input_swap; struct ecoff_debug_info input_debug; char *eraw_src; char *eraw_end; if (p->type != bfd_indirect_link_order) { if (p->type == bfd_data_link_order) continue; abort (); } input_section = p->u.indirect.section; input_bfd = input_section->owner; if (bfd_get_flavour (input_bfd) != bfd_target_elf_flavour || (get_elf_backend_data (input_bfd) ->elf_backend_ecoff_debug_swap) == NULL) { /* I don't know what a non MIPS ELF bfd would be doing with a .mdebug section, but I don't really want to deal with it. */ continue; } input_swap = (get_elf_backend_data (input_bfd) ->elf_backend_ecoff_debug_swap); BFD_ASSERT (p->size == input_section->size); /* The ECOFF linking code expects that we have already read in the debugging information and set up an ecoff_debug_info structure, so we do that now. */ if (! _bfd_mips_elf_read_ecoff_info (input_bfd, input_section, &input_debug)) return FALSE; if (! (bfd_ecoff_debug_accumulate (mdebug_handle, abfd, &debug, swap, input_bfd, &input_debug, input_swap, info))) return FALSE; /* Loop through the external symbols. For each one with interesting information, try to find the symbol in the linker global hash table and save the information for the output external symbols. */ eraw_src = input_debug.external_ext; eraw_end = (eraw_src + (input_debug.symbolic_header.iextMax * input_swap->external_ext_size)); for (; eraw_src < eraw_end; eraw_src += input_swap->external_ext_size) { EXTR ext; const char *name; struct mips_elf_link_hash_entry *h; (*input_swap->swap_ext_in) (input_bfd, eraw_src, &ext); if (ext.asym.sc == scNil || ext.asym.sc == scUndefined || ext.asym.sc == scSUndefined) continue; name = input_debug.ssext + ext.asym.iss; h = mips_elf_link_hash_lookup (mips_elf_hash_table (info), name, FALSE, FALSE, TRUE); if (h == NULL || h->esym.ifd != -2) continue; if (ext.ifd != -1) { BFD_ASSERT (ext.ifd < input_debug.symbolic_header.ifdMax); ext.ifd = input_debug.ifdmap[ext.ifd]; } h->esym = ext; } /* Free up the information we just read. */ free (input_debug.line); free (input_debug.external_dnr); free (input_debug.external_pdr); free (input_debug.external_sym); free (input_debug.external_opt); free (input_debug.external_aux); free (input_debug.ss); free (input_debug.ssext); free (input_debug.external_fdr); free (input_debug.external_rfd); free (input_debug.external_ext); /* Hack: reset the SEC_HAS_CONTENTS flag so that elf_link_input_bfd ignores this section. */ input_section->flags &= ~SEC_HAS_CONTENTS; } if (SGI_COMPAT (abfd) && info->shared) { /* Create .rtproc section. */ rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc"); if (rtproc_sec == NULL) { flagword flags = (SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY); rtproc_sec = bfd_make_section_with_flags (abfd, ".rtproc", flags); if (rtproc_sec == NULL || ! bfd_set_section_alignment (abfd, rtproc_sec, 4)) return FALSE; } if (! mips_elf_create_procedure_table (mdebug_handle, abfd, info, rtproc_sec, &debug)) return FALSE; } /* Build the external symbol information. */ einfo.abfd = abfd; einfo.info = info; einfo.debug = &debug; einfo.swap = swap; einfo.failed = FALSE; mips_elf_link_hash_traverse (mips_elf_hash_table (info), mips_elf_output_extsym, &einfo); if (einfo.failed) return FALSE; /* Set the size of the .mdebug section. */ o->size = bfd_ecoff_debug_size (abfd, &debug, swap); /* Skip this section later on (I don't think this currently matters, but someday it might). */ o->map_head.link_order = NULL; mdebug_sec = o; } if (strncmp (o->name, ".gptab.", sizeof ".gptab." - 1) == 0) { const char *subname; unsigned int c; Elf32_gptab *tab; Elf32_External_gptab *ext_tab; unsigned int j; /* The .gptab.sdata and .gptab.sbss sections hold information describing how the small data area would change depending upon the -G switch. These sections not used in executables files. */ if (! info->relocatable) { for (p = o->map_head.link_order; p != NULL; p = p->next) { asection *input_section; if (p->type != bfd_indirect_link_order) { if (p->type == bfd_data_link_order) continue; abort (); } input_section = p->u.indirect.section; /* Hack: reset the SEC_HAS_CONTENTS flag so that elf_link_input_bfd ignores this section. */ input_section->flags &= ~SEC_HAS_CONTENTS; } /* Skip this section later on (I don't think this currently matters, but someday it might). */ o->map_head.link_order = NULL; /* Really remove the section. */ bfd_section_list_remove (abfd, o); --abfd->section_count; continue; } /* There is one gptab for initialized data, and one for uninitialized data. */ if (strcmp (o->name, ".gptab.sdata") == 0) gptab_data_sec = o; else if (strcmp (o->name, ".gptab.sbss") == 0) gptab_bss_sec = o; else { (*_bfd_error_handler) (_("%s: illegal section name `%s'"), bfd_get_filename (abfd), o->name); bfd_set_error (bfd_error_nonrepresentable_section); return FALSE; } /* The linker script always combines .gptab.data and .gptab.sdata into .gptab.sdata, and likewise for .gptab.bss and .gptab.sbss. It is possible that there is no .sdata or .sbss section in the output file, in which case we must change the name of the output section. */ subname = o->name + sizeof ".gptab" - 1; if (bfd_get_section_by_name (abfd, subname) == NULL) { if (o == gptab_data_sec) o->name = ".gptab.data"; else o->name = ".gptab.bss"; subname = o->name + sizeof ".gptab" - 1; BFD_ASSERT (bfd_get_section_by_name (abfd, subname) != NULL); } /* Set up the first entry. */ c = 1; amt = c * sizeof (Elf32_gptab); tab = bfd_malloc (amt); if (tab == NULL) return FALSE; tab[0].gt_header.gt_current_g_value = elf_gp_size (abfd); tab[0].gt_header.gt_unused = 0; /* Combine the input sections. */ for (p = o->map_head.link_order; p != NULL; p = p->next) { asection *input_section; bfd *input_bfd; bfd_size_type size; unsigned long last; bfd_size_type gpentry; if (p->type != bfd_indirect_link_order) { if (p->type == bfd_data_link_order) continue; abort (); } input_section = p->u.indirect.section; input_bfd = input_section->owner; /* Combine the gptab entries for this input section one by one. We know that the input gptab entries are sorted by ascending -G value. */ size = input_section->size; last = 0; for (gpentry = sizeof (Elf32_External_gptab); gpentry < size; gpentry += sizeof (Elf32_External_gptab)) { Elf32_External_gptab ext_gptab; Elf32_gptab int_gptab; unsigned long val; unsigned long add; bfd_boolean exact; unsigned int look; if (! (bfd_get_section_contents (input_bfd, input_section, &ext_gptab, gpentry, sizeof (Elf32_External_gptab)))) { free (tab); return FALSE; } bfd_mips_elf32_swap_gptab_in (input_bfd, &ext_gptab, &int_gptab); val = int_gptab.gt_entry.gt_g_value; add = int_gptab.gt_entry.gt_bytes - last; exact = FALSE; for (look = 1; look < c; look++) { if (tab[look].gt_entry.gt_g_value >= val) tab[look].gt_entry.gt_bytes += add; if (tab[look].gt_entry.gt_g_value == val) exact = TRUE; } if (! exact) { Elf32_gptab *new_tab; unsigned int max; /* We need a new table entry. */ amt = (bfd_size_type) (c + 1) * sizeof (Elf32_gptab); new_tab = bfd_realloc (tab, amt); if (new_tab == NULL) { free (tab); return FALSE; } tab = new_tab; tab[c].gt_entry.gt_g_value = val; tab[c].gt_entry.gt_bytes = add; /* Merge in the size for the next smallest -G value, since that will be implied by this new value. */ max = 0; for (look = 1; look < c; look++) { if (tab[look].gt_entry.gt_g_value < val && (max == 0 || (tab[look].gt_entry.gt_g_value > tab[max].gt_entry.gt_g_value))) max = look; } if (max != 0) tab[c].gt_entry.gt_bytes += tab[max].gt_entry.gt_bytes; ++c; } last = int_gptab.gt_entry.gt_bytes; } /* Hack: reset the SEC_HAS_CONTENTS flag so that elf_link_input_bfd ignores this section. */ input_section->flags &= ~SEC_HAS_CONTENTS; } /* The table must be sorted by -G value. */ if (c > 2) qsort (tab + 1, c - 1, sizeof (tab[0]), gptab_compare); /* Swap out the table. */ amt = (bfd_size_type) c * sizeof (Elf32_External_gptab); ext_tab = bfd_alloc (abfd, amt); if (ext_tab == NULL) { free (tab); return FALSE; } for (j = 0; j < c; j++) bfd_mips_elf32_swap_gptab_out (abfd, tab + j, ext_tab + j); free (tab); o->size = c * sizeof (Elf32_External_gptab); o->contents = (bfd_byte *) ext_tab; /* Skip this section later on (I don't think this currently matters, but someday it might). */ o->map_head.link_order = NULL; } } /* Invoke the regular ELF backend linker to do all the work. */ if (!bfd_elf_final_link (abfd, info)) return FALSE; /* Now write out the computed sections. */ if (reginfo_sec != NULL) { Elf32_External_RegInfo ext; bfd_mips_elf32_swap_reginfo_out (abfd, &reginfo, &ext); if (! bfd_set_section_contents (abfd, reginfo_sec, &ext, 0, sizeof ext)) return FALSE; } if (mdebug_sec != NULL) { BFD_ASSERT (abfd->output_has_begun); if (! bfd_ecoff_write_accumulated_debug (mdebug_handle, abfd, &debug, swap, info, mdebug_sec->filepos)) return FALSE; bfd_ecoff_debug_free (mdebug_handle, abfd, &debug, swap, info); } if (gptab_data_sec != NULL) { if (! bfd_set_section_contents (abfd, gptab_data_sec, gptab_data_sec->contents, 0, gptab_data_sec->size)) return FALSE; } if (gptab_bss_sec != NULL) { if (! bfd_set_section_contents (abfd, gptab_bss_sec, gptab_bss_sec->contents, 0, gptab_bss_sec->size)) return FALSE; } if (SGI_COMPAT (abfd)) { rtproc_sec = bfd_get_section_by_name (abfd, ".rtproc"); if (rtproc_sec != NULL) { if (! bfd_set_section_contents (abfd, rtproc_sec, rtproc_sec->contents, 0, rtproc_sec->size)) return FALSE; } } return TRUE; } /* Structure for saying that BFD machine EXTENSION extends BASE. */ struct mips_mach_extension { unsigned long extension, base; }; /* An array describing how BFD machines relate to one another. The entries are ordered topologically with MIPS I extensions listed last. */ static const struct mips_mach_extension mips_mach_extensions[] = { /* MIPS64 extensions. */ { bfd_mach_mipsisa64r2, bfd_mach_mipsisa64 }, { bfd_mach_mips_sb1, bfd_mach_mipsisa64 }, /* MIPS V extensions. */ { bfd_mach_mipsisa64, bfd_mach_mips5 }, /* R10000 extensions. */ { bfd_mach_mips12000, bfd_mach_mips10000 }, /* R5000 extensions. Note: the vr5500 ISA is an extension of the core vr5400 ISA, but doesn't include the multimedia stuff. It seems better to allow vr5400 and vr5500 code to be merged anyway, since many libraries will just use the core ISA. Perhaps we could add some sort of ASE flag if this ever proves a problem. */ { bfd_mach_mips5500, bfd_mach_mips5400 }, { bfd_mach_mips5400, bfd_mach_mips5000 }, /* MIPS IV extensions. */ { bfd_mach_mips5, bfd_mach_mips8000 }, { bfd_mach_mips10000, bfd_mach_mips8000 }, { bfd_mach_mips5000, bfd_mach_mips8000 }, { bfd_mach_mips7000, bfd_mach_mips8000 }, { bfd_mach_mips9000, bfd_mach_mips8000 }, /* VR4100 extensions. */ { bfd_mach_mips4120, bfd_mach_mips4100 }, { bfd_mach_mips4111, bfd_mach_mips4100 }, /* MIPS III extensions. */ { bfd_mach_mips8000, bfd_mach_mips4000 }, { bfd_mach_mips4650, bfd_mach_mips4000 }, { bfd_mach_mips4600, bfd_mach_mips4000 }, { bfd_mach_mips4400, bfd_mach_mips4000 }, { bfd_mach_mips4300, bfd_mach_mips4000 }, { bfd_mach_mips4100, bfd_mach_mips4000 }, { bfd_mach_mips4010, bfd_mach_mips4000 }, /* MIPS32 extensions. */ { bfd_mach_mipsisa32r2, bfd_mach_mipsisa32 }, /* MIPS II extensions. */ { bfd_mach_mips4000, bfd_mach_mips6000 }, { bfd_mach_mipsisa32, bfd_mach_mips6000 }, /* MIPS I extensions. */ { bfd_mach_mips6000, bfd_mach_mips3000 }, { bfd_mach_mips3900, bfd_mach_mips3000 } }; /* Return true if bfd machine EXTENSION is an extension of machine BASE. */ static bfd_boolean mips_mach_extends_p (unsigned long base, unsigned long extension) { size_t i; if (extension == base) return TRUE; if (base == bfd_mach_mipsisa32 && mips_mach_extends_p (bfd_mach_mipsisa64, extension)) return TRUE; if (base == bfd_mach_mipsisa32r2 && mips_mach_extends_p (bfd_mach_mipsisa64r2, extension)) return TRUE; for (i = 0; i < ARRAY_SIZE (mips_mach_extensions); i++) if (extension == mips_mach_extensions[i].extension) { extension = mips_mach_extensions[i].base; if (extension == base) return TRUE; } return FALSE; } /* Return true if the given ELF header flags describe a 32-bit binary. */ static bfd_boolean mips_32bit_flags_p (flagword flags) { return ((flags & EF_MIPS_32BITMODE) != 0 || (flags & EF_MIPS_ABI) == E_MIPS_ABI_O32 || (flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32 || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1 || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2 || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32 || (flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2); } /* Merge backend specific data from an object file to the output object file when linking. */ bfd_boolean _bfd_mips_elf_merge_private_bfd_data (bfd *ibfd, bfd *obfd) { flagword old_flags; flagword new_flags; bfd_boolean ok; bfd_boolean null_input_bfd = TRUE; asection *sec; /* Check if we have the same endianess */ if (! _bfd_generic_verify_endian_match (ibfd, obfd)) { (*_bfd_error_handler) (_("%B: endianness incompatible with that of the selected emulation"), ibfd); return FALSE; } if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour || bfd_get_flavour (obfd) != bfd_target_elf_flavour) return TRUE; if (strcmp (bfd_get_target (ibfd), bfd_get_target (obfd)) != 0) { (*_bfd_error_handler) (_("%B: ABI is incompatible with that of the selected emulation"), ibfd); return FALSE; } new_flags = elf_elfheader (ibfd)->e_flags; elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_NOREORDER; old_flags = elf_elfheader (obfd)->e_flags; if (! elf_flags_init (obfd)) { elf_flags_init (obfd) = TRUE; elf_elfheader (obfd)->e_flags = new_flags; elf_elfheader (obfd)->e_ident[EI_CLASS] = elf_elfheader (ibfd)->e_ident[EI_CLASS]; if (bfd_get_arch (obfd) == bfd_get_arch (ibfd) && bfd_get_arch_info (obfd)->the_default) { if (! bfd_set_arch_mach (obfd, bfd_get_arch (ibfd), bfd_get_mach (ibfd))) return FALSE; } return TRUE; } /* Check flag compatibility. */ new_flags &= ~EF_MIPS_NOREORDER; old_flags &= ~EF_MIPS_NOREORDER; /* Some IRIX 6 BSD-compatibility objects have this bit set. It doesn't seem to matter. */ new_flags &= ~EF_MIPS_XGOT; old_flags &= ~EF_MIPS_XGOT; /* MIPSpro generates ucode info in n64 objects. Again, we should just be able to ignore this. */ new_flags &= ~EF_MIPS_UCODE; old_flags &= ~EF_MIPS_UCODE; if (new_flags == old_flags) return TRUE; /* Check to see if the input BFD actually contains any sections. If not, its flags may not have been initialised either, but it cannot actually cause any incompatibility. */ for (sec = ibfd->sections; sec != NULL; sec = sec->next) { /* Ignore synthetic sections and empty .text, .data and .bss sections which are automatically generated by gas. */ if (strcmp (sec->name, ".reginfo") && strcmp (sec->name, ".mdebug") && (sec->size != 0 || (strcmp (sec->name, ".text") && strcmp (sec->name, ".data") && strcmp (sec->name, ".bss")))) { null_input_bfd = FALSE; break; } } if (null_input_bfd) return TRUE; ok = TRUE; if (((new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0) != ((old_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) != 0)) { (*_bfd_error_handler) (_("%B: warning: linking PIC files with non-PIC files"), ibfd); ok = TRUE; } if (new_flags & (EF_MIPS_PIC | EF_MIPS_CPIC)) elf_elfheader (obfd)->e_flags |= EF_MIPS_CPIC; if (! (new_flags & EF_MIPS_PIC)) elf_elfheader (obfd)->e_flags &= ~EF_MIPS_PIC; new_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC); old_flags &= ~ (EF_MIPS_PIC | EF_MIPS_CPIC); /* Compare the ISAs. */ if (mips_32bit_flags_p (old_flags) != mips_32bit_flags_p (new_flags)) { (*_bfd_error_handler) (_("%B: linking 32-bit code with 64-bit code"), ibfd); ok = FALSE; } else if (!mips_mach_extends_p (bfd_get_mach (ibfd), bfd_get_mach (obfd))) { /* OBFD's ISA isn't the same as, or an extension of, IBFD's. */ if (mips_mach_extends_p (bfd_get_mach (obfd), bfd_get_mach (ibfd))) { /* Copy the architecture info from IBFD to OBFD. Also copy the 32-bit flag (if set) so that we continue to recognise OBFD as a 32-bit binary. */ bfd_set_arch_info (obfd, bfd_get_arch_info (ibfd)); elf_elfheader (obfd)->e_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH); elf_elfheader (obfd)->e_flags |= new_flags & (EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE); /* Copy across the ABI flags if OBFD doesn't use them and if that was what caused us to treat IBFD as 32-bit. */ if ((old_flags & EF_MIPS_ABI) == 0 && mips_32bit_flags_p (new_flags) && !mips_32bit_flags_p (new_flags & ~EF_MIPS_ABI)) elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ABI; } else { /* The ISAs aren't compatible. */ (*_bfd_error_handler) (_("%B: linking %s module with previous %s modules"), ibfd, bfd_printable_name (ibfd), bfd_printable_name (obfd)); ok = FALSE; } } new_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE); old_flags &= ~(EF_MIPS_ARCH | EF_MIPS_MACH | EF_MIPS_32BITMODE); /* Compare ABIs. The 64-bit ABI does not use EF_MIPS_ABI. But, it does set EI_CLASS differently from any 32-bit ABI. */ if ((new_flags & EF_MIPS_ABI) != (old_flags & EF_MIPS_ABI) || (elf_elfheader (ibfd)->e_ident[EI_CLASS] != elf_elfheader (obfd)->e_ident[EI_CLASS])) { /* Only error if both are set (to different values). */ if (((new_flags & EF_MIPS_ABI) && (old_flags & EF_MIPS_ABI)) || (elf_elfheader (ibfd)->e_ident[EI_CLASS] != elf_elfheader (obfd)->e_ident[EI_CLASS])) { (*_bfd_error_handler) (_("%B: ABI mismatch: linking %s module with previous %s modules"), ibfd, elf_mips_abi_name (ibfd), elf_mips_abi_name (obfd)); ok = FALSE; } new_flags &= ~EF_MIPS_ABI; old_flags &= ~EF_MIPS_ABI; } /* For now, allow arbitrary mixing of ASEs (retain the union). */ if ((new_flags & EF_MIPS_ARCH_ASE) != (old_flags & EF_MIPS_ARCH_ASE)) { elf_elfheader (obfd)->e_flags |= new_flags & EF_MIPS_ARCH_ASE; new_flags &= ~ EF_MIPS_ARCH_ASE; old_flags &= ~ EF_MIPS_ARCH_ASE; } /* Warn about any other mismatches */ if (new_flags != old_flags) { (*_bfd_error_handler) (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"), ibfd, (unsigned long) new_flags, (unsigned long) old_flags); ok = FALSE; } if (! ok) { bfd_set_error (bfd_error_bad_value); return FALSE; } return TRUE; } /* Function to keep MIPS specific file flags like as EF_MIPS_PIC. */ bfd_boolean _bfd_mips_elf_set_private_flags (bfd *abfd, flagword flags) { BFD_ASSERT (!elf_flags_init (abfd) || elf_elfheader (abfd)->e_flags == flags); elf_elfheader (abfd)->e_flags = flags; elf_flags_init (abfd) = TRUE; return TRUE; } bfd_boolean _bfd_mips_elf_print_private_bfd_data (bfd *abfd, void *ptr) { FILE *file = ptr; BFD_ASSERT (abfd != NULL && ptr != NULL); /* Print normal ELF private data. */ _bfd_elf_print_private_bfd_data (abfd, ptr); /* xgettext:c-format */ fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags); if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O32) fprintf (file, _(" [abi=O32]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_O64) fprintf (file, _(" [abi=O64]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI32) fprintf (file, _(" [abi=EABI32]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI) == E_MIPS_ABI_EABI64) fprintf (file, _(" [abi=EABI64]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ABI)) fprintf (file, _(" [abi unknown]")); else if (ABI_N32_P (abfd)) fprintf (file, _(" [abi=N32]")); else if (ABI_64_P (abfd)) fprintf (file, _(" [abi=64]")); else fprintf (file, _(" [no abi set]")); if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_1) fprintf (file, _(" [mips1]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_2) fprintf (file, _(" [mips2]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_3) fprintf (file, _(" [mips3]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_4) fprintf (file, _(" [mips4]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_5) fprintf (file, _(" [mips5]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32) fprintf (file, _(" [mips32]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64) fprintf (file, _(" [mips64]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_32R2) fprintf (file, _(" [mips32r2]")); else if ((elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH) == E_MIPS_ARCH_64R2) fprintf (file, _(" [mips64r2]")); else fprintf (file, _(" [unknown ISA]")); if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_MDMX) fprintf (file, _(" [mdmx]")); if (elf_elfheader (abfd)->e_flags & EF_MIPS_ARCH_ASE_M16) fprintf (file, _(" [mips16]")); if (elf_elfheader (abfd)->e_flags & EF_MIPS_32BITMODE) fprintf (file, _(" [32bitmode]")); else fprintf (file, _(" [not 32bitmode]")); fputc ('\n', file); return TRUE; } const struct bfd_elf_special_section _bfd_mips_elf_special_sections[] = { { ".lit4", 5, 0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL }, { ".lit8", 5, 0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL }, { ".mdebug", 7, 0, SHT_MIPS_DEBUG, 0 }, { ".sbss", 5, -2, SHT_NOBITS, SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL }, { ".sdata", 6, -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_MIPS_GPREL }, { ".ucode", 6, 0, SHT_MIPS_UCODE, 0 }, { NULL, 0, 0, 0, 0 } }; /* Ensure that the STO_OPTIONAL flag is copied into h->other, even if this is not a defintion of the symbol. */ void _bfd_mips_elf_merge_symbol_attribute (struct elf_link_hash_entry *h, const Elf_Internal_Sym *isym, bfd_boolean definition, bfd_boolean dynamic ATTRIBUTE_UNUSED) { if (! definition && ELF_MIPS_IS_OPTIONAL (isym->st_other)) h->other |= STO_OPTIONAL; }
Java
/* * SocialLedge.com - Copyright (C) 2013 * * This file is part of free software framework for embedded processors. * You can use it and/or distribute it as long as this copyright header * remains unmodified. The code is free for personal use and requires * permission to use in a commercial product. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * You can reach the author of this software at : * p r e e t . w i k i @ g m a i l . c o m */ #include <string.h> #include "FreeRTOS.h" #include "queue.h" #include "task.h" #include "can.h" #include "LPC17xx.h" #include "sys_config.h" #include "lpc_sys.h" // sys_get_uptime_ms() /** * If non-zero, test code is enabled, and each message sent is self-recepted. * You need to either connect a CAN transceiver, or connect RD/TD wires of * the board with a 1K resistor for the tests to work. * * Note that FullCAN and CAN filter is not tested together, but they both work individually. */ #define CAN_TESTING 0 /// CAN index: enum to struct index conversion #define CAN_INDEX(can) (can) #define CAN_STRUCT_PTR(can) (&(g_can_structs[CAN_INDEX(can)])) #define CAN_VALID(x) (can1 == x || can2 == x) // Used by CAN_CT_ASSERT(). Obtained from http://www.pixelbeat.org/programming/gcc/static_assert.html #define CAN_ASSERT_CONCAT_(a, b) a##b #define CAN_ASSERT_CONCAT(a, b) CAN_ASSERT_CONCAT_(a, b) #define CAN_CT_ASSERT(e) enum { CAN_ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) } // Make some compile-time (CT) checks : // Check the sizes of the structs because the size needs to match the HW registers CAN_CT_ASSERT( 2 == sizeof(can_std_id_t)); CAN_CT_ASSERT( 4 == sizeof(can_ext_id_t)); CAN_CT_ASSERT( 8 == sizeof(can_data_t)); CAN_CT_ASSERT(16 == sizeof(can_msg_t)); CAN_CT_ASSERT(12 == sizeof(can_fullcan_msg_t)); /// Interrupt masks of the CANxIER and CANxICR registers typedef enum { intr_rx = (1 << 0), ///< Receive intr_tx1 = (1 << 1), ///< Transmit 1 intr_warn = (1 << 2), ///< Warning (if error BUS status changes) intr_ovrn = (1 << 3), ///< Data overrun intr_wkup = (1 << 4), ///< Wake-up intr_epi = (1 << 5), ///< Change from error active to error passive or vice versa intr_ali = (1 << 6), ///< Arbitration lost intr_berr = (1 << 7), ///< Bus error (happens during each error/retry of a message) intr_idi = (1 << 8), ///< ID ready (a message was transmitted or aborted) intr_tx2 = (1 << 9), ///< Transmit 2 intr_tx3 = (1 << 10), ///< Transmit 3 intr_all_tx = (intr_tx1 | intr_tx2 | intr_tx3), ///< Mask of the 3 transmit buffers } can_intr_t; /// Bit mask of SR register indicating which hardware buffer is available enum { tx1_avail = (1 << 2), ///< Transmit buffer 1 is available tx2_avail = (1 << 10), ///< Transmit buffer 2 is available tx3_avail = (1 << 18), ///< Transmit buffer 3 is available tx_all_avail = (tx1_avail | tx2_avail | tx3_avail), }; /** * Data values of the AFMR register * @note Since AFMR is common to both controllers, when bypass mode is enabled, * then ALL messages from ALL CAN controllers will be accepted * * Bit1: Bypass Bit0: ACC Off * 0 1 No messages accepted * 1 X All messages accepted * 0 0 HW Filter or FullCAN */ enum { afmr_enabled = 0x00, ///< Hardware acceptance filtering afmr_disabled = 0x01, ///< No messages will be accepted afmr_bypass = 0x02, ///< Bypass mode, all messages will be accepted. Both 0x02 or 0x03 will work. afmr_fullcan = 0x04, ///< Hardware will receive and store messages per FullCAN mode. }; /// CAN MOD register values enum { can_mod_normal = 0x00, ///< CAN MOD register value to enable the BUS can_mod_reset = 0x01, ///< CAN MOD register value to reset the BUS can_mod_normal_tpm = (can_mod_normal | (1 << 3)), ///< CAN bus enabled with TPM mode bits set can_mod_selftest = (1 << 2) | can_mod_normal, ///< Used to enable global self-test }; /// Mask of the PCONP register enum { can1_pconp_mask = (1 << 13), ///< CAN1 power on bitmask can2_pconp_mask = (1 << 14), ///< CAN2 power on bitmask }; /// Typedef of CAN queues and data typedef struct { LPC_CAN_TypeDef *pCanRegs; ///< The pointer to the CAN registers QueueHandle_t rxQ; ///< TX queue QueueHandle_t txQ; ///< RX queue uint16_t droppedRxMsgs; ///< Number of messages dropped if no space found during the CAN interrupt that queues the RX messages uint16_t rxQWatermark; ///< Watermark of the FreeRTOS Rx Queue uint16_t txQWatermark; ///< Watermark of the FreeRTOS Tx Queue uint16_t txMsgCount; ///< Number of messages sent uint16_t rxMsgCount; ///< Number of received messages can_void_func_t bus_error; ///< When serious BUS error occurs can_void_func_t data_overrun; ///< When we read the CAN buffer too late for incoming message } can_struct_t ; /// Structure of both CANs can_struct_t g_can_structs[can_max] = { {LPC_CAN1}, {LPC_CAN2}}; /** * This type of CAN interrupt should lead to "bus error", but note that intr_berr is not the right * one as that one is triggered upon each type of CAN error which may be a simple "retry" that * can be recovered. intr_epi or intr_warn should work for this selection. */ static const can_intr_t g_can_bus_err_intr = intr_epi; /** @{ Private functions */ /** * Sends a message using an available buffer. Initially this chose one out of the three buffers but that's * a little tricky to use when messages are always queued since one of the 3 buffers can be starved and not * get sent. So therefore some of that logic is #ifdef'd out to only use one HW buffer. * * @returns true if the message was written to the HW buffer to be sent, otherwise false if the HW buffer(s) are busy. * * Notes: * - Using the TX message counter and the TPM bit, we can ensure that the HW chooses between the TX1/TX2/TX3 * in a round-robin fashion otherwise there is a possibility that if the CAN Tx queue is always full, * a low message ID can be starved even if it was amongst the first ones written using this method call. * * @warning This should be called from critical section since this method is not thread-safe */ static bool CAN_tx_now (can_struct_t *struct_ptr, can_msg_t *msg_ptr) { // 32-bit command of CMR register to start transmission of one of the buffers enum { go_cmd_invalid = 0, go_cmd_tx1 = 0x21, go_cmd_tx2 = 0x41, go_cmd_tx3 = 0x81, }; LPC_CAN_TypeDef *pCAN = struct_ptr->pCanRegs; const uint32_t can_sr_reg = pCAN->SR; volatile can_msg_t *pHwMsgRegs = NULL; uint32_t go_cmd = go_cmd_invalid; if (can_sr_reg & tx1_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI1); go_cmd = go_cmd_tx1; } #if 0 else if (can_sr_reg & tx2_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI2); go_cmd = go_cmd_tx2; } else if (can_sr_reg & tx3_avail){ pHwMsgRegs = (can_msg_t*)&(pCAN->TFI3); go_cmd = go_cmd_tx3; } #endif else { /* No buffer available, return failure */ return false; } /* Copy the CAN message to the HW CAN registers and write the 8 TPM bits. * We set TPM bits each time by using the txMsgCount because otherwise if TX1, and TX2 are always * being written with a lower message ID, then TX3 will starve and never be sent. */ #if 0 // Higher number will be sent later, but how do we handle the rollover from 255 to 0 because then the // newly written 0 will be sent, and buffer that contains higher TPM can starve. const uint8_t tpm = struct_ptr->txMsgCount; msg_ptr->frame |= tpm; #endif *pHwMsgRegs = *msg_ptr; struct_ptr->txMsgCount++; #if CAN_TESTING go_cmd &= (0xF0); go_cmd = (1 << 4); /* Self reception */ #endif /* Send the message! */ pCAN->CMR = go_cmd; return true; } static void CAN_handle_isr(const can_t can) { can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *pCAN = pStruct->pCanRegs; const uint32_t rbs = (1 << 0); const uint32_t ibits = pCAN->ICR; UBaseType_t count; can_msg_t msg; /* Handle the received message */ if ((ibits & intr_rx) | (pCAN->GSR & rbs)) { if( (count = uxQueueMessagesWaitingFromISR(pStruct->rxQ)) > pStruct->rxQWatermark) { pStruct->rxQWatermark = count; } can_msg_t *pHwMsgRegs = (can_msg_t*) &(pCAN->RFS); if (xQueueSendFromISR(pStruct->rxQ, pHwMsgRegs, NULL)) { pStruct->rxMsgCount++; } else { pStruct->droppedRxMsgs++; } pCAN->CMR = 0x04; // Release the receive buffer, no need to bitmask } /* A transmit finished, send any queued message(s) */ if (ibits & intr_all_tx) { if( (count = uxQueueMessagesWaitingFromISR(pStruct->txQ)) > pStruct->txQWatermark) { pStruct->txQWatermark = count; } if (xQueueReceiveFromISR(pStruct->txQ, &msg, NULL)) { CAN_tx_now(pStruct, &msg); } } /* We only enable interrupt when a valid callback exists, so no need * to check for the callback function being NULL */ if (ibits & g_can_bus_err_intr) { pStruct->bus_error(ibits); } if (ibits & intr_ovrn) { pStruct->data_overrun(ibits); } } /** @} */ /** * Actual ISR Handler (mapped to startup file's interrupt vector function name) * This interrupt is shared between CAN1, and CAN2 */ #ifdef __cplusplus extern "C" { #endif void CAN_IRQHandler(void) { const uint32_t pconp = LPC_SC->PCONP; /* Reading registers without CAN powered up will cause DABORT exception */ if (pconp & can1_pconp_mask) { CAN_handle_isr(can1); } if (pconp & can2_pconp_mask) { CAN_handle_isr(can2); } } #ifdef __cplusplus } #endif bool CAN_init(can_t can, uint32_t baudrate_kbps, uint16_t rxq_size, uint16_t txq_size, can_void_func_t bus_off_cb, can_void_func_t data_ovr_cb) { if (!CAN_VALID(can)){ return false; } can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *pCAN = pStruct->pCanRegs; bool failed = true; /* Enable CAN Power, and select the PINS * CAN1 is at P0.0, P0.1 and P0.21, P0.22 * CAN2 is at P0.4, P0.5 and P2.7, P2.8 * On SJ-One board, we have P0.0, P0.1, and P2.7, P2.8 */ if (can1 == can) { LPC_SC->PCONP |= can1_pconp_mask; LPC_PINCON->PINSEL0 &= ~(0xF << 0); LPC_PINCON->PINSEL0 |= (0x5 << 0); } else if (can2 == can){ LPC_SC->PCONP |= can2_pconp_mask; LPC_PINCON->PINSEL4 &= ~(0xF << 14); LPC_PINCON->PINSEL4 |= (0x5 << 14); } /* Create the queues with minimum size of 1 to avoid NULL pointer reference */ if (!pStruct->rxQ) { pStruct->rxQ = xQueueCreate(rxq_size ? rxq_size : 1, sizeof(can_msg_t)); } if (!pStruct->txQ) { pStruct->txQ = xQueueCreate(txq_size ? txq_size : 1, sizeof(can_msg_t)); } /* The CAN dividers must all be the same for both CANs * Set the dividers of CAN1, CAN2, ACF to CLK / 1 */ lpc_pclk(pclk_can1, clkdiv_1); lpc_pclk(pclk_can2, clkdiv_1); lpc_pclk(pclk_can_flt, clkdiv_1); pCAN->MOD = can_mod_reset; pCAN->IER = 0x0; // Disable All CAN Interrupts pCAN->GSR = 0x0; // Clear error counters pCAN->CMR = 0xE; // Abort Tx, release Rx, clear data over-run /** * About the AFMR register : * B0 B1 * Filter Mode | AccOff bit | AccBP bit | CAN Rx interrupt * Off Mode 1 0 No messages accepted * Bypass Mode X 1 All messages accepted * FullCAN 0 0 HW acceptance filtering */ LPC_CANAF->AFMR = afmr_disabled; // Clear pending interrupts and the CAN Filter RAM LPC_CANAF_RAM->mask[0] = pCAN->ICR; memset((void*)&(LPC_CANAF_RAM->mask[0]), 0, sizeof(LPC_CANAF_RAM->mask)); /* Zero out the filtering registers */ LPC_CANAF->SFF_sa = 0; LPC_CANAF->SFF_GRP_sa = 0; LPC_CANAF->EFF_sa = 0; LPC_CANAF->EFF_GRP_sa = 0; LPC_CANAF->ENDofTable = 0; /* Do not accept any messages until CAN filtering is enabled */ LPC_CANAF->AFMR = afmr_disabled; /* Set the baud-rate. You can verify the settings by visiting: * http://www.kvaser.com/en/support/bit-timing-calculator.html */ do { const uint32_t baudDiv = sys_get_cpu_clock() / (1000 * baudrate_kbps); const uint32_t SJW = 3; const uint32_t SAM = 0; uint32_t BRP = 0, TSEG1 = 0, TSEG2 = 0, NT = 0; /* Calculate suitable nominal time value * NT (nominal time) = (TSEG1 + TSEG2 + 3) * NT <= 24 * TSEG1 >= 2*TSEG2 */ failed = true; for(NT=24; NT > 0; NT-=2) { if ((baudDiv % NT)==0) { BRP = baudDiv / NT - 1; NT--; TSEG2 = (NT/3) - 1; TSEG1 = NT -(NT/3) - 1; failed = false; break; } } if (!failed) { pCAN->BTR = (SAM << 23) | (TSEG2<<20) | (TSEG1<<16) | (SJW<<14) | BRP; // CANx->BTR = 0x002B001D; // 48Mhz 100Khz } } while (0); /* If everything okay so far, enable the CAN interrupts */ if (!failed) { /* At minimum, we need Rx/Tx interrupts */ pCAN->IER = (intr_rx | intr_all_tx); /* Enable BUS-off interrupt and callback if given */ if (bus_off_cb) { pStruct->bus_error = bus_off_cb; pCAN->IER |= g_can_bus_err_intr; } /* Enable data-overrun interrupt and callback if given */ if (data_ovr_cb) { pStruct->data_overrun = data_ovr_cb; pCAN->IER |= intr_ovrn; } /* Finally, enable the actual CPU core interrupt */ vTraceSetISRProperties(CAN_IRQn, "CAN", IP_can); NVIC_EnableIRQ(CAN_IRQn); } /* return true if all is well */ return (false == failed); } bool CAN_tx (can_t can, can_msg_t *pCanMsg, uint32_t timeout_ms) { if (!CAN_VALID(can) || !pCanMsg || CAN_is_bus_off(can)) { return false; } bool ok = false; can_struct_t *pStruct = CAN_STRUCT_PTR(can); LPC_CAN_TypeDef *CANx = pStruct->pCanRegs; /* Try transmitting to one of the available buffers */ taskENTER_CRITICAL(); do { ok = CAN_tx_now(pStruct, pCanMsg); } while(0); taskEXIT_CRITICAL(); /* If HW buffer not available, then just queue the message */ if (!ok) { if (taskSCHEDULER_RUNNING == xTaskGetSchedulerState()) { ok = xQueueSend(pStruct->txQ, pCanMsg, OS_MS(timeout_ms)); } else { ok = xQueueSend(pStruct->txQ, pCanMsg, 0); } /* There is possibility that before we queued the message, we got interrupted * and all hw buffers were emptied meanwhile, and our queued message will now * sit in the queue forever until another Tx interrupt takes place. * So we dequeue it here if all are empty and send it over. */ taskENTER_CRITICAL(); do { can_msg_t msg; if (tx_all_avail == (CANx->SR & tx_all_avail) && xQueueReceive(pStruct->txQ, &msg, 0) ) { ok = CAN_tx_now(pStruct, &msg); } } while(0); taskEXIT_CRITICAL(); } return ok; } bool CAN_rx (can_t can, can_msg_t *pCanMsg, uint32_t timeout_ms) { bool ok = false; if (CAN_VALID(can) && pCanMsg) { if (taskSCHEDULER_RUNNING == xTaskGetSchedulerState()) { ok = xQueueReceive(CAN_STRUCT_PTR(can)->rxQ, pCanMsg, OS_MS(timeout_ms)); } else { uint64_t msg_timeout = sys_get_uptime_ms() + timeout_ms; while (! (ok = xQueueReceive(CAN_STRUCT_PTR(can)->rxQ, pCanMsg, 0))) { if (sys_get_uptime_ms() > msg_timeout) { break; } } } } return ok; } bool CAN_is_bus_off(can_t can) { const uint32_t bus_off_mask = (1 << 7); return (!CAN_VALID(can)) ? true : !! (CAN_STRUCT_PTR(can)->pCanRegs->GSR & bus_off_mask); } void CAN_reset_bus(can_t can) { if (CAN_VALID(can)) { CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_reset; #if CAN_TESTING CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_selftest; #else CAN_STRUCT_PTR(can)->pCanRegs->MOD = can_mod_normal_tpm; #endif } } uint16_t CAN_get_rx_watermark(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->rxQWatermark : 0; } uint16_t CAN_get_tx_watermark(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->txQWatermark : 0; } uint16_t CAN_get_tx_count(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->txMsgCount : 0; } uint16_t CAN_get_rx_count(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->rxMsgCount : 0; } uint16_t CAN_get_rx_dropped_count(can_t can) { return CAN_VALID(can) ? CAN_STRUCT_PTR(can)->droppedRxMsgs : 0; } void CAN_bypass_filter_accept_all_msgs(void) { LPC_CANAF->AFMR = afmr_bypass; } can_std_id_t CAN_gen_sid(can_t can, uint16_t id) { /* SCC in datasheet is defined as can controller - 1 */ const uint16_t scc = (can); can_std_id_t ret; ret.can_num = scc; ret.disable = (0xffff == id) ? 1 : 0; ret.fc_intr = 0; ret.id = id; return ret; } can_ext_id_t CAN_gen_eid(can_t can, uint32_t id) { /* SCC in datasheet is defined as can controller - 1 */ const uint16_t scc = (can); can_ext_id_t ret; ret.can_num = scc; ret.id = id; return ret; } bool CAN_fullcan_add_entry(can_t can, can_std_id_t id1, can_std_id_t id2) { /* Return if invalid CAN given */ if (!CAN_VALID(can)) { return false; } /* Check for enough room for more FullCAN entries * Each entry takes 2-byte entry, and 12-byte message RAM. */ const uint16_t existing_entries = CAN_fullcan_get_num_entries(); const uint16_t size_per_entry = sizeof(can_std_id_t) + sizeof(can_fullcan_msg_t); if ((existing_entries * size_per_entry) >= sizeof(LPC_CANAF_RAM->mask)) { return false; } /* Locate where we should write the next entry */ uint8_t *base = (uint8_t*) &(LPC_CANAF_RAM->mask[0]); uint8_t *next_entry_ptr = base + LPC_CANAF->SFF_sa; /* Copy the new entry into the RAM filter */ LPC_CANAF->AFMR = afmr_disabled; do { const uint32_t entries = ((uint32_t) id2.raw & UINT16_MAX) | ((uint32_t) id1.raw << 16); * (uint32_t*) (next_entry_ptr) = entries; /* The new start of Standard Frame Filter is after the two new entries */ const uint32_t new_sff_sa = LPC_CANAF->SFF_sa + sizeof(id1) + sizeof(id2); LPC_CANAF->SFF_sa = new_sff_sa; /* Next filters start at SFF_sa (they are disabled) */ LPC_CANAF->SFF_GRP_sa = new_sff_sa; LPC_CANAF->EFF_sa = new_sff_sa; LPC_CANAF->EFF_GRP_sa = new_sff_sa; LPC_CANAF->ENDofTable = new_sff_sa; } while(0); LPC_CANAF->AFMR = afmr_fullcan; return true; } can_fullcan_msg_t* CAN_fullcan_get_entry_ptr(can_std_id_t fc_id) { /* Number of entries depends on how far SFF_sa is from base of 0 */ const uint16_t num_entries = CAN_fullcan_get_num_entries(); uint16_t idx = 0; /* The FullCAN entries are at the base of the CAN RAM */ const can_std_id_t *id_list = (can_std_id_t*) &(LPC_CANAF_RAM->mask[0]); /* Find the standard ID entered into the RAM * Once we find the ID, its message's RAM location is after * LPC_CANAF->ENDofTable based on the index location. * * Note that due to MSB/LSB of the CAN RAM, we check in terms of 16-bit WORDS * and LSB word match means we will find it at index + 1, and MSB word match * means we will find it at the index. */ for (idx = 0; idx < num_entries; idx+=2) { if (id_list[idx].id == fc_id.id) { ++idx; break; } if (id_list[idx+1].id == fc_id.id) { break; } } can_fullcan_msg_t *real_entry = NULL; if (idx < num_entries) { /* If we find an index, we have to convert it to the actual message pointer */ can_fullcan_msg_t *base_msg_entry = (can_fullcan_msg_t*) (((uint8_t*) &(LPC_CANAF_RAM->mask[0])) + LPC_CANAF->ENDofTable); real_entry = (base_msg_entry + idx); } return real_entry; } bool CAN_fullcan_read_msg_copy(can_fullcan_msg_t *pMsg, can_fullcan_msg_t *pMsgCopy) { const uint8_t *can_ram_base = (uint8_t*) &(LPC_CANAF_RAM->mask[0]); const uint8_t *start = can_ram_base + LPC_CANAF->ENDofTable; // Actual FullCAN msgs are stored after this const uint8_t *end = can_ram_base + sizeof(LPC_CANAF_RAM->mask); // Last byte of CAN RAM + 1 bool new_msg_received = false; /* Validate the input pointers. pMsg must be within range of our RAM filter * where the actual FullCAN message should be stored at */ const uint8_t *ptr = (uint8_t*) pMsg; if (ptr < start || ptr >= end || !pMsgCopy) { return false; } /* If semaphore bits change, then HW has updated the message so read it again. * After HW writes new message, semaphore bits are changed to 0b11. */ while (0 != pMsg->semphr) { new_msg_received = true; pMsg->semphr = 0; *pMsgCopy = *pMsg; } return new_msg_received; } uint8_t CAN_fullcan_get_num_entries(void) { return LPC_CANAF->SFF_sa / sizeof(can_std_id_t); } bool CAN_setup_filter(const can_std_id_t *std_id_list, uint16_t sid_cnt, const can_std_grp_id_t *std_group_id_list, uint16_t sgp_cnt, const can_ext_id_t *ext_id_list, uint16_t eid_cnt, const can_ext_grp_id_t *ext_group_id_list, uint16_t egp_cnt) { bool ok = true; uint32_t i = 0; uint32_t temp32 = 0; // Count of standard IDs must be even if (sid_cnt & 1) { return false; } LPC_CANAF->AFMR = afmr_disabled; do { /* Filter RAM is after the FulLCAN entries */ uint32_t can_ram_base_addr = (uint32_t) &(LPC_CANAF_RAM->mask[0]); /* FullCAN entries take up 2 bytes each at beginning RAM, and 12-byte sections at the end */ const uint32_t can_ram_end_addr = can_ram_base_addr + sizeof(LPC_CANAF_RAM->mask) - ( sizeof(can_fullcan_msg_t) * CAN_fullcan_get_num_entries()); /* Our filter RAM is after FullCAN entries */ uint32_t *ptr = (uint32_t*) (can_ram_base_addr + LPC_CANAF->SFF_sa); /* macro to swap top and bottom 16-bits of 32-bit DWORD */ #define CAN_swap32(t32) do { \ t32 = (t32 >> 16) | (t32 << 16);\ } while (0) /** * Standard ID list and group list need to swapped otherwise setting the wrong * filter will make the CAN ISR go into a loop for no apparent reason. * It looks like the filter data is motorolla big-endian format. * See "configuration example 5" in CAN chapter. */ #define CAN_add_filter_list(list, ptr, end, cnt, entry_size, swap) \ do { if (NULL != list) { \ if ((uint32_t)ptr + (cnt * entry_size) < end) { \ for (i = 0; i < (cnt * entry_size)/4; i++) { \ if(swap) { \ temp32 = ((uint32_t*)list) [i]; \ CAN_swap32(temp32); \ ptr[i] = temp32; \ } \ else { \ ptr[i] = ((uint32_t*)list) [i]; \ } \ } \ ptr += (cnt * entry_size)/4; \ } else { ok = false; } } } while(0) /* The sa (start addresses) are byte address offset from CAN RAM * and must be 16-bit (WORD) aligned * LPC_CANAF->SFF_sa should already be setup by FullCAN if used, or * set to zero by the can init function. */ CAN_add_filter_list(std_id_list, ptr, can_ram_end_addr, sid_cnt, sizeof(can_std_id_t), true); LPC_CANAF->SFF_GRP_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(std_group_id_list, ptr, can_ram_end_addr, sgp_cnt, sizeof(can_std_grp_id_t), true); LPC_CANAF->EFF_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(ext_id_list, ptr, can_ram_end_addr, eid_cnt, sizeof(can_ext_id_t), false); LPC_CANAF->EFF_GRP_sa = ((uint32_t)ptr - can_ram_base_addr); CAN_add_filter_list(ext_group_id_list, ptr, can_ram_end_addr, egp_cnt, sizeof(can_ext_grp_id_t), false); /* End of table is where the FullCAN messages are stored */ LPC_CANAF->ENDofTable = ((uint32_t)ptr - can_ram_base_addr); } while(0); /* If there was no FullCAN entry, then SFF_sa will be zero. * If it was zero, we just enable the AFMR, but if it was not zero, that means * FullCAN entry was added, so we restore AMFR to fullcan enable */ LPC_CANAF->AFMR = (0 == LPC_CANAF->SFF_sa) ? afmr_enabled : afmr_fullcan; return ok; } #if CAN_TESTING #include <printf_lib.h> #define CAN_ASSERT(x) if (!(x)) { u0_dbg_printf("Failed at %i, BUS: %s MOD: 0x%08x, GSR: 0x%08x\n"\ "IER/ICR: 0x%08X/0x%08x BTR: 0x%08x"\ "\nLine %i: %s\n", __LINE__, \ CAN_is_bus_off(can1) ? "OFF" : "ON", \ (int)LPC_CAN1->MOD, (int)LPC_CAN1->GSR, \ (int)LPC_CAN1->IER, (int)LPC_CAN1->ICR, \ (int)LPC_CAN1->BTR, \ __LINE__, #x); return false; } void CAN_test_bufoff_cb(uint32_t d) { u0_dbg_printf("CB: BUS OFF\n"); } void CAN_test_bufovr_cb(uint32_t d) { u0_dbg_printf("CB: DATA OVR\n"); } bool CAN_test(void) { uint32_t i = 0; #define can_test_msg(msg, id, rxtrue) do { \ u0_dbg_printf("Send ID: 0x%08X\n", id); \ msg.msg_id = id; \ CAN_ASSERT(CAN_tx(can1, &msg, 0)); \ msg.msg_id = 0; \ CAN_ASSERT(rxtrue == CAN_rx(can1, &msg, 10)); \ if (rxtrue) CAN_ASSERT(id == msg.msg_id); \ } while(0) u0_dbg_printf(" Test init()\n"); CAN_ASSERT(!CAN_init(can_max, 100, 0, 0, NULL, NULL)); CAN_ASSERT(CAN_init(can1, 100, 5, 5, CAN_test_bufoff_cb, CAN_test_bufovr_cb)); CAN_ASSERT(LPC_CAN1->MOD == can_mod_reset); CAN_bypass_filter_accept_all_msgs(); CAN_ASSERT(g_can_rx_qs[0] != NULL); CAN_ASSERT(g_can_tx_qs[0] != NULL); CAN_ASSERT(LPC_CANAF->SFF_sa == 0); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 0); CAN_ASSERT(LPC_CANAF->EFF_sa == 0); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 0); CAN_ASSERT(LPC_CANAF->ENDofTable == 0); CAN_reset_bus(can1); CAN_ASSERT(LPC_CAN1->MOD == can_mod_selftest); /* Create a message, and test tx with bad input */ uint32_t id = 0x100; can_msg_t msg; memset(&msg, 0, sizeof(msg)); msg.frame = 0; msg.msg_id = id; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; msg.data.qword = 0x1122334455667788; CAN_ASSERT(!CAN_tx(can_max, &msg, 0)); // Invalid CAN CAN_ASSERT(!CAN_rx(can1, NULL, 0)); // Invalid message pointer /* Send msg and test receive */ u0_dbg_printf(" Test Tx/Rx\n"); can_test_msg(msg, 0x100, true); can_test_msg(msg, 0x200, true); can_test_msg(msg, 0x300, true); can_test_msg(msg, 0x400, true); can_test_msg(msg, 0x500, true); const can_std_id_t slist[] = { CAN_gen_sid(can1, 0x100), CAN_gen_sid(can1, 0x110), // 2 entries CAN_gen_sid(can1, 0x120), CAN_gen_sid(can1, 0x130) // 2 entries }; const can_std_grp_id_t sglist[] = { {CAN_gen_sid(can1, 0x200), CAN_gen_sid(can1, 0x210)}, // Group 1 {CAN_gen_sid(can1, 0x220), CAN_gen_sid(can1, 0x230)} // Group 2 }; const can_ext_id_t elist[] = { CAN_gen_eid(can1, 0x7500), CAN_gen_eid(can1, 0x8500)}; const can_ext_grp_id_t eglist[] = { {CAN_gen_eid(can1, 0xA000), CAN_gen_eid(can1, 0xB000)} }; // Group 1 /* Test filter setup */ u0_dbg_printf(" Test filter setup\n"); CAN_setup_filter(slist, 4, sglist, 2, elist, 2, eglist, 1); /* We use offset of zero if 2 FullCAN messages are added, otherwise 4 if none were added above */ const uint8_t offset = 4; CAN_ASSERT(LPC_CANAF->SFF_sa == 4 - offset); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 12 - offset); CAN_ASSERT(LPC_CANAF->EFF_sa == 20 - offset); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 28 - offset); CAN_ASSERT(LPC_CANAF->ENDofTable == 36 - offset); for ( i = 0; i < 10; i++) { u0_dbg_printf("%2i: 0x%08X\n", i, (uint32_t) LPC_CANAF_RAM->mask[i]); } /* Send a message defined in filter */ u0_dbg_printf(" Test filter messages\n"); msg.frame = 0; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; msg.data.qword = 0x1122334455667788; /* Test reception of messages defined in the filter */ u0_dbg_printf(" Test message reception according to filter\n"); msg.frame_fields.is_29bit = 0; can_test_msg(msg, 0x100, true); // standard id can_test_msg(msg, 0x110, true); // standard id can_test_msg(msg, 0x120, true); // standard id can_test_msg(msg, 0x130, true); // standard id can_test_msg(msg, 0x200, true); // Start of standard ID group can_test_msg(msg, 0x210, true); // Last of standard ID group can_test_msg(msg, 0x220, true); // Start of standard ID group can_test_msg(msg, 0x230, true); // Last of standard ID group msg.frame_fields.is_29bit = 1; can_test_msg(msg, 0x7500, true); // extended id can_test_msg(msg, 0x8500, true); // extended id can_test_msg(msg, 0xA000, true); // extended id group start can_test_msg(msg, 0xB000, true); // extended id group end u0_dbg_printf(" Test messages that should not be received\n"); /* Send a message not defined in filter */ msg.frame_fields.is_29bit = 0; can_test_msg(msg, 0x0FF, false); can_test_msg(msg, 0x111, false); can_test_msg(msg, 0x131, false); can_test_msg(msg, 0x1FF, false); can_test_msg(msg, 0x211, false); can_test_msg(msg, 0x21f, false); can_test_msg(msg, 0x231, false); msg.frame_fields.is_29bit = 1; can_test_msg(msg, 0x7501, false); can_test_msg(msg, 0x8501, false); can_test_msg(msg, 0xA000-1, false); can_test_msg(msg, 0xB000+1, false); /* Test FullCAN */ u0_dbg_printf(" Test FullCAN\n"); CAN_init(can1, 100, 5, 5, CAN_test_bufoff_cb, CAN_test_bufovr_cb); CAN_reset_bus(can1); id = 0x100; CAN_ASSERT(0 == CAN_fullcan_get_num_entries()); CAN_ASSERT(CAN_fullcan_add_entry(can1, CAN_gen_sid(can1, id), CAN_gen_sid(can1, id+1))); CAN_ASSERT(2 == CAN_fullcan_get_num_entries()); CAN_ASSERT(LPC_CANAF->SFF_sa == 4); CAN_ASSERT(LPC_CANAF->SFF_GRP_sa == 4); CAN_ASSERT(LPC_CANAF->EFF_sa == 4); CAN_ASSERT(LPC_CANAF->EFF_GRP_sa == 4); CAN_ASSERT(LPC_CANAF->ENDofTable == 4); CAN_ASSERT(CAN_fullcan_add_entry(can1, CAN_gen_sid(can1, id+2), CAN_gen_sid(can1, id+3))); CAN_ASSERT(4 == CAN_fullcan_get_num_entries()); CAN_ASSERT(LPC_CANAF->SFF_sa == 8); for ( i = 0; i < 3; i++) { u0_dbg_printf("%2i: 0x%08X\n", i, (uint32_t) LPC_CANAF_RAM->mask[i]); } can_fullcan_msg_t *fc1 = CAN_fullcan_get_entry_ptr(CAN_gen_sid(can1, id)); can_fullcan_msg_t *fc2 = CAN_fullcan_get_entry_ptr(CAN_gen_sid(can1, id+1)); can_fullcan_msg_t *fc3 = CAN_fullcan_get_entry_ptr(CAN_gen_sid(can1, id+2)); can_fullcan_msg_t *fc4 = CAN_fullcan_get_entry_ptr(CAN_gen_sid(can1, id+3)); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa) == (uint32_t)fc1); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 1*sizeof(can_fullcan_msg_t)) == (uint32_t)fc2); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 2*sizeof(can_fullcan_msg_t)) == (uint32_t)fc3); CAN_ASSERT((LPC_CANAF_RAM_BASE + LPC_CANAF->SFF_sa + 3*sizeof(can_fullcan_msg_t)) == (uint32_t)fc4); can_fullcan_msg_t fc_temp; CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc1, &fc_temp)); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc2, &fc_temp)); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc3, &fc_temp)); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc4, &fc_temp)); /* Send message, see if fullcan captures it */ msg.frame = 0; msg.msg_id = id; msg.frame_fields.is_29bit = 0; msg.frame_fields.data_len = 8; #define can_test_fullcan_msg(fc, msg_copy, id) \ do { \ msg.msg_id = id; \ CAN_ASSERT(CAN_tx(can1, &msg, 0)); \ CAN_ASSERT(!CAN_rx(can1, &msg, 10)); \ CAN_ASSERT(CAN_fullcan_read_msg_copy(fc, &msg_copy)); \ CAN_ASSERT(fc->msg_id == id) \ } while(0) can_test_fullcan_msg(fc1, fc_temp, id+0); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc2, &fc_temp)); can_test_fullcan_msg(fc2, fc_temp, id+1); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc3, &fc_temp)); can_test_fullcan_msg(fc3, fc_temp, id+2); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc4, &fc_temp)); can_test_fullcan_msg(fc4, fc_temp, id+3); CAN_ASSERT(!CAN_fullcan_read_msg_copy(fc1, &fc_temp)); u0_dbg_printf(" \n--> All tests successful! <--\n"); return true; } #endif
Java
<?php /* * acf_get_setting * * This function will return a value from the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) the setting name to return * @return (mixed) */ function acf_get_setting( $name, $default = null ) { // vars $settings = acf()->settings; // find setting $setting = acf_maybe_get( $settings, $name, $default ); // filter for 3rd party customization $setting = apply_filters( "acf/settings/{$name}", $setting ); // return return $setting; } /* * acf_get_compatibility * * This function will return true or false for a given compatibility setting * * @type function * @date 20/01/2015 * @since 5.1.5 * * @param $name (string) * @return (boolean) */ function acf_get_compatibility( $name ) { return apply_filters( "acf/compatibility/{$name}", false ); } /* * acf_update_setting * * This function will update a value into the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) * @param $value (mixed) * @return n/a */ function acf_update_setting( $name, $value ) { acf()->settings[ $name ] = $value; } /* * acf_append_setting * * This function will add a value into the settings array found in the acf object * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $name (string) * @param $value (mixed) * @return n/a */ function acf_append_setting( $name, $value ) { // createa array if needed if( !isset(acf()->settings[ $name ]) ) { acf()->settings[ $name ] = array(); } // append to array acf()->settings[ $name ][] = $value; } /* * acf_get_path * * This function will return the path to a file within the ACF plugin folder * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $path (string) the relative path from the root of the ACF plugin folder * @return (string) */ function acf_get_path( $path ) { return acf_get_setting('path') . $path; } /* * acf_get_dir * * This function will return the url to a file within the ACF plugin folder * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $path (string) the relative path from the root of the ACF plugin folder * @return (string) */ function acf_get_dir( $path ) { return acf_get_setting('dir') . $path; } /* * acf_include * * This function will include a file * * @type function * @date 10/03/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_include( $file ) { $path = acf_get_path( $file ); if( file_exists($path) ) { include_once( $path ); } } /* * acf_parse_args * * This function will merge together 2 arrays and also convert any numeric values to ints * * @type function * @date 18/10/13 * @since 5.0.0 * * @param $args (array) * @param $defaults (array) * @return $args (array) */ function acf_parse_args( $args, $defaults = array() ) { // $args may not be na array! if( !is_array($args) ) { $args = array(); } // parse args $args = wp_parse_args( $args, $defaults ); // parse types $args = acf_parse_types( $args ); // return return $args; } /* * acf_parse_types * * This function will convert any numeric values to int and trim strings * * @type function * @date 18/10/13 * @since 5.0.0 * * @param $var (mixed) * @return $var (mixed) */ function acf_parse_types( $array ) { // some keys are restricted $restricted = array( 'label', 'name', 'value', 'instructions', 'nonce' ); // loop foreach( array_keys($array) as $k ) { // parse type if not restricted if( !in_array($k, $restricted, true) ) { $array[ $k ] = acf_parse_type( $array[ $k ] ); } } // return return $array; } /* * acf_parse_type * * description * * @type function * @date 11/11/2014 * @since 5.0.9 * * @param $post_id (int) * @return $post_id (int) */ function acf_parse_type( $v ) { // test for array if( is_array($v) ) { return acf_parse_types($v); } // bail early if not string if( !is_string($v) ) { return $v; } // trim $v = trim($v); // numbers if( is_numeric($v) && strval((int)$v) === $v ) { $v = intval( $v ); } // return return $v; } /* * acf_get_view * * This function will load in a file from the 'admin/views' folder and allow variables to be passed through * * @type function * @date 28/09/13 * @since 5.0.0 * * @param $view_name (string) * @param $args (array) * @return n/a */ function acf_get_view( $view_name = '', $args = array() ) { // vars $path = acf_get_path("admin/views/{$view_name}.php"); if( file_exists($path) ) { include( $path ); } } /* * acf_merge_atts * * description * * @type function * @date 2/11/2014 * @since 5.0.9 * * @param $post_id (int) * @return $post_id (int) */ function acf_merge_atts( $atts, $extra = array() ) { // bail ealry if no $extra if( empty($extra) ) { return $atts; } // merge in new atts foreach( $extra as $k => $v ) { if( $k == 'class' || $k == 'style' ) { if( $v === '' ) { continue; } $v = $atts[ $k ] . ' ' . $v; } $atts[ $k ] = $v; } // return return $atts; } /* * acf_esc_attr * * This function will return a render of an array of attributes to be used in markup * * @type function * @date 1/10/13 * @since 5.0.0 * * @param $atts (array) * @return n/a */ function acf_esc_attr( $atts ) { // is string? if( is_string($atts) ) { $atts = trim( $atts ); return esc_attr( $atts ); } // validate if( empty($atts) ) { return ''; } // vars $e = array(); // loop through and render foreach( $atts as $k => $v ) { // object if( is_array($v) || is_object($v) ) { $v = json_encode($v); // boolean } elseif( is_bool($v) ) { $v = $v ? 1 : 0; // string } elseif( is_string($v) ) { $v = trim($v); } // append $e[] = $k . '="' . esc_attr( $v ) . '"'; } // echo return implode(' ', $e); } function acf_esc_attr_e( $atts ) { echo acf_esc_attr( $atts ); } /* * acf_hidden_input * * description * * @type function * @date 3/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_hidden_input( $atts ) { $atts['type'] = 'hidden'; return '<input ' . acf_esc_attr( $atts ) . ' />'; } function acf_hidden_input( $atts ) { echo acf_get_hidden_input( $atts ); } /* * acf_extract_var * * This function will remove the var from the array, and return the var * * @type function * @date 2/10/13 * @since 5.0.0 * * @param $array (array) * @param $key (string) * @return (mixed) */ function acf_extract_var( &$array, $key ) { // check if exists if( is_array($array) && array_key_exists($key, $array) ) { // store value $v = $array[ $key ]; // unset unset( $array[ $key ] ); // return return $v; } // return return null; } /* * acf_extract_vars * * This function will remove the vars from the array, and return the vars * * @type function * @date 8/10/13 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_extract_vars( &$array, $keys ) { $r = array(); foreach( $keys as $key ) { $r[ $key ] = acf_extract_var( $array, $key ); } return $r; } /* * acf_get_post_types * * This function will return an array of available post types * * @type function * @date 7/10/13 * @since 5.0.0 * * @param $exclude (array) * @param $include (array) * @return (array) */ function acf_get_post_types( $exclude = array(), $include = array() ) { // get all custom post types $post_types = get_post_types(); // core exclude $exclude = wp_parse_args( $exclude, array('acf-field', 'acf-field-group', 'revision', 'nav_menu_item') ); // include if( !empty($include) ) { foreach( array_keys($include) as $i ) { $post_type = $include[ $i ]; if( post_type_exists($post_type) ) { $post_types[ $post_type ] = $post_type; } } } // exclude foreach( array_values($exclude) as $i ) { unset( $post_types[ $i ] ); } // simplify keys $post_types = array_values($post_types); // return return $post_types; } function acf_get_pretty_post_types( $post_types = array() ) { // get post types if( empty($post_types) ) { // get all custom post types $post_types = acf_get_post_types(); } // get labels $ref = array(); $r = array(); foreach( $post_types as $post_type ) { // vars $label = $post_type; // check that object exists (case exists when importing field group from another install and post type does not exist) if( post_type_exists($post_type) ) { $obj = get_post_type_object($post_type); $label = $obj->labels->singular_name; } // append to r $r[ $post_type ] = $label; // increase counter if( !isset($ref[ $label ]) ) { $ref[ $label ] = 0; } $ref[ $label ]++; } // get slugs foreach( array_keys($r) as $i ) { // vars $post_type = $r[ $i ]; if( $ref[ $post_type ] > 1 ) { $r[ $i ] .= ' (' . $i . ')'; } } // return return $r; } /* * acf_verify_nonce * * This function will look at the $_POST['_acfnonce'] value and return true or false * * @type function * @date 15/10/13 * @since 5.0.0 * * @param $nonce (string) * @return (boolean) */ function acf_verify_nonce( $value, $post_id = 0 ) { // vars $nonce = acf_maybe_get( $_POST, '_acfnonce' ); // bail early if no nonce or if nonce does not match (post|user|comment|term) if( !$nonce || !wp_verify_nonce($nonce, $value) ) { return false; } // if saving specific post if( $post_id ) { // vars $form_post_id = (int) acf_maybe_get( $_POST, 'post_ID' ); $post_parent = wp_is_post_revision( $post_id ); // 1. no $_POST['post_id'] (shopp plugin) if( !$form_post_id ) { // do nothing (don't remove this if statement!) // 2. direct match (this is the post we were editing) } elseif( $post_id === $form_post_id ) { // do nothing (don't remove this if statement!) // 3. revision (this post is a revision of the post we were editing) } elseif( $post_parent === $form_post_id ) { // return true early and prevent $_POST['_acfnonce'] from being reset // this will allow another save_post to save the real post return true; // 4. no match (this post is a custom created one during the save proccess via either WP or 3rd party) } else { // return false early and prevent $_POST['_acfnonce'] from being reset // this will allow another save_post to save the real post return false; } } // reset nonce (only allow 1 save) $_POST['_acfnonce'] = false; // return return true; } /* * acf_verify_ajax * * This function will return true if the current AJAX request is valid * It's action will also allow WPML to set the lang and avoid AJAX get_posts issues * * @type function * @date 7/08/2015 * @since 5.2.3 * * @param n/a * @return (boolean) */ function acf_verify_ajax() { // bail early if not acf action if( empty($_POST['action']) || substr($_POST['action'], 0, 3) !== 'acf' ) { return false; } // bail early if not acf nonce if( empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'acf_nonce') ) { return false; } // action for 3rd party customization do_action('acf/verify_ajax'); // return return true; } /* * acf_add_admin_notice * * This function will add the notice data to a setting in the acf object for the admin_notices action to use * * @type function * @date 17/10/13 * @since 5.0.0 * * @param $text (string) * @param $class (string) * @return (int) message ID (array position) */ function acf_add_admin_notice( $text, $class = '', $wrap = 'p' ) { // vars $admin_notices = acf_get_admin_notices(); // add to array $admin_notices[] = array( 'text' => $text, 'class' => "updated {$class}", 'wrap' => $wrap ); // update acf_update_setting( 'admin_notices', $admin_notices ); // return return ( count( $admin_notices ) - 1 ); } /* * acf_get_admin_notices * * This function will return an array containing any admin notices * * @type function * @date 17/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function acf_get_admin_notices() { // vars $admin_notices = acf_get_setting( 'admin_notices' ); // validate if( !$admin_notices ) { $admin_notices = array(); } // return return $admin_notices; } /* * acf_get_image_sizes * * This function will return an array of available image sizes * * @type function * @date 23/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function acf_get_image_sizes() { // global global $_wp_additional_image_sizes; // vars $sizes = array( 'thumbnail' => __("Thumbnail",'acf'), 'medium' => __("Medium",'acf'), 'large' => __("Large",'acf') ); // find all sizes $all_sizes = get_intermediate_image_sizes(); // add extra registered sizes if( !empty($all_sizes) ) { foreach( $all_sizes as $size ) { // bail early if already in array if( isset($sizes[ $size ]) ) { continue; } // append to array $label = str_replace('-', ' ', $size); $label = ucwords( $label ); $sizes[ $size ] = $label; } } // add sizes foreach( array_keys($sizes) as $s ) { // vars $w = isset($_wp_additional_image_sizes[$s]['width']) ? $_wp_additional_image_sizes[$s]['width'] : get_option( "{$s}_size_w" ); $h = isset($_wp_additional_image_sizes[$s]['height']) ? $_wp_additional_image_sizes[$s]['height'] : get_option( "{$s}_size_h" ); if( $w && $h ) { $sizes[ $s ] .= " ({$w} x {$h})"; } } // add full end $sizes['full'] = __("Full Size",'acf'); // filter for 3rd party customization $sizes = apply_filters( 'acf/get_image_sizes', $sizes ); // return return $sizes; } /* * acf_get_taxonomies * * This function will return an array of available taxonomies * * @type function * @date 7/10/13 * @since 5.0.0 * * @param n/a * @return (array) */ function acf_get_taxonomies() { // get all taxonomies $taxonomies = get_taxonomies( false, 'objects' ); $ignore = array( 'nav_menu', 'link_category' ); $r = array(); // populate $r foreach( $taxonomies as $taxonomy ) { if( in_array($taxonomy->name, $ignore) ) { continue; } $r[ $taxonomy->name ] = $taxonomy->name; //"{$taxonomy->labels->singular_name}"; // ({$taxonomy->name}) } // return return $r; } function acf_get_pretty_taxonomies( $taxonomies = array() ) { // get post types if( empty($taxonomies) ) { // get all custom post types $taxonomies = acf_get_taxonomies(); } // get labels $ref = array(); $r = array(); foreach( array_keys($taxonomies) as $i ) { // vars $taxonomy = acf_extract_var( $taxonomies, $i); $obj = get_taxonomy( $taxonomy ); $name = $obj->labels->singular_name; // append to r $r[ $taxonomy ] = $name; // increase counter if( !isset($ref[ $name ]) ) { $ref[ $name ] = 0; } $ref[ $name ]++; } // get slugs foreach( array_keys($r) as $i ) { // vars $taxonomy = $r[ $i ]; if( $ref[ $taxonomy ] > 1 ) { $r[ $i ] .= ' (' . $i . ')'; } } // return return $r; } /* * acf_get_taxonomy_terms * * This function will return an array of available taxonomy terms * * @type function * @date 7/10/13 * @since 5.0.0 * * @param $taxonomies (array) * @return (array) */ function acf_get_taxonomy_terms( $taxonomies = array() ) { // force array $taxonomies = acf_get_array( $taxonomies ); // get pretty taxonomy names $taxonomies = acf_get_pretty_taxonomies( $taxonomies ); // vars $r = array(); // populate $r foreach( array_keys($taxonomies) as $taxonomy ) { // vars $label = $taxonomies[ $taxonomy ]; $terms = get_terms( $taxonomy, array( 'hide_empty' => false ) ); if( !empty($terms) ) { $r[ $label ] = array(); foreach( $terms as $term ) { $k = "{$taxonomy}:{$term->slug}"; $r[ $label ][ $k ] = $term->name; } } } // return return $r; } /* * acf_decode_taxonomy_terms * * This function decodes the $taxonomy:$term strings into a nested array * * @type function * @date 27/02/2014 * @since 5.0.0 * * @param $terms (array) * @return (array) */ function acf_decode_taxonomy_terms( $terms = false ) { // load all taxonomies if not specified in args if( !$terms ) { $terms = acf_get_taxonomy_terms(); } // vars $r = array(); foreach( $terms as $term ) { // vars $data = acf_decode_taxonomy_term( $term ); // create empty array if( !array_key_exists($data['taxonomy'], $r) ) { $r[ $data['taxonomy'] ] = array(); } // append to taxonomy $r[ $data['taxonomy'] ][] = $data['term']; } // return return $r; } /* * acf_decode_taxonomy_term * * This function will convert a term string into an array of term data * * @type function * @date 31/03/2014 * @since 5.0.0 * * @param $string (string) * @return (array) */ function acf_decode_taxonomy_term( $string ) { // vars $r = array(); // vars $data = explode(':', $string); $taxonomy = 'category'; $term = ''; // check data if( isset($data[1]) ) { $taxonomy = $data[0]; $term = $data[1]; } // add data to $r $r['taxonomy'] = $taxonomy; $r['term'] = $term; // return return $r; } /* * acf_cache_get * * This function is a wrapper for the wp_cache_get to allow for 3rd party customization * * @type function * @date 4/12/2013 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ /* function acf_cache_get( $key, &$found ) { // vars $group = 'acf'; $force = false; // load from cache $cache = wp_cache_get( $key, $group, $force, $found ); // allow 3rd party customization if cache was not found if( !$found ) { $custom = apply_filters("acf/get_cache/{$key}", $cache); if( $custom !== $cache ) { $cache = $custom; $found = true; } } // return return $cache; } */ /* * acf_get_array * * This function will force a variable to become an array * * @type function * @date 4/02/2014 * @since 5.0.0 * * @param $var (mixed) * @return (array) */ function acf_get_array( $var = false, $delimiter = ',' ) { // is array? if( is_array($var) ) { return $var; } // bail early if empty if( empty($var) && !is_numeric($var) ) { return array(); } // string if( is_string($var) && $delimiter ) { return explode($delimiter, $var); } // place in array return array( $var ); } /* * acf_get_posts * * This function will return an array of posts making sure the order is correct * * @type function * @date 3/03/2015 * @since 5.1.5 * * @param $args (array) * @return (array) */ function acf_get_posts( $args = array() ) { // vars $posts = array(); // defaults // leave suppress_filters as true becuase we don't want any plugins to modify the query as we know exactly what $args = acf_parse_args( $args, array( 'posts_per_page' => -1, 'post_type' => '', 'post_status' => 'any' )); // post type if( empty($args['post_type']) ) { $args['post_type'] = acf_get_post_types(); } // validate post__in if( $args['post__in'] ) { // force value to array $args['post__in'] = acf_get_array( $args['post__in'] ); // convert to int $args['post__in'] = array_map('intval', $args['post__in']); // add filter to remove post_type // use 'query' filter so that 'suppress_filters' can remain true //add_filter('query', '_acf_query_remove_post_type'); // order by post__in $args['orderby'] = 'post__in'; } // load posts in 1 query to save multiple DB calls from following code $posts = get_posts($args); // remove this filter (only once) //remove_filter('query', '_acf_query_remove_post_type'); // validate order if( $posts && $args['post__in'] ) { // vars $order = array(); // generate sort order foreach( $posts as $i => $post ) { $order[ $i ] = array_search($post->ID, $args['post__in']); } // sort array_multisort($order, $posts); } // return return $posts; } /* * _acf_query_remove_post_type * * This function will remove the 'wp_posts.post_type' WHERE clause completely * When using 'post__in', this clause is unneccessary and slow. * * @type function * @date 4/03/2015 * @since 5.1.5 * * @param $sql (string) * @return $sql */ function _acf_query_remove_post_type( $sql ) { // global global $wpdb; // bail ealry if no 'wp_posts.ID IN' if( strpos($sql, "$wpdb->posts.ID IN") === false ) { return $sql; } // get bits $glue = 'AND'; $bits = explode($glue, $sql); // loop through $where and remove any post_type queries foreach( $bits as $i => $bit ) { if( strpos($bit, "$wpdb->posts.post_type") !== false ) { unset( $bits[ $i ] ); } } // join $where back together $sql = implode($glue, $bits); // return return $sql; } /* * acf_get_grouped_posts * * This function will return all posts grouped by post_type * This is handy for select settings * * @type function * @date 27/02/2014 * @since 5.0.0 * * @param $args (array) * @return (array) */ function acf_get_grouped_posts( $args ) { // vars $r = array(); // defaults $args = acf_parse_args( $args, array( 'posts_per_page' => -1, 'paged' => 0, 'post_type' => 'post', 'orderby' => 'menu_order title', 'order' => 'ASC', 'post_status' => 'any', 'suppress_filters' => false, 'update_post_meta_cache' => false, )); // find array of post_type $post_types = acf_get_array( $args['post_type'] ); $post_types_labels = acf_get_pretty_post_types($post_types); // attachment doesn't work if it is the only item in an array if( count($post_types) == 1 ) { $args['post_type'] = current($post_types); } // add filter to orderby post type add_filter('posts_orderby', '_acf_orderby_post_type', 10, 2); // get posts $posts = get_posts( $args ); // remove this filter (only once) remove_filter('posts_orderby', '_acf_orderby_post_type'); // loop foreach( $post_types as $post_type ) { // vars $this_posts = array(); $this_group = array(); // populate $this_posts foreach( array_keys($posts) as $key ) { if( $posts[ $key ]->post_type == $post_type ) { $this_posts[] = acf_extract_var( $posts, $key ); } } // bail early if no posts for this post type if( empty($this_posts) ) { continue; } // sort into hierachial order! // this will fail if a search has taken place because parents wont exist if( is_post_type_hierarchical($post_type) && empty($args['s'])) { // vars $match_id = $this_posts[ 0 ]->ID; $offset = 0; $length = count($this_posts); $parent = acf_maybe_get( $args, 'post_parent', 0 ); // reset $this_posts $this_posts = array(); // get all posts $all_args = array_merge($args, array( 'posts_per_page' => -1, 'paged' => 0, 'post_type' => $post_type )); $all_posts = get_posts( $all_args ); // loop over posts and update $offset foreach( $all_posts as $offset => $p ) { if( $p->ID == $match_id ) { break; } } // order posts $all_posts = get_page_children( $parent, $all_posts ); // append for( $i = $offset; $i < ($offset + $length); $i++ ) { $this_posts[] = acf_extract_var( $all_posts, $i); } } // populate $this_posts foreach( array_keys($this_posts) as $key ) { // extract post $post = acf_extract_var( $this_posts, $key ); // add to group $this_group[ $post->ID ] = $post; } // group by post type $post_type_name = $post_types_labels[ $post_type ]; $r[ $post_type_name ] = $this_group; } // return return $r; } function _acf_orderby_post_type( $ordeby, $wp_query ) { // global global $wpdb; // get post types $post_types = $wp_query->get('post_type'); // prepend SQL if( is_array($post_types) ) { $post_types = implode("','", $post_types); $ordeby = "FIELD({$wpdb->posts}.post_type,'$post_types')," . $ordeby; } // return return $ordeby; } function acf_get_post_title( $post = 0 ) { // load post if given an ID if( is_numeric($post) ) { $post = get_post($post); } // title $title = get_the_title( $post->ID ); // empty if( $title === '' ) { $title = __('(no title)', 'acf'); } // ancestors if( $post->post_type != 'attachment' ) { $ancestors = get_ancestors( $post->ID, $post->post_type ); $title = str_repeat('- ', count($ancestors)) . $title; } // status if( get_post_status( $post->ID ) != "publish" ) { $title .= ' (' . get_post_status( $post->ID ) . ')'; } // return return $title; } function acf_order_by_search( $array, $search ) { // vars $weights = array(); $needle = strtolower( $search ); // add key prefix foreach( array_keys($array) as $k ) { $array[ '_' . $k ] = acf_extract_var( $array, $k ); } // add search weight foreach( $array as $k => $v ) { // vars $weight = 0; $haystack = strtolower( $v ); $strpos = strpos( $haystack, $needle ); // detect search match if( $strpos !== false ) { // set eright to length of match $weight = strlen( $search ); // increase weight if match starts at begining of string if( $strpos == 0 ) { $weight++; } } // append to wights $weights[ $k ] = $weight; } // sort the array with menu_order ascending array_multisort( $weights, SORT_DESC, $array ); // remove key prefix foreach( array_keys($array) as $k ) { $array[ substr($k,1) ] = acf_extract_var( $array, $k ); } // return return $array; } /* * acf_json_encode * * This function will return pretty JSON for all PHP versions * * @type function * @date 6/03/2014 * @since 5.0.0 * * @param $json (array) * @return (string) */ function acf_json_encode( $json ) { // PHP at least 5.4 if( version_compare(PHP_VERSION, '5.4.0', '>=') ) { return json_encode($json, JSON_PRETTY_PRINT); } // PHP less than 5.4 $json = json_encode($json); // http://snipplr.com/view.php?codeview&id=60559 $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = " "; $newLine = "\n"; $prevChar = ''; $outOfQuotes = true; for ($i=0; $i<=$strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && $prevChar != '\\') { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } else if(($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos --; for ($j=0; $j<$pos; $j++) { $result .= $indentStr; } } // Add the character to the result string. $result .= $char; // If this character is ':' adda space after it if($char == ':' && $outOfQuotes) { $result .= ' '; } // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos ++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } $prevChar = $char; } // return return $result; } /* * acf_str_exists * * This function will return true if a sub string is found * * @type function * @date 1/05/2014 * @since 5.0.0 * * @param $needle (string) * @param $haystack (string) * @return (boolean) */ function acf_str_exists( $needle, $haystack ) { // return true if $haystack contains the $needle if( is_string($haystack) && strpos($haystack, $needle) !== false ) { return true; } // return return false; } /* * acf_debug * * description * * @type function * @date 2/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_debug() { // vars $args = func_get_args(); $s = array_shift($args); $o = ''; $nl = "\r\n"; // start script $o .= '<script type="text/javascript">' . $nl; $o .= 'console.log("' . $s . '"'; if( !empty($args) ) { foreach( $args as $arg ) { if( is_object($arg) || is_array($arg) ) { $arg = json_encode($arg); } elseif( is_bool($arg) ) { $arg = $arg ? 'true' : 'false'; }elseif( is_string($arg) ) { $arg = '"' . $arg . '"'; } $o .= ', ' . $arg; } } $o .= ');' . $nl; // end script $o .= '</script>' . $nl; // echo echo $o; } function acf_debug_start() { acf_update_setting( 'debug_start', memory_get_usage()); } function acf_debug_end() { $start = acf_get_setting( 'debug_start' ); $end = memory_get_usage(); return $end - $start; } /* * acf_get_updates * * This function will reutrn all or relevant updates for ACF * * @type function * @date 12/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_updates() { // vars $updates = array(); $plugin_version = acf_get_setting('version'); $acf_version = get_option('acf_version'); $path = acf_get_path('admin/updates'); // bail early if no version (not activated) if( !$acf_version ) { return false; } // check that path exists if( !file_exists( $path ) ) { return false; } $dir = opendir( $path ); while(false !== ( $file = readdir($dir)) ) { // only php files if( substr($file, -4) !== '.php' ) { continue; } // get version number $update_version = substr($file, 0, -4); // ignore if update is for a future version. May exist for testing if( version_compare( $update_version, $plugin_version, '>') ) { continue; } // ignore if update has already been run if( version_compare( $update_version, $acf_version, '<=') ) { continue; } // append $updates[] = $update_version; } // return return $updates; } /* * acf_encode_choices * * description * * @type function * @date 4/06/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_encode_choices( $array = array() ) { // bail early if not array if( !is_array($array) ) { return $array; } // vars $string = ''; if( !empty($array) ) { foreach( $array as $k => $v ) { if( $k !== $v ) { $array[ $k ] = $k . ' : ' . $v; } } $string = implode("\n", $array); } // return return $string; } function acf_decode_choices( $string = '' ) { // validate if( $string === '') { return array(); // force array on single numeric values } elseif( is_numeric($string) ) { return array( $string ); // bail early if not a a string } elseif( !is_string($string) ) { return $string; } // vars $array = array(); // explode $lines = explode("\n", $string); // key => value foreach( $lines as $line ) { // vars $k = trim($line); $v = trim($line); // look for ' : ' if( acf_str_exists(' : ', $line) ) { $line = explode(' : ', $line); $k = trim($line[0]); $v = trim($line[1]); } // append $array[ $k ] = $v; } // return return $array; } /* * acf_convert_date_to_php * * This fucntion converts a date format string from JS to PHP * * @type function * @date 20/06/2014 * @since 5.0.0 * * @param $date (string) * @return $date (string) */ acf_update_setting('php_to_js_date_formats', array( // Year 'Y' => 'yy', // Numeric, 4 digits 1999, 2003 'y' => 'y', // Numeric, 2 digits 99, 03 // Month 'm' => 'mm', // Numeric, with leading zeros 01–12 'n' => 'm', // Numeric, without leading zeros 1–12 'F' => 'MM', // Textual full January – December 'M' => 'M', // Textual three letters Jan - Dec // Weekday 'l' => 'DD', // Full name (lowercase 'L') Sunday – Saturday 'D' => 'D', // Three letter name Mon – Sun // Day of Month 'd' => 'dd', // Numeric, with leading zeros 01–31 'j' => 'd', // Numeric, without leading zeros 1–31 'S' => '', // The English suffix for the day of the month st, nd or th in the 1st, 2nd or 15th. )); function acf_convert_date_to_php( $date ) { // vars $ignore = array(); // conversion $php_to_js = acf_get_setting('php_to_js_date_formats'); // loop over conversions foreach( $php_to_js as $replace => $search ) { // ignore this replace? if( in_array($search, $ignore) ) { continue; } // replace $date = str_replace($search, $replace, $date); // append to ignore $ignore[] = $replace; } // return return $date; } /* * acf_convert_date_to_js * * This fucntion converts a date format string from PHP to JS * * @type function * @date 20/06/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_convert_date_to_js( $date ) { // vars $ignore = array(); // conversion $php_to_js = acf_get_setting('php_to_js_date_formats'); // loop over conversions foreach( $php_to_js as $search => $replace ) { // ignore this replace? if( in_array($search, $ignore) ) { continue; } // replace $date = str_replace($search, $replace, $date); // append to ignore $ignore[] = $replace; } // return return $date; } /* * acf_update_user_setting * * description * * @type function * @date 15/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_update_user_setting( $name, $value ) { // get current user id $user_id = get_current_user_id(); // get user settings $settings = get_user_meta( $user_id, 'acf_user_settings', false ); // find settings if( isset($settings[0]) ) { $settings = $settings[0]; } else { $settings = array(); } // append setting $settings[ $name ] = $value; // update user data return update_metadata('user', $user_id, 'acf_user_settings', $settings); } /* * acf_get_user_setting * * description * * @type function * @date 15/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_user_setting( $name = '', $default = false ) { // get current user id $user_id = get_current_user_id(); // get user settings $settings = get_user_meta( $user_id, 'acf_user_settings', false ); // bail arly if no settings if( empty($settings[0][$name]) ) { return $default; } // return return $settings[0][$name]; } /* * acf_in_array * * description * * @type function * @date 22/07/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_in_array( $value, $array ) { // bail early if not array if( !is_array($array) ) { return false; } // find value in array return in_array($value, $array); } /* * acf_get_valid_post_id * * This function will return a valid post_id based on the current screen / parameter * * @type function * @date 8/12/2013 * @since 5.0.0 * * @param $post_id (mixed) * @return $post_id (mixed) */ function acf_get_valid_post_id( $post_id = 0 ) { // set post_id to global if( !$post_id ) { $post_id = (int) get_the_ID(); } // allow for option == options if( $post_id == 'option' ) { $post_id = 'options'; } // $post_id may be an object if( is_object($post_id) ) { if( isset($post_id->roles, $post_id->ID) ) { $post_id = 'user_' . $post_id->ID; } elseif( isset($post_id->taxonomy, $post_id->term_id) ) { $post_id = $post_id->taxonomy . '_' . $post_id->term_id; } elseif( isset($post_id->comment_ID) ) { $post_id = 'comment_' . $post_id->comment_ID; } elseif( isset($post_id->ID) ) { $post_id = $post_id->ID; } } // append language code if( $post_id == 'options' ) { $dl = acf_get_setting('default_language'); $cl = acf_get_setting('current_language'); if( $cl && $cl !== $dl ) { $post_id .= '_' . $cl; } } /* * Override for preview * * If the $_GET['preview_id'] is set, then the user wants to see the preview data. * There is also the case of previewing a page with post_id = 1, but using get_field * to load data from another post_id. * In this case, we need to make sure that the autosave revision is actually related * to the $post_id variable. If they match, then the autosave data will be used, otherwise, * the user wants to load data from a completely different post_id */ if( isset($_GET['preview_id']) ) { $autosave = wp_get_post_autosave( $_GET['preview_id'] ); if( $autosave && $autosave->post_parent == $post_id ) { $post_id = (int) $autosave->ID; } } // return return $post_id; } /* * acf_upload_files * * This function will walk througfh the $_FILES data and upload each found * * @type function * @date 25/10/2014 * @since 5.0.9 * * @param $ancestors (array) an internal parameter, not required * @return n/a */ function acf_upload_files( $ancestors = array() ) { // vars $file = array( 'name' => '', 'type' => '', 'tmp_name' => '', 'error' => '', 'size' => '' ); // populate with $_FILES data foreach( array_keys($file) as $k ) { $file[ $k ] = $_FILES['acf'][ $k ]; } // walk through ancestors if( !empty($ancestors) ) { foreach( $ancestors as $a ) { foreach( array_keys($file) as $k ) { $file[ $k ] = $file[ $k ][ $a ]; } } } // is array? if( is_array($file['name']) ) { foreach( array_keys($file['name']) as $k ) { $_ancestors = array_merge($ancestors, array($k)); acf_upload_files( $_ancestors ); } return; } // bail ealry if file has error (no file uploaded) if( $file['error'] ) { return; } // assign global _acfuploader for media validation $_POST['_acfuploader'] = end($ancestors); // file found! $attachment_id = acf_upload_file( $file ); // update $_POST array_unshift($ancestors, 'acf'); acf_update_nested_array( $_POST, $ancestors, $attachment_id ); } /* * acf_upload_file * * This function will uploade a $_FILE * * @type function * @date 27/10/2014 * @since 5.0.9 * * @param $uploaded_file (array) array found from $_FILE data * @return $id (int) new attachment ID */ function acf_upload_file( $uploaded_file ) { // required require_once(ABSPATH . "/wp-load.php"); require_once(ABSPATH . "/wp-admin/includes/file.php"); require_once(ABSPATH . "/wp-admin/includes/image.php"); // required for wp_handle_upload() to upload the file $upload_overrides = array( 'test_form' => false ); // upload $file = wp_handle_upload( $uploaded_file, $upload_overrides ); // bail ealry if upload failed if( isset($file['error']) ) { return $file['error']; } // vars $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = basename($file); // Construct the object array $object = array( 'post_title' => $filename, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'acf-upload' ); // Save the data $id = wp_insert_attachment($object, $file); // Add the meta-data wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); /** This action is documented in wp-admin/custom-header.php */ do_action( 'wp_create_file_in_uploads', $file, $id ); // For replication // return new ID return $id; } /* * acf_update_nested_array * * This function will update a nested array value. Useful for modifying the $_POST array * * @type function * @date 27/10/2014 * @since 5.0.9 * * @param $array (array) target array to be updated * @param $ancestors (array) array of keys to navigate through to find the child * @param $value (mixed) The new value * @return (boolean) */ function acf_update_nested_array( &$array, $ancestors, $value ) { // if no more ancestors, update the current var if( empty($ancestors) ) { $array = $value; // return return true; } // shift the next ancestor from the array $k = array_shift( $ancestors ); // if exists if( isset($array[ $k ]) ) { return acf_update_nested_array( $array[ $k ], $ancestors, $value ); } // return return false; } /* * acf_is_screen * * This function will return true if all args are matched for the current screen * * @type function * @date 9/12/2014 * @since 5.1.5 * * @param $post_id (int) * @return $post_id (int) */ function acf_is_screen( $id = '' ) { // vars $current_screen = get_current_screen(); // return return ($id === $current_screen->id); } /* * acf_maybe_get * * This function will return a var if it exists in an array * * @type function * @date 9/12/2014 * @since 5.1.5 * * @param $array (array) the array to look within * @param $key (key) the array key to look for. Nested values may be found using '/' * @param $default (mixed) the value returned if not found * @return $post_id (int) */ function acf_maybe_get( $array, $key, $default = null ) { // vars $keys = explode('/', $key); // loop through keys foreach( $keys as $k ) { // return default if does not exist if( !isset($array[ $k ]) ) { return $default; } // update $array $array = $array[ $k ]; } // return return $array; } /* * acf_get_attachment * * This function will return an array of attachment data * * @type function * @date 5/01/2015 * @since 5.1.5 * * @param $post (mixed) either post ID or post object * @return (array) */ function acf_get_attachment( $post ) { // get post if ( !$post = get_post( $post ) ) { return false; } // vars $thumb_id = 0; $id = $post->ID; $a = array( 'ID' => $id, 'id' => $id, 'title' => $post->post_title, 'filename' => wp_basename( $post->guid ), 'url' => wp_get_attachment_url( $id ), 'alt' => get_post_meta($id, '_wp_attachment_image_alt', true), 'author' => $post->post_author, 'description' => $post->post_content, 'caption' => $post->post_excerpt, 'name' => $post->post_name, 'date' => $post->post_date_gmt, 'modified' => $post->post_modified_gmt, 'mime_type' => $post->post_mime_type, 'type' => acf_maybe_get( explode('/', $post->post_mime_type), 0, '' ), 'icon' => wp_mime_type_icon( $id ) ); // video may use featured image if( $a['type'] === 'image' ) { $thumb_id = $id; $src = wp_get_attachment_image_src( $id, 'full' ); $a['url'] = $src[0]; $a['width'] = $src[1]; $a['height'] = $src[2]; } elseif( $a['type'] === 'audio' || $a['type'] === 'video' ) { // video dimentions if( $a['type'] == 'video' ) { $meta = wp_get_attachment_metadata( $id ); $a['width'] = acf_maybe_get($meta, 'width', 0); $a['height'] = acf_maybe_get($meta, 'height', 0); } // feature image if( $featured_id = get_post_thumbnail_id($id) ) { $thumb_id = $featured_id; } } // sizes if( $thumb_id ) { // find all image sizes if( $sizes = get_intermediate_image_sizes() ) { $a['sizes'] = array(); foreach( $sizes as $size ) { // url $src = wp_get_attachment_image_src( $thumb_id, $size ); // add src $a['sizes'][ $size ] = $src[0]; $a['sizes'][ $size . '-width' ] = $src[1]; $a['sizes'][ $size . '-height' ] = $src[2]; } } } // return return $a; } /* * acf_get_truncated * * This function will truncate and return a string * * @type function * @date 8/08/2014 * @since 5.0.0 * * @param $text (string) * @param $length (int) * @return (string) */ function acf_get_truncated( $text, $length = 64 ) { // vars $text = trim($text); $the_length = strlen( $text ); // cut $return = substr( $text, 0, ($length - 3) ); // ... if( $the_length > ($length - 3) ) { $return .= '...'; } // return return $return; } /* * acf_get_current_url * * This function will return the current URL * * @type function * @date 23/01/2015 * @since 5.1.5 * * @param n/a * @return (string) */ function acf_get_current_url() { // vars $home = home_url(); $url = home_url($_SERVER['REQUEST_URI']); // test //$home = 'http://acf5/dev/wp-admin'; //$url = $home . '/dev/wp-admin/api-template/acf_form'; // explode url (4th bit is the sub folder) $bits = explode('/', $home, 4); /* Array ( [0] => http: [1] => [2] => acf5 [3] => dev ) */ // handle sub folder if( !empty($bits[3]) ) { $find = '/' . $bits[3]; $pos = strpos($url, $find); $length = strlen($find); if( $pos !== false ) { $url = substr_replace($url, '', $pos, $length); } } // return return $url; } /* * acf_current_user_can_admin * * This function will return true if the current user can administrate the ACF field groups * * @type function * @date 9/02/2015 * @since 5.1.5 * * @param $post_id (int) * @return $post_id (int) */ function acf_current_user_can_admin() { if( acf_get_setting('show_admin') && current_user_can(acf_get_setting('capability')) ) { return true; } // return return false; } /* * acf_get_filesize * * This function will return a numeric value of bytes for a given filesize string * * @type function * @date 18/02/2015 * @since 5.1.5 * * @param $size (mixed) * @return (int) */ function acf_get_filesize( $size = 1 ) { // vars $unit = 'MB'; $units = array( 'TB' => 4, 'GB' => 3, 'MB' => 2, 'KB' => 1, ); // look for $unit within the $size parameter (123 KB) if( is_string($size) ) { // vars $custom = strtoupper( substr($size, -2) ); foreach( $units as $k => $v ) { if( $custom === $k ) { $unit = $k; $size = substr($size, 0, -2); } } } // calc bytes $bytes = floatval($size) * pow(1024, $units[$unit]); // return return $bytes; } /* * acf_format_filesize * * This function will return a formatted string containing the filesize and unit * * @type function * @date 18/02/2015 * @since 5.1.5 * * @param $size (mixed) * @return (int) */ function acf_format_filesize( $size = 1 ) { // convert $bytes = acf_get_filesize( $size ); // vars $units = array( 'TB' => 4, 'GB' => 3, 'MB' => 2, 'KB' => 1, ); // loop through units foreach( $units as $k => $v ) { $result = $bytes / pow(1024, $v); if( $result >= 1 ) { return $result . ' ' . $k; } } // return return $bytes . ' B'; } /* * acf_get_valid_terms * * This function will replace old terms with new split term ids * * @type function * @date 27/02/2015 * @since 5.1.5 * * @param $terms (int|array) * @param $taxonomy (string) * @return $terms */ function acf_get_valid_terms( $terms = false, $taxonomy = 'category' ) { // bail early if function does not yet exist or if( !function_exists('wp_get_split_term') || empty($terms) ) { return $terms; } // vars $is_array = is_array($terms); // force into array $terms = acf_get_array( $terms ); // force ints $terms = array_map('intval', $terms); // attempt to find new terms foreach( $terms as $i => $term_id ) { $new_term_id = wp_get_split_term($term_id, $taxonomy); if( $new_term_id ) { $terms[ $i ] = $new_term_id; } } // revert array if needed if( !$is_array ) { $terms = $terms[0]; } // return return $terms; } /* * acf_esc_html_deep * * Navigates through an array and escapes html from the values. * * @type function * @date 10/06/2015 * @since 5.2.7 * * @param $value (mixed) * @return $value */ /* function acf_esc_html_deep( $value ) { // array if( is_array($value) ) { $value = array_map('acf_esc_html_deep', $value); // object } elseif( is_object($value) ) { $vars = get_object_vars( $value ); foreach( $vars as $k => $v ) { $value->{$k} = acf_esc_html_deep( $v ); } // string } elseif( is_string($value) ) { $value = esc_html($value); } // return return $value; } */ /* * acf_validate_attachment * * This function will validate an attachment based on a field's resrictions and return an array of errors * * @type function * @date 3/07/2015 * @since 5.2.3 * * @param $attachment (array) attachment data. Cahnges based on context * @param $field (array) field settings containing restrictions * @param $context (string) $file is different when uploading / preparing * @return $errors (array) */ function acf_validate_attachment( $attachment, $field, $context = 'prepare' ) { // vars $errors = array(); $file = array( 'type' => '', 'width' => 0, 'height' => 0, 'size' => 0 ); // upload if( $context == 'upload' ) { // vars $file['type'] = pathinfo($attachment['name'], PATHINFO_EXTENSION); $file['size'] = filesize($attachment['tmp_name']); if( strpos($attachment['type'], 'image') !== false ) { $size = getimagesize($attachment['tmp_name']); $file['width'] = acf_maybe_get($size, 0); $file['height'] = acf_maybe_get($size, 1); } // prepare } elseif( $context == 'prepare' ) { $file['type'] = pathinfo($attachment['url'], PATHINFO_EXTENSION); $file['size'] = acf_maybe_get($attachment, 'filesizeInBytes', 0); $file['width'] = acf_maybe_get($attachment, 'width', 0); $file['height'] = acf_maybe_get($attachment, 'height', 0); // custom } else { $file = wp_parse_args($file, $attachment); } // image if( $file['width'] || $file['height'] ) { // width $min_width = (int) acf_maybe_get($field, 'min_width', 0); $max_width = (int) acf_maybe_get($field, 'max_width', 0); if( $file['width'] ) { if( $min_width && $file['width'] < $min_width ) { // min width $errors['min_width'] = sprintf(__('Image width must be at least %dpx.', 'acf'), $min_width ); } elseif( $max_width && $file['width'] > $max_width ) { // min width $errors['max_width'] = sprintf(__('Image width must not exceed %dpx.', 'acf'), $max_width ); } } // height $min_height = (int) acf_maybe_get($field, 'min_height', 0); $max_height = (int) acf_maybe_get($field, 'max_height', 0); if( $file['height'] ) { if( $min_height && $file['height'] < $min_height ) { // min height $errors['min_height'] = sprintf(__('Image height must be at least %dpx.', 'acf'), $min_height ); } elseif( $max_height && $file['height'] > $max_height ) { // min height $errors['max_height'] = sprintf(__('Image height must not exceed %dpx.', 'acf'), $max_height ); } } } // file size if( $file['size'] ) { $min_size = acf_maybe_get($field, 'min_size', 0); $max_size = acf_maybe_get($field, 'max_size', 0); if( $min_size && $file['size'] < acf_get_filesize($min_size) ) { // min width $errors['min_size'] = sprintf(__('File size must be at least %s.', 'acf'), acf_format_filesize($min_size) ); } elseif( $max_size && $file['size'] > acf_get_filesize($max_size) ) { // min width $errors['max_size'] = sprintf(__('File size must must not exceed %s.', 'acf'), acf_format_filesize($max_size) ); } } // file type if( $file['type'] ) { $mime_types = acf_maybe_get($field, 'mime_types', ''); // lower case $file['type'] = strtolower($file['type']); $mime_types = strtolower($mime_types); // explode $mime_types = str_replace(array(' ', '.'), '', $mime_types); $mime_types = explode(',', $mime_types); // split pieces $mime_types = array_filter($mime_types); // remove empty pieces if( !empty($mime_types) && !in_array($file['type'], $mime_types) ) { // glue together last 2 types if( count($mime_types) > 1 ) { $last1 = array_pop($mime_types); $last2 = array_pop($mime_types); $mime_types[] = $last2 . ' ' . __('or', 'acf') . ' ' . $last1; } $errors['mime_types'] = sprintf(__('File type must be %s.', 'acf'), implode(', ', $mime_types) ); } } // filter for 3rd party customization $errors = apply_filters("acf/validate_attachment", $errors, $file, $attachment, $field); $errors = apply_filters("acf/validate_attachment/type={$field['type']}", $errors, $file, $attachment, $field ); $errors = apply_filters("acf/validate_attachment/name={$field['name']}", $errors, $file, $attachment, $field ); $errors = apply_filters("acf/validate_attachment/key={$field['key']}", $errors, $file, $attachment, $field ); // return return $errors; } /* * _acf_settings_uploader * * Dynamic logic for uploader setting * * @type function * @date 7/05/2015 * @since 5.2.3 * * @param $uploader (string) * @return $uploader */ add_filter('acf/settings/uploader', '_acf_settings_uploader'); function _acf_settings_uploader( $uploader ) { // if can't upload files if( !current_user_can('upload_files') ) { $uploader = 'basic'; } // return return $uploader; } /* * Hacks * * description * * @type function * @date 17/01/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ add_filter("acf/settings/slug", '_acf_settings_slug'); function _acf_settings_slug( $v ) { $basename = acf_get_setting('basename'); $slug = explode('/', $basename); $slug = current($slug); return $slug; } ?>
Java
<?xml version="1.0" encoding="UTF-8" ?> <!-- If you are working with a multi language form keep the order! <option lang="de">Deutschland</option> <option lang="de">Groß Britannien</option> <option lang="en">Germany</option> <option lang="en">United Kingdom</option> If you don't keep the order and the user switches the country you will have a wrong translation! --> <select_countries> <option lang="de">Deutschland</option> <option lang="de">Groß Britannien</option> <option lang="de">Frankreich</option> <option lang="de">Österreich</option> <option lang="en">Germany</option> <option lang="en">United Kingdom</option> <option lang="en">France</option> <option lang="en">Austria</option> </select_countries>
Java
import { Query } from "../services"; export interface QueryState { queries?: Query[]; loading?: boolean; error?: String; visibilityFilter?: string; }
Java
<?php /** * AmanCMS * * LICENSE * * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-2.0.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@amancms.com so we can send you a copy immediately. * * @copyright Copyright (c) 2010-2012 KhanSoft Limited (http://www.khansoft.com) * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2 * @version $Id: Rss.php 5048 2010-08-28 18:15:15Z mehrab $ */ class News_Services_Rss { /** * Cache time * @const string */ const CACHE_TIME = 3600; const LIMIT = 20; /** * Get RSS output that show latest activated articles * * @param int $categoryId Id of categories * @param string $lang (since 2.0.8) * @return string */ public static function feed($categoryId = null, $lang) { $config = Aman_Config::getConfig(); $baseUrl = $config->web->url->base; $prefix = AMAN_TEMP_DIR . DS . 'cache' . DS . $lang . '_news_rss_'; $file = (null == $categoryId) ? $prefix . 'latest.xml' : $prefix . 'category_' . $categoryId . '.xml'; if (Aman_Cache_File::isFileNewerThan($file, time() - self::CACHE_TIME)) { $output = file_get_contents($file); return $output; } /** * Get the latest articles */ $conn = Aman_Db_Connection::factory()->getSlaveConnection(); $category = null; if ($categoryId) { $categoryDao = Aman_Model_Dao_Factory::getInstance()->setModule('category')->getCategoryDao(); $categoryDao->setDbConnection($conn); $category = $categoryDao->getById($categoryId); } $exp = array('status' => 'active'); if ($categoryId) { $exp['category_id'] = $categoryId; } $articleDao = Aman_Model_Dao_Factory::getInstance()->setModule('news')->getArticleDao(); $articleDao->setDbConnection($conn); $articleDao->setLang($lang); $articles = $articleDao->find(0, self::LIMIT, $exp); $newsConfig = Aman_Module_Config::getConfig('news'); /** * Create RSS items ... */ $router = Zend_Controller_Front::getInstance()->getRouter(); $entries = array(); if ($articles != null && count($articles) > 0) { foreach ($articles as $article) { $link = $router->assemble($article->getProperties(), 'news_article_details'); $description = $article->description; $image = $article->image_thumbnail; $description = (null == $image || '' == $image) ? $description : '<a href="' . $baseUrl . $link . '" title="' . addslashes($article->title) . '"><img src="' . $image . '" alt="' . addslashes($article->title) . '" /></a>' . $description; $entry = array( 'title' => $article->title, 'guid' => $baseUrl . $link, 'link' => $baseUrl . $link, 'description' => $description, 'lastUpdate' => strtotime($article->activate_date), ); $entries[] = $entry; } } /** * ... and write to file */ $link = (null == $category) ? $baseUrl : $baseUrl.$router->assemble($category->getProperties(), 'news_article_category'); $generator = ($newsConfig->rss->channel_generator != '') ? $newsConfig->rss->channel_generator : 'AmanCMS v' . Aman_Version::getVersion(); $buildDate = strtotime(date('D, d M Y h:i:s')); $data = array( 'title' => $newsConfig->rss->channel_title, 'link' => $link, 'description' => $newsConfig->rss->channel_description, 'copyright' => $newsConfig->rss->channel_copyright, 'generator' => $generator, 'lastUpdate' => $buildDate, 'published' => $buildDate, 'charset' => 'UTF-8', 'entries' => $entries, ); $feed = Zend_Feed::importArray($data, 'rss'); $rssFeed = $feed->saveXML(); $fh = fopen($file, 'w'); fwrite($fh, $rssFeed); fclose($fh); return $rssFeed; } }
Java
/* * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc. * Copyright (c) 2008 Dave Chinner * All Rights Reserved. * * 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. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_mount.h" #include "xfs_trans.h" #include "xfs_trans_priv.h" #include "xfs_trace.h" #include "xfs_error.h" #include "xfs_log.h" #ifdef DEBUG /* * Check that the list is sorted as it should be. */ STATIC void xfs_ail_check( struct xfs_ail *ailp, xfs_log_item_t *lip) { xfs_log_item_t *prev_lip; if (list_empty(&ailp->xa_ail)) return; /* * Check the next and previous entries are valid. */ ASSERT((lip->li_flags & XFS_LI_IN_AIL) != 0); prev_lip = list_entry(lip->li_ail.prev, xfs_log_item_t, li_ail); if (&prev_lip->li_ail != &ailp->xa_ail) ASSERT(XFS_LSN_CMP(prev_lip->li_lsn, lip->li_lsn) <= 0); prev_lip = list_entry(lip->li_ail.next, xfs_log_item_t, li_ail); if (&prev_lip->li_ail != &ailp->xa_ail) ASSERT(XFS_LSN_CMP(prev_lip->li_lsn, lip->li_lsn) >= 0); } #else /* !DEBUG */ #define xfs_ail_check(a,l) #endif /* DEBUG */ /* * Return a pointer to the last item in the AIL. If the AIL is empty, then * return NULL. */ static xfs_log_item_t * xfs_ail_max( struct xfs_ail *ailp) { if (list_empty(&ailp->xa_ail)) return NULL; return list_entry(ailp->xa_ail.prev, xfs_log_item_t, li_ail); } /* * Return a pointer to the item which follows the given item in the AIL. If * the given item is the last item in the list, then return NULL. */ static xfs_log_item_t * xfs_ail_next( struct xfs_ail *ailp, xfs_log_item_t *lip) { if (lip->li_ail.next == &ailp->xa_ail) return NULL; return list_first_entry(&lip->li_ail, xfs_log_item_t, li_ail); } /* * This is called by the log manager code to determine the LSN of the tail of * the log. This is exactly the LSN of the first item in the AIL. If the AIL * is empty, then this function returns 0. * * We need the AIL lock in order to get a coherent read of the lsn of the last * item in the AIL. */ xfs_lsn_t xfs_ail_min_lsn( struct xfs_ail *ailp) { xfs_lsn_t lsn = 0; xfs_log_item_t *lip; spin_lock(&ailp->xa_lock); lip = xfs_ail_min(ailp); if (lip) lsn = lip->li_lsn; spin_unlock(&ailp->xa_lock); return lsn; } /* * Return the maximum lsn held in the AIL, or zero if the AIL is empty. */ static xfs_lsn_t xfs_ail_max_lsn( struct xfs_ail *ailp) { xfs_lsn_t lsn = 0; xfs_log_item_t *lip; spin_lock(&ailp->xa_lock); lip = xfs_ail_max(ailp); if (lip) lsn = lip->li_lsn; spin_unlock(&ailp->xa_lock); return lsn; } /* * The cursor keeps track of where our current traversal is up to by tracking * the next item in the list for us. However, for this to be safe, removing an * object from the AIL needs to invalidate any cursor that points to it. hence * the traversal cursor needs to be linked to the struct xfs_ail so that * deletion can search all the active cursors for invalidation. */ STATIC void xfs_trans_ail_cursor_init( struct xfs_ail *ailp, struct xfs_ail_cursor *cur) { cur->item = NULL; list_add_tail(&cur->list, &ailp->xa_cursors); } /* * Get the next item in the traversal and advance the cursor. If the cursor * was invalidated (indicated by a lip of 1), restart the traversal. */ struct xfs_log_item * xfs_trans_ail_cursor_next( struct xfs_ail *ailp, struct xfs_ail_cursor *cur) { struct xfs_log_item *lip = cur->item; if ((__psint_t)lip & 1) lip = xfs_ail_min(ailp); if (lip) cur->item = xfs_ail_next(ailp, lip); return lip; } /* * When the traversal is complete, we need to remove the cursor from the list * of traversing cursors. */ void xfs_trans_ail_cursor_done( struct xfs_ail_cursor *cur) { cur->item = NULL; list_del_init(&cur->list); } /* * Invalidate any cursor that is pointing to this item. This is called when an * item is removed from the AIL. Any cursor pointing to this object is now * invalid and the traversal needs to be terminated so it doesn't reference a * freed object. We set the low bit of the cursor item pointer so we can * distinguish between an invalidation and the end of the list when getting the * next item from the cursor. */ STATIC void xfs_trans_ail_cursor_clear( struct xfs_ail *ailp, struct xfs_log_item *lip) { struct xfs_ail_cursor *cur; list_for_each_entry(cur, &ailp->xa_cursors, list) { if (cur->item == lip) cur->item = (struct xfs_log_item *) ((__psint_t)cur->item | 1); } } /* * Find the first item in the AIL with the given @lsn by searching in ascending * LSN order and initialise the cursor to point to the next item for a * ascending traversal. Pass a @lsn of zero to initialise the cursor to the * first item in the AIL. Returns NULL if the list is empty. */ xfs_log_item_t * xfs_trans_ail_cursor_first( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, xfs_lsn_t lsn) { xfs_log_item_t *lip; xfs_trans_ail_cursor_init(ailp, cur); if (lsn == 0) { lip = xfs_ail_min(ailp); goto out; } list_for_each_entry(lip, &ailp->xa_ail, li_ail) { if (XFS_LSN_CMP(lip->li_lsn, lsn) >= 0) goto out; } return NULL; out: if (lip) cur->item = xfs_ail_next(ailp, lip); return lip; } static struct xfs_log_item * __xfs_trans_ail_cursor_last( struct xfs_ail *ailp, xfs_lsn_t lsn) { xfs_log_item_t *lip; list_for_each_entry_reverse(lip, &ailp->xa_ail, li_ail) { if (XFS_LSN_CMP(lip->li_lsn, lsn) <= 0) return lip; } return NULL; } /* * Find the last item in the AIL with the given @lsn by searching in descending * LSN order and initialise the cursor to point to that item. If there is no * item with the value of @lsn, then it sets the cursor to the last item with an * LSN lower than @lsn. Returns NULL if the list is empty. */ struct xfs_log_item * xfs_trans_ail_cursor_last( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, xfs_lsn_t lsn) { xfs_trans_ail_cursor_init(ailp, cur); cur->item = __xfs_trans_ail_cursor_last(ailp, lsn); return cur->item; } /* * Splice the log item list into the AIL at the given LSN. We splice to the * tail of the given LSN to maintain insert order for push traversals. The * cursor is optional, allowing repeated updates to the same LSN to avoid * repeated traversals. This should not be called with an empty list. */ static void xfs_ail_splice( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, struct list_head *list, xfs_lsn_t lsn) { struct xfs_log_item *lip; ASSERT(!list_empty(list)); /* * Use the cursor to determine the insertion point if one is * provided. If not, or if the one we got is not valid, * find the place in the AIL where the items belong. */ lip = cur ? cur->item : NULL; if (!lip || (__psint_t) lip & 1) lip = __xfs_trans_ail_cursor_last(ailp, lsn); /* * If a cursor is provided, we know we're processing the AIL * in lsn order, and future items to be spliced in will * follow the last one being inserted now. Update the * cursor to point to that last item, now while we have a * reliable pointer to it. */ if (cur) cur->item = list_entry(list->prev, struct xfs_log_item, li_ail); /* * Finally perform the splice. Unless the AIL was empty, * lip points to the item in the AIL _after_ which the new * items should go. If lip is null the AIL was empty, so * the new items go at the head of the AIL. */ if (lip) list_splice(list, &lip->li_ail); else list_splice(list, &ailp->xa_ail); } /* * Delete the given item from the AIL. Return a pointer to the item. */ static void xfs_ail_delete( struct xfs_ail *ailp, xfs_log_item_t *lip) { xfs_ail_check(ailp, lip); list_del(&lip->li_ail); xfs_trans_ail_cursor_clear(ailp, lip); } static long xfsaild_push( struct xfs_ail *ailp) { xfs_mount_t *mp = ailp->xa_mount; struct xfs_ail_cursor cur; xfs_log_item_t *lip; xfs_lsn_t lsn; xfs_lsn_t target; long tout; int stuck = 0; int flushing = 0; int count = 0; /* * If we encountered pinned items or did not finish writing out all * buffers the last time we ran, force the log first and wait for it * before pushing again. */ if (ailp->xa_log_flush && ailp->xa_last_pushed_lsn == 0 && (!list_empty_careful(&ailp->xa_buf_list) || xfs_ail_min_lsn(ailp))) { ailp->xa_log_flush = 0; XFS_STATS_INC(xs_push_ail_flush); xfs_log_force(mp, XFS_LOG_SYNC); } spin_lock(&ailp->xa_lock); /* barrier matches the xa_target update in xfs_ail_push() */ smp_rmb(); target = ailp->xa_target; ailp->xa_target_prev = target; lip = xfs_trans_ail_cursor_first(ailp, &cur, ailp->xa_last_pushed_lsn); if (!lip) { /* * If the AIL is empty or our push has reached the end we are * done now. */ xfs_trans_ail_cursor_done(&cur); spin_unlock(&ailp->xa_lock); goto out_done; } XFS_STATS_INC(xs_push_ail); lsn = lip->li_lsn; while ((XFS_LSN_CMP(lip->li_lsn, target) <= 0)) { int lock_result; /* * Note that iop_push may unlock and reacquire the AIL lock. We * rely on the AIL cursor implementation to be able to deal with * the dropped lock. */ lock_result = lip->li_ops->iop_push(lip, &ailp->xa_buf_list); switch (lock_result) { case XFS_ITEM_SUCCESS: XFS_STATS_INC(xs_push_ail_success); trace_xfs_ail_push(lip); ailp->xa_last_pushed_lsn = lsn; break; case XFS_ITEM_FLUSHING: /* * The item or its backing buffer is already beeing * flushed. The typical reason for that is that an * inode buffer is locked because we already pushed the * updates to it as part of inode clustering. * * We do not want to to stop flushing just because lots * of items are already beeing flushed, but we need to * re-try the flushing relatively soon if most of the * AIL is beeing flushed. */ XFS_STATS_INC(xs_push_ail_flushing); trace_xfs_ail_flushing(lip); flushing++; ailp->xa_last_pushed_lsn = lsn; break; case XFS_ITEM_PINNED: XFS_STATS_INC(xs_push_ail_pinned); trace_xfs_ail_pinned(lip); stuck++; ailp->xa_log_flush++; break; case XFS_ITEM_LOCKED: XFS_STATS_INC(xs_push_ail_locked); trace_xfs_ail_locked(lip); stuck++; break; default: ASSERT(0); break; } count++; /* * Are there too many items we can't do anything with? * * If we we are skipping too many items because we can't flush * them or they are already being flushed, we back off and * given them time to complete whatever operation is being * done. i.e. remove pressure from the AIL while we can't make * progress so traversals don't slow down further inserts and * removals to/from the AIL. * * The value of 100 is an arbitrary magic number based on * observation. */ if (stuck > 100) break; lip = xfs_trans_ail_cursor_next(ailp, &cur); if (lip == NULL) break; lsn = lip->li_lsn; } xfs_trans_ail_cursor_done(&cur); spin_unlock(&ailp->xa_lock); if (xfs_buf_delwri_submit_nowait(&ailp->xa_buf_list)) ailp->xa_log_flush++; if (!count || XFS_LSN_CMP(lsn, target) >= 0) { out_done: /* * We reached the target or the AIL is empty, so wait a bit * longer for I/O to complete and remove pushed items from the * AIL before we start the next scan from the start of the AIL. */ tout = 50; ailp->xa_last_pushed_lsn = 0; } else if (((stuck + flushing) * 100) / count > 90) { /* * Either there is a lot of contention on the AIL or we are * stuck due to operations in progress. "Stuck" in this case * is defined as >90% of the items we tried to push were stuck. * * Backoff a bit more to allow some I/O to complete before * restarting from the start of the AIL. This prevents us from * spinning on the same items, and if they are pinned will all * the restart to issue a log force to unpin the stuck items. */ tout = 20; ailp->xa_last_pushed_lsn = 0; } else { /* * Assume we have more work to do in a short while. */ tout = 10; } return tout; } static int xfsaild( void *data) { struct xfs_ail *ailp = data; long tout = 0; /* milliseconds */ set_freezable(); current->flags |= PF_MEMALLOC; while (!kthread_freezable_should_stop(NULL)) { if (tout && tout <= 20) __set_current_state(TASK_KILLABLE); else __set_current_state(TASK_INTERRUPTIBLE); spin_lock(&ailp->xa_lock); /* * Idle if the AIL is empty and we are not racing with a target * update. We check the AIL after we set the task to a sleep * state to guarantee that we either catch an xa_target update * or that a wake_up resets the state to TASK_RUNNING. * Otherwise, we run the risk of sleeping indefinitely. * * The barrier matches the xa_target update in xfs_ail_push(). */ smp_rmb(); if (!xfs_ail_min(ailp) && ailp->xa_target == ailp->xa_target_prev) { spin_unlock(&ailp->xa_lock); schedule(); try_to_freeze(); tout = 0; continue; } spin_unlock(&ailp->xa_lock); if (tout) schedule_timeout(msecs_to_jiffies(tout)); __set_current_state(TASK_RUNNING); try_to_freeze(); tout = xfsaild_push(ailp); } return 0; } /* * This routine is called to move the tail of the AIL forward. It does this by * trying to flush items in the AIL whose lsns are below the given * threshold_lsn. * * The push is run asynchronously in a workqueue, which means the caller needs * to handle waiting on the async flush for space to become available. * We don't want to interrupt any push that is in progress, hence we only queue * work if we set the pushing bit approriately. * * We do this unlocked - we only need to know whether there is anything in the * AIL at the time we are called. We don't need to access the contents of * any of the objects, so the lock is not needed. */ void xfs_ail_push( struct xfs_ail *ailp, xfs_lsn_t threshold_lsn) { xfs_log_item_t *lip; lip = xfs_ail_min(ailp); if (!lip || XFS_FORCED_SHUTDOWN(ailp->xa_mount) || XFS_LSN_CMP(threshold_lsn, ailp->xa_target) <= 0) return; /* * Ensure that the new target is noticed in push code before it clears * the XFS_AIL_PUSHING_BIT. */ smp_wmb(); xfs_trans_ail_copy_lsn(ailp, &ailp->xa_target, &threshold_lsn); smp_wmb(); wake_up_process(ailp->xa_task); } /* * Push out all items in the AIL immediately */ void xfs_ail_push_all( struct xfs_ail *ailp) { xfs_lsn_t threshold_lsn = xfs_ail_max_lsn(ailp); if (threshold_lsn) xfs_ail_push(ailp, threshold_lsn); } /* * Push out all items in the AIL immediately and wait until the AIL is empty. */ void xfs_ail_push_all_sync( struct xfs_ail *ailp) { struct xfs_log_item *lip; DEFINE_WAIT(wait); spin_lock(&ailp->xa_lock); while ((lip = xfs_ail_max(ailp)) != NULL) { prepare_to_wait(&ailp->xa_empty, &wait, TASK_UNINTERRUPTIBLE); ailp->xa_target = lip->li_lsn; wake_up_process(ailp->xa_task); spin_unlock(&ailp->xa_lock); schedule(); spin_lock(&ailp->xa_lock); } spin_unlock(&ailp->xa_lock); finish_wait(&ailp->xa_empty, &wait); } /* * xfs_trans_ail_update - bulk AIL insertion operation. * * @xfs_trans_ail_update takes an array of log items that all need to be * positioned at the same LSN in the AIL. If an item is not in the AIL, it will * be added. Otherwise, it will be repositioned by removing it and re-adding * it to the AIL. If we move the first item in the AIL, update the log tail to * match the new minimum LSN in the AIL. * * This function takes the AIL lock once to execute the update operations on * all the items in the array, and as such should not be called with the AIL * lock held. As a result, once we have the AIL lock, we need to check each log * item LSN to confirm it needs to be moved forward in the AIL. * * To optimise the insert operation, we delete all the items from the AIL in * the first pass, moving them into a temporary list, then splice the temporary * list into the correct position in the AIL. This avoids needing to do an * insert operation on every item. * * This function must be called with the AIL lock held. The lock is dropped * before returning. */ void xfs_trans_ail_update_bulk( struct xfs_ail *ailp, struct xfs_ail_cursor *cur, struct xfs_log_item **log_items, int nr_items, xfs_lsn_t lsn) __releases(ailp->xa_lock) { xfs_log_item_t *mlip; int mlip_changed = 0; int i; LIST_HEAD(tmp); ASSERT(nr_items > 0); /* Not required, but true. */ mlip = xfs_ail_min(ailp); for (i = 0; i < nr_items; i++) { struct xfs_log_item *lip = log_items[i]; if (lip->li_flags & XFS_LI_IN_AIL) { /* check if we really need to move the item */ if (XFS_LSN_CMP(lsn, lip->li_lsn) <= 0) continue; trace_xfs_ail_move(lip, lip->li_lsn, lsn); xfs_ail_delete(ailp, lip); if (mlip == lip) mlip_changed = 1; } else { lip->li_flags |= XFS_LI_IN_AIL; trace_xfs_ail_insert(lip, 0, lsn); } lip->li_lsn = lsn; list_add(&lip->li_ail, &tmp); } if (!list_empty(&tmp)) xfs_ail_splice(ailp, cur, &tmp, lsn); if (mlip_changed) { if (!XFS_FORCED_SHUTDOWN(ailp->xa_mount)) xlog_assign_tail_lsn_locked(ailp->xa_mount); spin_unlock(&ailp->xa_lock); xfs_log_space_wake(ailp->xa_mount); } else { spin_unlock(&ailp->xa_lock); } } /* * xfs_trans_ail_delete_bulk - remove multiple log items from the AIL * * @xfs_trans_ail_delete_bulk takes an array of log items that all need to * removed from the AIL. The caller is already holding the AIL lock, and done * all the checks necessary to ensure the items passed in via @log_items are * ready for deletion. This includes checking that the items are in the AIL. * * For each log item to be removed, unlink it from the AIL, clear the IN_AIL * flag from the item and reset the item's lsn to 0. If we remove the first * item in the AIL, update the log tail to match the new minimum LSN in the * AIL. * * This function will not drop the AIL lock until all items are removed from * the AIL to minimise the amount of lock traffic on the AIL. This does not * greatly increase the AIL hold time, but does significantly reduce the amount * of traffic on the lock, especially during IO completion. * * This function must be called with the AIL lock held. The lock is dropped * before returning. */ void xfs_trans_ail_delete_bulk( struct xfs_ail *ailp, struct xfs_log_item **log_items, int nr_items, int shutdown_type) __releases(ailp->xa_lock) { xfs_log_item_t *mlip; int mlip_changed = 0; int i; mlip = xfs_ail_min(ailp); for (i = 0; i < nr_items; i++) { struct xfs_log_item *lip = log_items[i]; if (!(lip->li_flags & XFS_LI_IN_AIL)) { struct xfs_mount *mp = ailp->xa_mount; spin_unlock(&ailp->xa_lock); if (!XFS_FORCED_SHUTDOWN(mp)) { xfs_alert_tag(mp, XFS_PTAG_AILDELETE, "%s: attempting to delete a log item that is not in the AIL", __func__); xfs_force_shutdown(mp, shutdown_type); } return; } trace_xfs_ail_delete(lip, mlip->li_lsn, lip->li_lsn); xfs_ail_delete(ailp, lip); lip->li_flags &= ~XFS_LI_IN_AIL; lip->li_lsn = 0; if (mlip == lip) mlip_changed = 1; } if (mlip_changed) { if (!XFS_FORCED_SHUTDOWN(ailp->xa_mount)) xlog_assign_tail_lsn_locked(ailp->xa_mount); if (list_empty(&ailp->xa_ail)) wake_up_all(&ailp->xa_empty); spin_unlock(&ailp->xa_lock); xfs_log_space_wake(ailp->xa_mount); } else { spin_unlock(&ailp->xa_lock); } } int xfs_trans_ail_init( xfs_mount_t *mp) { struct xfs_ail *ailp; ailp = kmem_zalloc(sizeof(struct xfs_ail), KM_MAYFAIL); if (!ailp) return ENOMEM; ailp->xa_mount = mp; INIT_LIST_HEAD(&ailp->xa_ail); INIT_LIST_HEAD(&ailp->xa_cursors); spin_lock_init(&ailp->xa_lock); INIT_LIST_HEAD(&ailp->xa_buf_list); init_waitqueue_head(&ailp->xa_empty); ailp->xa_task = kthread_run(xfsaild, ailp, "xfsaild/%s", ailp->xa_mount->m_fsname); if (IS_ERR(ailp->xa_task)) goto out_free_ailp; mp->m_ail = ailp; return 0; out_free_ailp: kmem_free(ailp); return ENOMEM; } void xfs_trans_ail_destroy( xfs_mount_t *mp) { struct xfs_ail *ailp = mp->m_ail; kthread_stop(ailp->xa_task); kmem_free(ailp); }
Java
{- | Module : $EmptyHeader$ Description : <optional short description entry> Copyright : (c) <Authors or Affiliations> License : GPLv2 or higher, see LICENSE.txt Maintainer : <email> Stability : unstable | experimental | provisional | stable | frozen Portability : portable | non-portable (<reason>) <optional description> -} ------------------------------------------------------------------------------- -- GMP -- Copyright 2007, Lutz Schroeder and Georgel Calin ------------------------------------------------------------------------------- module Main where import Text.ParserCombinators.Parsec import System.Environment import IO import GMP.GMPAS import GMP.GMPSAT import GMP.GMPParser import GMP.ModalLogic import GMP.ModalK() import GMP.ModalKD() import GMP.GradedML() import GMP.CoalitionL() import GMP.MajorityL() import GMP.GenericML() import GMP.Lexer ------------------------------------------------------------------------------- -- Funtion to run parser & print ------------------------------------------------------------------------------- runLex :: (Ord a, Show a, ModalLogic a b) => Parser (Formula a) -> String -> IO () runLex p input = run (do whiteSpace ; x <- p ; eof ; return x ) input run :: (Ord a, Show a, ModalLogic a b) => Parser (Formula a) -> String -> IO () run p input = case (parse p "" input) of Left err -> do putStr "parse error at " print err Right x -> do putStrLn ("Input Formula: "{- ++ show x ++ " ..."-}) let sat = checkSAT x if sat then putStrLn "x ... is Satisfiable" else putStrLn "x ... is not Satisfiable" let nsat = checkSAT $ Neg x if nsat then putStrLn "~x ... is Satisfiable" else putStrLn "~x ... is not Satisfiable" let prov = not $ checkSAT $ Neg x if prov then putStrLn "x ... is Provable" else putStrLn "x ... is not Provable" ------------------------------------------------------------------------------- -- For Testing ------------------------------------------------------------------------------- runTest :: Int -> FilePath -> IO () runTest ml p = do input <- readFile (p) case ml of 1 -> runLex ((par5er parseIndex) :: Parser (Formula ModalK)) input 2 -> runLex ((par5er parseIndex) :: Parser (Formula ModalKD)) input 3 -> runLex ((par5er parseIndex) :: Parser (Formula CL)) input 4 -> runLex ((par5er parseIndex) :: Parser (Formula GML)) input 5 -> runLex ((par5er parseIndex) :: Parser (Formula ML)) input _ -> runLex ((par5er parseIndex) :: Parser (Formula Kars)) input return () help :: IO() help = do putStrLn ( "Usage:\n" ++ " ./main <ML> <path>\n\n" ++ "<ML>: 1 for K ML\n" ++ " 2 for KD ML\n" ++ " 3 for Coalition L\n" ++ " 4 for Graded ML\n" ++ " 5 for Majority L\n" ++ " _ for Generic ML\n" ++ "<path>: path to input file\n" ) ------------------------------------------------------------------------------- main :: IO() main = do args <- getArgs if (args == [])||(head args == "--help")||(length args < 2) then help else let ml = head args p = head (tail args) in runTest (read ml) p
Java
<?php /** * Plugin Installer List Table class. * * @package WordPress * @subpackage List_Table * @since 3.1.0 * @access private */ class WP_Plugin_Install_List_Table extends WP_List_Table { function ajax_user_can() { return current_user_can('install_plugins'); } function prepare_items() { include( ABSPATH . 'wp-admin/includes/plugin-install.php' ); global $tabs, $tab, $paged, $type, $term; wp_reset_vars( array( 'tab' ) ); $paged = $this->get_pagenum(); $per_page = 30; // These are the tabs which are shown on the page $tabs = array(); $tabs['dashboard'] = __( 'Поиск' ); if ( 'search' == $tab ) $tabs['search'] = __( 'Search Results' ); $tabs['upload'] = __( 'Upload' ); $tabs['featured'] = _x( 'Featured','Plugin Installer' ); $tabs['popular'] = _x( 'Popular','Plugin Installer' ); $tabs['new'] = _x( 'Newest','Plugin Installer' ); $nonmenu_tabs = array( 'plugin-information' ); //Valid actions to perform which do not have a Menu item. $tabs = apply_filters( 'install_plugins_tabs', $tabs ); $nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs ); // If a non-valid menu tab has been selected, And its not a non-menu action. if ( empty( $tab ) || ( !isset( $tabs[ $tab ] ) && !in_array( $tab, (array) $nonmenu_tabs ) ) ) $tab = key( $tabs ); $args = array( 'page' => $paged, 'per_page' => $per_page ); switch ( $tab ) { case 'search': $type = isset( $_REQUEST['type'] ) ? stripslashes( $_REQUEST['type'] ) : 'term'; $term = isset( $_REQUEST['s'] ) ? stripslashes( $_REQUEST['s'] ) : ''; switch ( $type ) { case 'tag': $args['tag'] = sanitize_title_with_dashes( $term ); break; case 'term': $args['search'] = $term; break; case 'author': $args['author'] = $term; break; } add_action( 'install_plugins_table_header', 'install_search_form', 10, 0 ); break; case 'featured': case 'popular': case 'new': $args['browse'] = $tab; break; default: $args = false; } if ( !$args ) return; $api = plugins_api( 'query_plugins', $args ); if ( is_wp_error( $api ) ) wp_die( $api->get_error_message() . '</p> <p class="hide-if-no-js"><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try again' ) . '</a>' ); $this->items = $api->plugins; $this->set_pagination_args( array( 'total_items' => $api->info['results'], 'per_page' => $per_page, ) ); } function no_items() { _e( 'No plugins match your request.' ); } function get_views() { global $tabs, $tab; $display_tabs = array(); foreach ( (array) $tabs as $action => $text ) { $class = ( $action == $tab ) ? ' class="current"' : ''; $href = self_admin_url('plugin-install.php?tab=' . $action); $display_tabs['plugin-install-'.$action] = "<a href='$href'$class>$text</a>"; } return $display_tabs; } function display_tablenav( $which ) { if ( 'top' == $which ) { ?> <div class="tablenav top"> <div class="alignleft actions"> <?php do_action( 'install_plugins_table_header' ); ?> </div> <?php $this->pagination( $which ); ?> <img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" /> <br class="clear" /> </div> <?php } else { ?> <div class="tablenav bottom"> <?php $this->pagination( $which ); ?> <img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" /> <br class="clear" /> </div> <?php } } function get_table_classes() { extract( $this->_args ); return array( 'widefat', $plural ); } function get_columns() { return array( 'name' => _x( 'Name', 'plugin name' ), 'version' => __( 'Version' ), 'rating' => __( 'Rating' ), 'description' => __( 'Description' ), ); } function display_rows() { $plugins_allowedtags = array( 'a' => array( 'href' => array(),'title' => array(), 'target' => array() ), 'abbr' => array( 'title' => array() ),'acronym' => array( 'title' => array() ), 'code' => array(), 'pre' => array(), 'em' => array(),'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array() ); list( $columns, $hidden ) = $this->get_column_info(); $style = array(); foreach ( $columns as $column_name => $column_display_name ) { $style[ $column_name ] = in_array( $column_name, $hidden ) ? 'style="display:none;"' : ''; } foreach ( (array) $this->items as $plugin ) { if ( is_object( $plugin ) ) $plugin = (array) $plugin; $title = wp_kses( $plugin['name'], $plugins_allowedtags ); //Limit description to 400char, and remove any HTML. $description = strip_tags( $plugin['description'] ); if ( strlen( $description ) > 400 ) $description = mb_substr( $description, 0, 400 ) . '&#8230;'; //remove any trailing entities $description = preg_replace( '/&[^;\s]{0,6}$/', '', $description ); //strip leading/trailing & multiple consecutive lines $description = trim( $description ); $description = preg_replace( "|(\r?\n)+|", "\n", $description ); //\n => <br> $description = nl2br( $description ); $version = wp_kses( $plugin['version'], $plugins_allowedtags ); $name = strip_tags( $title . ' ' . $version ); $author = $plugin['author']; if ( ! empty( $plugin['author'] ) ) $author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '.</cite>'; $author = wp_kses( $author, $plugins_allowedtags ); $action_links = array(); $action_links[] = '<a href="' . self_admin_url( 'plugin-install.php?tab=plugin-information&amp;plugin=' . $plugin['slug'] . '&amp;TB_iframe=true&amp;width=600&amp;height=550' ) . '" class="thickbox" title="' . esc_attr( sprintf( __( 'More information about %s' ), $name ) ) . '">' . __( 'Details' ) . '</a>'; if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) { $status = install_plugin_install_status( $plugin ); switch ( $status['status'] ) { case 'install': if ( $status['url'] ) $action_links[] = '<a class="install-now" href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Install %s' ), $name ) ) . '">' . __( 'Install Now' ) . '</a>'; break; case 'update_available': if ( $status['url'] ) $action_links[] = '<a href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Update to version %s' ), $status['version'] ) ) . '">' . sprintf( __( 'Update Now' ), $status['version'] ) . '</a>'; break; case 'latest_installed': case 'newer_installed': $action_links[] = '<span title="' . esc_attr__( 'This plugin is already installed and is up to date' ) . ' ">' . _x( 'Installed', 'plugin' ) . '</span>'; break; } } $action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin ); ?> <tr> <td class="name column-name"<?php echo $style['name']; ?>><strong><?php echo $title; ?></strong> <div class="action-links"><?php if ( !empty( $action_links ) ) echo implode( ' | ', $action_links ); ?></div> </td> <td class="vers column-version"<?php echo $style['version']; ?>><?php echo $version; ?></td> <td class="vers column-rating"<?php echo $style['rating']; ?>> <div class="star-holder" title="<?php printf( _n( '(based on %s rating)', '(based on %s ratings)', $plugin['num_ratings'] ), number_format_i18n( $plugin['num_ratings'] ) ) ?>"> <div class="star star-rating" style="width: <?php echo esc_attr( str_replace( ',', '.', $plugin['rating'] ) ); ?>px"></div> </div> </td> <td class="desc column-description"<?php echo $style['description']; ?>><?php echo $description, $author; ?></td> </tr> <?php } } }
Java
package com.ues21.ferreteria.login; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.ues21.ferreteria.productos.Productos; import com.ues21.ferreteria.productos.ProductosDAO; import com.ues21.ferreteria.usuarios.Usuarios; import com.ues21.ferreteria.usuarios.UsuariosDAO; @Controller public class LoginController { @Autowired private LoginDAO loginDAO; @Autowired private UsuariosDAO usuariosDAO; /* @RequestMapping(value = "/login", method = RequestMethod.GET) public String listaHome(Model model) { model.addAttribute("login", null); return "login"; } */ @RequestMapping(value = "/login", method = RequestMethod.GET) public String viewRegistration(Map<String, Object> model) { Login userForm = new Login(); model.put("userForm", userForm); return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String processRegistration(@ModelAttribute("userForm") Login user, Model model, HttpSession session) { // implement your own registration logic here... Login login = loginDAO.verificarUsuario(user); // for testing purpose: System.out.println("username: " + user.getDni()); System.out.println("password: " + user.getContrasena()); if (login==null){ model.addAttribute("loginError", "Error logging in. Please try again"); return "index"; } else { Usuarios usuario = usuariosDAO.getUsuario(user.getDni()); session.setAttribute("loggedInUser", usuario); return "home"; } } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpSession session){ session.removeAttribute("loggedInUser"); return "index"; } }
Java
<?php /** * The Sidebar containing the primary and secondary widget areas. * * @package WordPress * @subpackage Twenty_Ten * @since Twenty Ten 1.0 */ ?> <div id="primary" class="widget-area" role="complementary"> <ul class="xoxo"> <?php /* When we call the dynamic_sidebar() function, it'll spit out * the widgets for that widget area. If it instead returns false, * then the sidebar simply doesn't exist, so we'll hard-code in * some default sidebar stuff just in case. */ if ( ! dynamic_sidebar( 'primary-widget-area-en' ) ) : ?> <?php endif; // end primary widget area ?> </ul> </div><!-- #primary .widget-area -->
Java
<?php load_libraries(array('fields/passwordfield')); PhangoVar::$model['user_group']=new Webmodel('user_group'); PhangoVar::$model['user_group']->set_component('name', 'CharField', array(255)); PhangoVar::$model['user_group']->set_component('permissions', 'SerializeField', array()); PhangoVar::$model['user']=new Webmodel('user'); PhangoVar::$model['user']->set_component('username', 'CharField', array(25)); PhangoVar::$model['user']->set_component('password', 'PasswordField', array(25)); PhangoVar::$model['user']->set_component('email', 'EmailField', array(255)); PhangoVar::$model['user']->set_component('group', 'ForeignKeyField', array('user_group')); PhangoVar::$model['user']->set_component('token_client', 'CharField', array(255), 1); PhangoVar::$model['user']->set_component('token_recovery', 'CharField', array(255), 1); PhangoVar::$model['login_tried']=new Webmodel('login_tried'); PhangoVar::$model['login_tried']->components['ip']=new CharField(255); PhangoVar::$model['login_tried']->components['num_tried']=new IntegerField(11); PhangoVar::$model['login_tried']->components['time']=new IntegerField(11); ?>
Java
<?php /** * @file * Contains \Drupal\migrate_drupal\Tests\MigrateFullDrupalTestBase. */ namespace Drupal\migrate_drupal\Tests; use Drupal\migrate\MigrateExecutable; use Drupal\simpletest\TestBase; /** * Test helper for running a complete Drupal migration. */ abstract class MigrateFullDrupalTestBase extends MigrateDrupalTestBase { /** * The test class which discovered migration tests must extend in order to be * included in this test run. */ const BASE_TEST_CLASS = 'Drupal\migrate_drupal\Tests\MigrateDrupalTestBase'; /** * A list of fully-qualified test classes which should be ignored. * * @var string[] */ protected static $blacklist = []; /** * Get the test classes that needs to be run for this test. * * @return array * The list of fully-classified test class names. */ protected function getTestClassesList() { $classes = []; $discovery = \Drupal::getContainer()->get('test_discovery'); foreach (static::$modules as $module) { foreach ($discovery->getTestClasses($module) as $group) { foreach (array_keys($group) as $class) { if (is_subclass_of($class, static::BASE_TEST_CLASS)) { $classes[] = $class; } } } } // Exclude blacklisted classes. return array_diff($classes, static::$blacklist); } /** * {@inheritdoc} */ protected function tearDown() { // Move the results of every class under ours. This is solely for // reporting, the filename will guide developers. self::getDatabaseConnection() ->update('simpletest') ->fields(array('test_class' => get_class($this))) ->condition('test_id', $this->testId) ->execute(); parent::tearDown(); } /** * Test the complete Drupal migration. */ public function testDrupal() { $classes = $this->getTestClassesList(); foreach ($classes as $class) { if (is_subclass_of($class, '\Drupal\migrate\Tests\MigrateDumpAlterInterface')) { $class::migrateDumpAlter($this); } } // Run every migration in the order specified by the storage controller. foreach (entity_load_multiple('migration', static::$migrations) as $migration) { (new MigrateExecutable($migration, $this))->import(); } foreach ($classes as $class) { $test_object = new $class($this->testId); $test_object->databasePrefix = $this->databasePrefix; $test_object->container = $this->container; // run() does a lot of setup and tear down work which we don't need: // it would setup a new database connection and wouldn't find the // Drupal dump. Also by skipping the setUp() methods there are no id // mappings or entities prepared. The tests run against solely migrated // data. foreach (get_class_methods($test_object) as $method) { if (strtolower(substr($method, 0, 4)) == 'test') { // Insert a fail record. This will be deleted on completion to ensure // that testing completed. $method_info = new \ReflectionMethod($class, $method); $caller = array( 'file' => $method_info->getFileName(), 'line' => $method_info->getStartLine(), 'function' => $class . '->' . $method . '()', ); $completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller); // Run the test method. try { $test_object->$method(); } catch (\Exception $e) { $this->exceptionHandler($e); } // Remove the completion check record. TestBase::deleteAssert($completion_check_id); } } // Add the pass/fail/exception/debug results. foreach ($this->results as $key => &$value) { $value += $test_object->results[$key]; } } } }
Java
<?php /** * @package Joomla.UnitTest * @subpackage Filesystem * * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ JLoader::register('JPath', JPATH_PLATFORM . '/joomla/filesystem/path.php'); /** * Tests for the JPath class. * * @package Joomla.UnitTest * @subpackage Filesystem * @since 12.2 */ class JPathTest extends TestCase { /** * Data provider for testClean() method. * * @return array * * @since 12.2 */ public function getCleanData() { return array( // Input Path, Directory Separator, Expected Output 'Nothing to do.' => array('/var/www/foo/bar/baz', '/', '/var/www/foo/bar/baz'), 'One backslash.' => array('/var/www/foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'Two and one backslashes.' => array('/var/www\\\\foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'Mixed backslashes and double forward slashes.' => array('/var\\/www//foo\\bar/baz', '/', '/var/www/foo/bar/baz'), 'UNC path.' => array('\\\\www\\docroot', '\\', '\\\\www\\docroot'), 'UNC path with forward slash.' => array('\\\\www/docroot', '\\', '\\\\www\\docroot'), 'UNC path with UNIX directory separator.' => array('\\\\www/docroot', '/', '/www/docroot'), ); } /** * Test... * * @todo Implement testCanChmod(). * * @return void */ public function testCanChmod() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testSetPermissions(). * * @return void */ public function testSetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testGetPermissions(). * * @return void */ public function testGetPermissions() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testCheck(). * * @return void */ public function testCheck() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Tests the clean method. * * @param string $input @todo * @param string $ds @todo * @param string $expected @todo * * @return void * * @covers JPath::clean * @dataProvider getCleanData * @since 12.2 */ public function testClean($input, $ds, $expected) { $this->assertEquals( $expected, JPath::clean($input, $ds) ); } /** * Test... * * @todo Implement testIsOwner(). * * @return void */ public function testIsOwner() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Test... * * @todo Implement testFind(). * * @return void */ public function testFind() { // Remove the following lines when you implement this test. $this->markTestIncomplete('This test has not been implemented yet.'); } }
Java
body { background-color: #f9f9f9; font-family: 'Helvetica Neue', Helvetica, 'Segoe UI', Arial, freesans, sans-serif; font-size: 1em; font-style: normal; font-variant: normal; line-height: 1.25em; } h1, h2, h3, h4 { font-weight: bold; margin-bottom: 1em; margin-top: 1em; } h1 { font-size: 2em; line-height: 1.2em; } h2 { font-size: 1.5em; line-height: 1.2; } a { color: #4078c0; text-decoration: none; } a:hover, a:active { text-decoration: underline; } ul { list-style: disc; margin-bottom: 1em; padding-left: 2em; } p { margin-bottom: 1em; } table { display: block; margin-bottom: 1em; overflow: auto; width: 100%; word-break: keep-all; } table th, table td { border: 1px solid #ddd; padding: 0.4em 0.8em; } table tr { border-top: 1px solid #ccc; } table tr:nth-child(2n) { background-color: #f8f8f8; } /* FORMS */ label { margin: 0.9375em 0; display: block; cursor: default; } label span { display: block; margin: 0 0 0.35em; } input[type="text"], input[type="password"], input[type="email"], input[type="number"], input[type="tel"], input[type="url"], select, textarea { background-color: #fafafa; border: 1px solid #ccc; border-radius: 0.188em; box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075); font: inherit; font-size: 0.813em; max-width: 33.846em; min-height: 2.615em; outline: none; padding: 0.538em 0.615em; vertical-align: middle; width: 100%; } input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, input[type="number"]:focus, input[type="tel"]:focus, input[type="url"]:focus, select:focus, textarea:focus { background-color: #fff; } textarea { min-height: 10em; } textarea.short { min-height: 5em; } input[type="submit"], .button { background-color: #eee; border: 1px solid #d5d5d5; border-radius: 0.188em; color: #333; cursor: pointer; display: inline-block; font: inherit; font-size: 0.813em; font-weight: bold; padding: 0.462em 0.923em; vertical-align: middle; white-space: nowrap; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-appearance: none; } input[type="submit"]:hover, input[type="submit"]:active, .button:hover, .button:active { background-color: #ddd; border-color: #ccc; text-decoration: none; } /* ALERT BOXES */ .alert-box { border-radius: 0.188em; margin-bottom: 1em; padding: 1em; } .alert-box span { font-weight: bold; text-transform: uppercase; } .error { background: #ffecec; border: 1px solid #f5aca6; } .success { background: #e9ffd9; border: 1px solid #a6ca8a; } .warning { background: #fff8c4; border: 1px solid #f2c779; } .notice { background: #e3f7fc; border: 1px solid #8ed9f6; }
Java
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ /* Freenet 0.7 node. */ package freenet.node; import static freenet.node.stats.DataStoreKeyType.CHK; import static freenet.node.stats.DataStoreKeyType.PUB_KEY; import static freenet.node.stats.DataStoreKeyType.SSK; import static freenet.node.stats.DataStoreType.CACHE; import static freenet.node.stats.DataStoreType.CLIENT; import static freenet.node.stats.DataStoreType.SLASHDOT; import static freenet.node.stats.DataStoreType.STORE; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Random; import java.util.Set; import freenet.config.*; import freenet.node.useralerts.*; import org.tanukisoftware.wrapper.WrapperManager; import freenet.client.FetchContext; import freenet.clients.fcp.FCPMessage; import freenet.clients.fcp.FeedMessage; import freenet.clients.http.SecurityLevelsToadlet; import freenet.clients.http.SimpleToadletServer; import freenet.crypt.DSAPublicKey; import freenet.crypt.ECDH; import freenet.crypt.MasterSecret; import freenet.crypt.PersistentRandomSource; import freenet.crypt.RandomSource; import freenet.crypt.Yarrow; import freenet.io.comm.DMT; import freenet.io.comm.DisconnectedException; import freenet.io.comm.FreenetInetAddress; import freenet.io.comm.IOStatisticCollector; import freenet.io.comm.Message; import freenet.io.comm.MessageCore; import freenet.io.comm.MessageFilter; import freenet.io.comm.Peer; import freenet.io.comm.PeerParseException; import freenet.io.comm.ReferenceSignatureVerificationException; import freenet.io.comm.TrafficClass; import freenet.io.comm.UdpSocketHandler; import freenet.io.xfer.PartiallyReceivedBlock; import freenet.keys.CHKBlock; import freenet.keys.CHKVerifyException; import freenet.keys.ClientCHK; import freenet.keys.ClientCHKBlock; import freenet.keys.ClientKey; import freenet.keys.ClientKeyBlock; import freenet.keys.ClientSSK; import freenet.keys.ClientSSKBlock; import freenet.keys.Key; import freenet.keys.KeyBlock; import freenet.keys.KeyVerifyException; import freenet.keys.NodeCHK; import freenet.keys.NodeSSK; import freenet.keys.SSKBlock; import freenet.keys.SSKVerifyException; import freenet.l10n.BaseL10n; import freenet.l10n.NodeL10n; import freenet.node.DarknetPeerNode.FRIEND_TRUST; import freenet.node.DarknetPeerNode.FRIEND_VISIBILITY; import freenet.node.NodeDispatcher.NodeDispatcherCallback; import freenet.node.OpennetManager.ConnectionType; import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL; import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL; import freenet.node.probe.Listener; import freenet.node.probe.Type; import freenet.node.stats.DataStoreInstanceType; import freenet.node.stats.DataStoreStats; import freenet.node.stats.NotAvailNodeStoreStats; import freenet.node.stats.StoreCallbackStats; import freenet.node.updater.NodeUpdateManager; import freenet.pluginmanager.ForwardPort; import freenet.pluginmanager.PluginDownLoaderOfficialHTTPS; import freenet.pluginmanager.PluginManager; import freenet.store.BlockMetadata; import freenet.store.CHKStore; import freenet.store.FreenetStore; import freenet.store.KeyCollisionException; import freenet.store.NullFreenetStore; import freenet.store.PubkeyStore; import freenet.store.RAMFreenetStore; import freenet.store.SSKStore; import freenet.store.SlashdotStore; import freenet.store.StorableBlock; import freenet.store.StoreCallback; import freenet.store.caching.CachingFreenetStore; import freenet.store.caching.CachingFreenetStoreTracker; import freenet.store.saltedhash.ResizablePersistentIntBuffer; import freenet.store.saltedhash.SaltedHashFreenetStore; import freenet.support.Executor; import freenet.support.Fields; import freenet.support.HTMLNode; import freenet.support.HexUtil; import freenet.support.JVMVersion; import freenet.support.LogThresholdCallback; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.PooledExecutor; import freenet.support.PrioritizedTicker; import freenet.support.ShortBuffer; import freenet.support.SimpleFieldSet; import freenet.support.Ticker; import freenet.support.TokenBucket; import freenet.support.api.BooleanCallback; import freenet.support.api.IntCallback; import freenet.support.api.LongCallback; import freenet.support.api.ShortCallback; import freenet.support.api.StringCallback; import freenet.support.io.ArrayBucketFactory; import freenet.support.io.Closer; import freenet.support.io.FileUtil; import freenet.support.io.NativeThread; import freenet.support.math.MersenneTwister; import freenet.support.transport.ip.HostnameSyntaxException; /** * @author amphibian */ public class Node implements TimeSkewDetectorCallback { public class MigrateOldStoreData implements Runnable { private final boolean clientCache; public MigrateOldStoreData(boolean clientCache) { this.clientCache = clientCache; if(clientCache) { oldCHKClientCache = chkClientcache; oldPKClientCache = pubKeyClientcache; oldSSKClientCache = sskClientcache; } else { oldCHK = chkDatastore; oldPK = pubKeyDatastore; oldSSK = sskDatastore; oldCHKCache = chkDatastore; oldPKCache = pubKeyDatastore; oldSSKCache = sskDatastore; } } @Override public void run() { System.err.println("Migrating old "+(clientCache ? "client cache" : "datastore")); if(clientCache) { migrateOldStore(oldCHKClientCache, chkClientcache, true); StoreCallback<? extends StorableBlock> old; synchronized(Node.this) { old = oldCHKClientCache; oldCHKClientCache = null; } closeOldStore(old); migrateOldStore(oldPKClientCache, pubKeyClientcache, true); synchronized(Node.this) { old = oldPKClientCache; oldPKClientCache = null; } closeOldStore(old); migrateOldStore(oldSSKClientCache, sskClientcache, true); synchronized(Node.this) { old = oldSSKClientCache; oldSSKClientCache = null; } closeOldStore(old); } else { migrateOldStore(oldCHK, chkDatastore, false); oldCHK = null; migrateOldStore(oldPK, pubKeyDatastore, false); oldPK = null; migrateOldStore(oldSSK, sskDatastore, false); oldSSK = null; migrateOldStore(oldCHKCache, chkDatacache, false); oldCHKCache = null; migrateOldStore(oldPKCache, pubKeyDatacache, false); oldPKCache = null; migrateOldStore(oldSSKCache, sskDatacache, false); oldSSKCache = null; } System.err.println("Finished migrating old "+(clientCache ? "client cache" : "datastore")); } } volatile CHKStore oldCHK; volatile PubkeyStore oldPK; volatile SSKStore oldSSK; volatile CHKStore oldCHKCache; volatile PubkeyStore oldPKCache; volatile SSKStore oldSSKCache; volatile CHKStore oldCHKClientCache; volatile PubkeyStore oldPKClientCache; volatile SSKStore oldSSKClientCache; private <T extends StorableBlock> void migrateOldStore(StoreCallback<T> old, StoreCallback<T> newStore, boolean canReadClientCache) { FreenetStore<T> store = old.getStore(); if(store instanceof RAMFreenetStore) { RAMFreenetStore<T> ramstore = (RAMFreenetStore<T>)store; try { ramstore.migrateTo(newStore, canReadClientCache); } catch (IOException e) { Logger.error(this, "Caught migrating old store: "+e, e); } ramstore.clear(); } else if(store instanceof SaltedHashFreenetStore) { Logger.error(this, "Migrating from from a saltedhashstore not fully supported yet: will not keep old keys"); } } public <T extends StorableBlock> void closeOldStore(StoreCallback<T> old) { FreenetStore<T> store = old.getStore(); if(store instanceof SaltedHashFreenetStore) { SaltedHashFreenetStore<T> saltstore = (SaltedHashFreenetStore<T>) store; saltstore.close(); saltstore.destruct(); } } private static volatile boolean logMINOR; private static volatile boolean logDEBUG; static { Logger.registerLogThresholdCallback(new LogThresholdCallback(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this); } }); } private static MeaningfulNodeNameUserAlert nodeNameUserAlert; private static TimeSkewDetectedUserAlert timeSkewDetectedUserAlert; public class NodeNameCallback extends StringCallback { NodeNameCallback() { } @Override public String get() { String name; synchronized(this) { name = myName; } if(name.startsWith("Node id|")|| name.equals("MyFirstFreenetNode") || name.startsWith("Freenet node with no name #")){ clientCore.alerts.register(nodeNameUserAlert); }else{ clientCore.alerts.unregister(nodeNameUserAlert); } return name; } @Override public void set(String val) throws InvalidConfigValueException { if(get().equals(val)) return; else if(val.length() > 128) throw new InvalidConfigValueException("The given node name is too long ("+val+')'); else if("".equals(val)) val = "~none~"; synchronized(this) { myName = val; } // We'll broadcast the new name to our connected darknet peers via a differential node reference SimpleFieldSet fs = new SimpleFieldSet(true); fs.putSingle("myName", myName); peers.locallyBroadcastDiffNodeRef(fs, true, false); // We call the callback once again to ensure MeaningfulNodeNameUserAlert // has been unregistered ... see #1595 get(); } } private class StoreTypeCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { synchronized(Node.this) { return storeType; } } @Override public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException { boolean found = false; for (String p : getPossibleValues()) { if (p.equals(val)) { found = true; break; } } if (!found) throw new InvalidConfigValueException("Invalid store type"); String type; synchronized(Node.this) { type = storeType; } if(type.equals("ram")) { synchronized(this) { // Serialise this part. makeStore(val); } } else { synchronized(Node.this) { storeType = val; } throw new NodeNeedRestartException("Store type cannot be changed on the fly"); } } @Override public String[] getPossibleValues() { return new String[] { "salt-hash", "ram" }; } } private class ClientCacheTypeCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { synchronized(Node.this) { return clientCacheType; } } @Override public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException { boolean found = false; for (String p : getPossibleValues()) { if (p.equals(val)) { found = true; break; } } if (!found) throw new InvalidConfigValueException("Invalid store type"); synchronized(this) { // Serialise this part. String suffix = getStoreSuffix(); if (val.equals("salt-hash")) { byte[] key; try { synchronized(Node.this) { if(keys == null) throw new MasterKeysWrongPasswordException(); key = keys.clientCacheMasterKey; clientCacheType = val; } } catch (MasterKeysWrongPasswordException e1) { setClientCacheAwaitingPassword(); throw new InvalidConfigValueException("You must enter the password"); } try { initSaltHashClientCacheFS(suffix, true, key); } catch (NodeInitException e) { Logger.error(this, "Unable to create new store", e); System.err.println("Unable to create new store: "+e); e.printStackTrace(); // FIXME l10n both on the NodeInitException and the wrapper message throw new InvalidConfigValueException("Unable to create new store: "+e); } } else if(val.equals("ram")) { initRAMClientCacheFS(); } else /*if(val.equals("none")) */{ initNoClientCacheFS(); } synchronized(Node.this) { clientCacheType = val; } } } @Override public String[] getPossibleValues() { return new String[] { "salt-hash", "ram", "none" }; } } private static class L10nCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { return NodeL10n.getBase().getSelectedLanguage().fullName; } @Override public void set(String val) throws InvalidConfigValueException { if(val == null || get().equalsIgnoreCase(val)) return; try { NodeL10n.getBase().setLanguage(BaseL10n.LANGUAGE.mapToLanguage(val)); } catch (MissingResourceException e) { throw new InvalidConfigValueException(e.getLocalizedMessage()); } PluginManager.setLanguage(NodeL10n.getBase().getSelectedLanguage()); } @Override public String[] getPossibleValues() { return BaseL10n.LANGUAGE.valuesWithFullNames(); } } /** Encryption key for client.dat.crypt or client.dat.bak.crypt */ private DatabaseKey databaseKey; /** Encryption keys, if loaded, null if waiting for a password. We must be able to write them, * and they're all used elsewhere anyway, so there's no point trying not to keep them in memory. */ private MasterKeys keys; /** Stats */ public final NodeStats nodeStats; /** Config object for the whole node. */ public final PersistentConfig config; // Static stuff related to logger /** Directory to log to */ static File logDir; /** Maximum size of gzipped logfiles */ static long maxLogSize; /** Log config handler */ public static LoggingConfigHandler logConfigHandler; public static final int PACKETS_IN_BLOCK = 32; public static final int PACKET_SIZE = 1024; public static final double DECREMENT_AT_MIN_PROB = 0.25; public static final double DECREMENT_AT_MAX_PROB = 0.5; // Send keepalives every 7-14 seconds. Will be acked and if necessary resent. // Old behaviour was keepalives every 14-28. Even that was adequate for a 30 second // timeout. Most nodes don't need to send keepalives because they are constantly busy, // this is only an issue for disabled darknet connections, very quiet private networks // etc. public static final long KEEPALIVE_INTERVAL = SECONDS.toMillis(7); // If no activity for 30 seconds, node is dead // 35 seconds allows plenty of time for resends etc even if above is 14 sec as it is on older nodes. public static final long MAX_PEER_INACTIVITY = SECONDS.toMillis(35); /** Time after which a handshake is assumed to have failed. */ public static final int HANDSHAKE_TIMEOUT = (int) MILLISECONDS.toMillis(4800); // Keep the below within the 30 second assumed timeout. // Inter-handshake time must be at least 2x handshake timeout public static final int MIN_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // 10-20 secs public static final int RANDOMIZED_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // avoid overlap when the two handshakes are at the same time public static final int MIN_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*4; public static final int RANDOMIZED_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*2; // 20-30 secs public static final int MIN_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*4; public static final int RANDOMIZED_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*2; // 20-30 secs public static final int MIN_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*24; // 2-5 minutes public static final int RANDOMIZED_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*36; public static final int MIN_BURSTING_HANDSHAKE_BURST_SIZE = 1; // 1-4 handshake sends per burst public static final int RANDOMIZED_BURSTING_HANDSHAKE_BURST_SIZE = 3; // If we don't receive any packets at all in this period, from any node, tell the user public static final long ALARM_TIME = MINUTES.toMillis(1); static final long MIN_INTERVAL_BETWEEN_INCOMING_SWAP_REQUESTS = MILLISECONDS.toMillis(900); static final long MIN_INTERVAL_BETWEEN_INCOMING_PROBE_REQUESTS = MILLISECONDS.toMillis(1000); public static final int SYMMETRIC_KEY_LENGTH = 32; // 256 bits - note that this isn't used everywhere to determine it /** Datastore directory */ private final ProgramDirectory storeDir; /** Datastore properties */ private String storeType; private boolean storeUseSlotFilters; private boolean storeSaltHashResizeOnStart; /** Minimum total datastore size */ static final long MIN_STORE_SIZE = 32 * 1024 * 1024; /** Default datastore size (must be at least MIN_STORE_SIZE) */ static final long DEFAULT_STORE_SIZE = 32 * 1024 * 1024; /** Minimum client cache size */ static final long MIN_CLIENT_CACHE_SIZE = 0; /** Default client cache size (must be at least MIN_CLIENT_CACHE_SIZE) */ static final long DEFAULT_CLIENT_CACHE_SIZE = 10 * 1024 * 1024; /** Minimum slashdot cache size */ static final long MIN_SLASHDOT_CACHE_SIZE = 0; /** Default slashdot cache size (must be at least MIN_SLASHDOT_CACHE_SIZE) */ static final long DEFAULT_SLASHDOT_CACHE_SIZE = 10 * 1024 * 1024; /** The number of bytes per key total in all the different datastores. All the datastores * are always the same size in number of keys. */ public static final int sizePerKey = CHKBlock.DATA_LENGTH + CHKBlock.TOTAL_HEADERS_LENGTH + DSAPublicKey.PADDED_SIZE + SSKBlock.DATA_LENGTH + SSKBlock.TOTAL_HEADERS_LENGTH; /** The maximum number of keys stored in each of the datastores, cache and store combined. */ private long maxTotalKeys; long maxCacheKeys; long maxStoreKeys; /** The maximum size of the datastore. Kept to avoid rounding turning 5G into 5368698672 */ private long maxTotalDatastoreSize; /** If true, store shrinks occur immediately even if they are over 10% of the store size. If false, * we just set the storeSize and do an offline shrink on the next startup. Online shrinks do not * preserve the most recently used data so are not recommended. */ private boolean storeForceBigShrinks; private final SemiOrderedShutdownHook shutdownHook; /** The CHK datastore. Long term storage; data should only be inserted here if * this node is the closest location on the chain so far, and it is on an * insert (because inserts will always reach the most specialized node; if we * allow requests to store here, then we get pollution by inserts for keys not * close to our specialization). These conclusions derived from Oskar's simulations. */ private CHKStore chkDatastore; /** The SSK datastore. See description for chkDatastore. */ private SSKStore sskDatastore; /** The store of DSAPublicKeys (by hash). See description for chkDatastore. */ private PubkeyStore pubKeyDatastore; /** Client cache store type */ private String clientCacheType; /** Client cache could not be opened so is a RAMFS until the correct password is entered */ private boolean clientCacheAwaitingPassword; private boolean databaseAwaitingPassword; /** Client cache maximum cached keys for each type */ long maxClientCacheKeys; /** Maximum size of the client cache. Kept to avoid rounding problems. */ private long maxTotalClientCacheSize; /** The CHK datacache. Short term cache which stores everything that passes * through this node. */ private CHKStore chkDatacache; /** The SSK datacache. Short term cache which stores everything that passes * through this node. */ private SSKStore sskDatacache; /** The public key datacache (by hash). Short term cache which stores * everything that passes through this node. */ private PubkeyStore pubKeyDatacache; /** The CHK client cache. Caches local requests only. */ private CHKStore chkClientcache; /** The SSK client cache. Caches local requests only. */ private SSKStore sskClientcache; /** The pubkey client cache. Caches local requests only. */ private PubkeyStore pubKeyClientcache; // These only cache keys for 30 minutes. // FIXME make the first two configurable private long maxSlashdotCacheSize; private int maxSlashdotCacheKeys; static final long PURGE_INTERVAL = SECONDS.toMillis(60); private CHKStore chkSlashdotcache; private SlashdotStore<CHKBlock> chkSlashdotcacheStore; private SSKStore sskSlashdotcache; private SlashdotStore<SSKBlock> sskSlashdotcacheStore; private PubkeyStore pubKeySlashdotcache; private SlashdotStore<DSAPublicKey> pubKeySlashdotcacheStore; /** If false, only ULPRs will use the slashdot cache. If true, everything does. */ private boolean useSlashdotCache; /** If true, we write stuff to the datastore even though we shouldn't because the HTL is * too high. However it is flagged as old so it won't be included in the Bloom filter for * sharing purposes. */ private boolean writeLocalToDatastore; final NodeGetPubkey getPubKey; /** FetchContext for ARKs */ public final FetchContext arkFetcherContext; /** IP detector */ public final NodeIPDetector ipDetector; /** For debugging/testing, set this to true to stop the * probabilistic decrement at the edges of the HTLs. */ boolean disableProbabilisticHTLs; public final RequestTracker tracker; /** Semi-unique ID for swap requests. Used to identify us so that the * topology can be reconstructed. */ public long swapIdentifier; private String myName; public final LocationManager lm; /** My peers */ public final PeerManager peers; /** Node-reference directory (node identity, peers, etc) */ final ProgramDirectory nodeDir; /** Config directory (l10n overrides, etc) */ final ProgramDirectory cfgDir; /** User data directory (bookmarks, download lists, etc) */ final ProgramDirectory userDir; /** Run-time state directory (bootID, PRNG seed, etc) */ final ProgramDirectory runDir; /** Plugin directory */ final ProgramDirectory pluginDir; /** File to write crypto master keys into, possibly passworded */ final File masterKeysFile; /** Directory to put extra peer data into */ final File extraPeerDataDir; private volatile boolean hasPanicked; /** Strong RNG */ public final RandomSource random; /** JCA-compliant strong RNG. WARNING: DO NOT CALL THIS ON THE MAIN NETWORK * HANDLING THREADS! In some configurations it can block, potentially * forever, on nextBytes()! */ public final SecureRandom secureRandom; /** Weak but fast RNG */ public final Random fastWeakRandom; /** The object which handles incoming messages and allows us to wait for them */ final MessageCore usm; // Darknet stuff NodeCrypto darknetCrypto; // Back compat private boolean showFriendsVisibilityAlert; // Opennet stuff private final NodeCryptoConfig opennetCryptoConfig; OpennetManager opennet; private volatile boolean isAllowedToConnectToSeednodes; private int maxOpennetPeers; private boolean acceptSeedConnections; private boolean passOpennetRefsThroughDarknet; // General stuff public final Executor executor; public final PacketSender ps; public final PrioritizedTicker ticker; final DNSRequester dnsr; final NodeDispatcher dispatcher; public final UptimeEstimator uptime; public final TokenBucket outputThrottle; public boolean throttleLocalData; private int outputBandwidthLimit; private int inputBandwidthLimit; private long amountOfDataToCheckCompressionRatio; private int minimumCompressionPercentage; private int maxTimeForSingleCompressor; private boolean connectionSpeedDetection; boolean inputLimitDefault; final boolean enableARKs; final boolean enablePerNodeFailureTables; final boolean enableULPRDataPropagation; final boolean enableSwapping; private volatile boolean publishOurPeersLocation; private volatile boolean routeAccordingToOurPeersLocation; boolean enableSwapQueueing; boolean enablePacketCoalescing; public static final short DEFAULT_MAX_HTL = (short)18; private short maxHTL; private boolean skipWrapperWarning; private int maxPacketSize; /** Should inserts ignore low backoff times by default? */ public static final boolean IGNORE_LOW_BACKOFF_DEFAULT = false; /** Definition of "low backoff times" for above. */ public static final long LOW_BACKOFF = SECONDS.toMillis(30); /** Should inserts be fairly blatently prioritised on accept by default? */ public static final boolean PREFER_INSERT_DEFAULT = false; /** Should inserts fork when the HTL reaches cacheability? */ public static final boolean FORK_ON_CACHEABLE_DEFAULT = true; public final IOStatisticCollector collector; /** Type identifier for fproxy node to node messages, as sent on DMT.nodeToNodeMessage's */ public static final int N2N_MESSAGE_TYPE_FPROXY = 1; /** Type identifier for differential node reference messages, as sent on DMT.nodeToNodeMessage's */ public static final int N2N_MESSAGE_TYPE_DIFFNODEREF = 2; /** Identifier within fproxy messages for simple, short text messages to be displayed on the homepage as useralerts */ public static final int N2N_TEXT_MESSAGE_TYPE_USERALERT = 1; /** Identifier within fproxy messages for an offer to transfer a file */ public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER = 2; /** Identifier within fproxy messages for accepting an offer to transfer a file */ public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED = 3; /** Identifier within fproxy messages for rejecting an offer to transfer a file */ public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED = 4; /** Identified within friend feed for the recommendation of a bookmark */ public static final int N2N_TEXT_MESSAGE_TYPE_BOOKMARK = 5; /** Identified within friend feed for the recommendation of a file */ public static final int N2N_TEXT_MESSAGE_TYPE_DOWNLOAD = 6; public static final int EXTRA_PEER_DATA_TYPE_N2NTM = 1; public static final int EXTRA_PEER_DATA_TYPE_PEER_NOTE = 2; public static final int EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM = 3; public static final int EXTRA_PEER_DATA_TYPE_BOOKMARK = 4; public static final int EXTRA_PEER_DATA_TYPE_DOWNLOAD = 5; public static final int PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT = 1; /** The bootID of the last time the node booted up. Or -1 if we don't know due to * permissions problems, or we suspect that the node has been booted and not * written the file e.g. if we can't write it. So if we want to compare data * gathered in the last session and only recorded to disk on a clean shutdown * to data we have now, we just include the lastBootID. */ public final long lastBootID; public final long bootID; public final long startupTime; private SimpleToadletServer toadlets; public final NodeClientCore clientCore; // ULPRs, RecentlyFailed, per node failure tables, are all managed by FailureTable. final FailureTable failureTable; // The version we were before we restarted. public int lastVersion; /** NodeUpdater **/ public final NodeUpdateManager nodeUpdater; public final SecurityLevels securityLevels; // Things that's needed to keep track of public final PluginManager pluginManager; // Helpers public final InetAddress localhostAddress; public final FreenetInetAddress fLocalhostAddress; // The node starter private static NodeStarter nodeStarter; // The watchdog will be silenced until it's true private boolean hasStarted; private boolean isStopping = false; /** * Minimum uptime for us to consider a node an acceptable place to store a key. We store a key * to the datastore only if it's from an insert, and we are a sink, but when calculating whether * we are a sink we ignore nodes which have less uptime (percentage) than this parameter. */ static final int MIN_UPTIME_STORE_KEY = 40; private volatile boolean isPRNGReady = false; private boolean storePreallocate; private boolean enableRoutedPing; private boolean peersOffersDismissed; /** * Minimum bandwidth limit in bytes considered usable: 10 KiB. If there is an attempt to set a limit below this - * excluding the reserved -1 for input bandwidth - the callback will throw. See the callbacks for * outputBandwidthLimit and inputBandwidthLimit. 10 KiB are equivalent to 50 GiB traffic per month. */ private static final int minimumBandwidth = 10 * 1024; /** Quality of Service mark we will use for all outgoing packets (opennet/darknet) */ private TrafficClass trafficClass; public TrafficClass getTrafficClass() { return trafficClass; } /* * Gets minimum bandwidth in bytes considered usable. * * @see #minimumBandwidth */ public static int getMinimumBandwidth() { return minimumBandwidth; } /** * Dispatches a probe request with the specified settings * @see freenet.node.probe.Probe#start(byte, long, Type, Listener) */ public void startProbe(final byte htl, final long uid, final Type type, final Listener listener) { dispatcher.probe.start(htl, uid, type, listener); } /** * Read all storable settings (identity etc) from the node file. * @param filename The name of the file to read from. * @throws IOException throw when I/O error occur */ private void readNodeFile(String filename) throws IOException { // REDFLAG: Any way to share this code with NodePeer? FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); SimpleFieldSet fs = new SimpleFieldSet(br, false, true); br.close(); // Read contents String[] udp = fs.getAll("physical.udp"); if((udp != null) && (udp.length > 0)) { for(String udpAddr : udp) { // Just keep the first one with the correct port number. Peer p; try { p = new Peer(udpAddr, false, true); } catch (HostnameSyntaxException e) { Logger.error(this, "Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr); System.err.println("Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr); continue; } catch (PeerParseException e) { throw (IOException)new IOException().initCause(e); } if(p.getPort() == getDarknetPortNumber()) { // DNSRequester doesn't deal with our own node ipDetector.setOldIPAddress(p.getFreenetAddress()); break; } } } darknetCrypto.readCrypto(fs); swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash); String loc = fs.get("location"); double locD = Location.getLocation(loc); if (locD == -1.0) throw new IOException("Invalid location: " + loc); lm.setLocation(locD); myName = fs.get("myName"); if(myName == null) { myName = newName(); } String verString = fs.get("version"); if(verString == null) { Logger.error(this, "No version!"); System.err.println("No version!"); } else { lastVersion = Version.getArbitraryBuildNumber(verString, -1); } } public void makeStore(String val) throws InvalidConfigValueException { String suffix = getStoreSuffix(); if (val.equals("salt-hash")) { try { initSaltHashFS(suffix, true, null); } catch (NodeInitException e) { Logger.error(this, "Unable to create new store", e); System.err.println("Unable to create new store: "+e); e.printStackTrace(); // FIXME l10n both on the NodeInitException and the wrapper message throw new InvalidConfigValueException("Unable to create new store: "+e); } } else { initRAMFS(); } synchronized(Node.this) { storeType = val; } } private String newName() { return "Freenet node with no name #"+random.nextLong(); } private final Object writeNodeFileSync = new Object(); public void writeNodeFile() { synchronized(writeNodeFileSync) { writeNodeFile(nodeDir.file("node-"+getDarknetPortNumber()), nodeDir.file("node-"+getDarknetPortNumber()+".bak")); } } public void writeOpennetFile() { OpennetManager om = opennet; if(om != null) om.writeFile(); } private void writeNodeFile(File orig, File backup) { SimpleFieldSet fs = darknetCrypto.exportPrivateFieldSet(); if(orig.exists()) backup.delete(); FileOutputStream fos = null; try { fos = new FileOutputStream(backup); fs.writeTo(fos); fos.close(); fos = null; FileUtil.renameTo(backup, orig); } catch (IOException ioe) { Logger.error(this, "IOE :"+ioe.getMessage(), ioe); return; } finally { Closer.close(fos); } } private void initNodeFileSettings() { Logger.normal(this, "Creating new node file from scratch"); // Don't need to set getDarknetPortNumber() // FIXME use a real IP! darknetCrypto.initCrypto(); swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash); myName = newName(); } /** * Read the config file from the arguments. * Then create a node. * Anything that needs static init should ideally be in here. * @param args */ public static void main(String[] args) throws IOException { NodeStarter.main(args); } public boolean isUsingWrapper(){ if(nodeStarter!=null && WrapperManager.isControlledByNativeWrapper()) return true; else return false; } public NodeStarter getNodeStarter(){ return nodeStarter; } /** * Create a Node from a Config object. * @param config The Config object for this node. * @param r The random number generator for this node. Passed in because we may want * to use a non-secure RNG for e.g. one-JVM live-code simulations. Should be a Yarrow in * a production node. Yarrow will be used if that parameter is null * @param weakRandom The fast random number generator the node will use. If null a MT * instance will be used, seeded from the secure PRNG. * @param lc logging config Handler * @param ns NodeStarter * @param executor Executor * @throws NodeInitException If the node initialization fails. */ Node(PersistentConfig config, RandomSource r, RandomSource weakRandom, LoggingConfigHandler lc, NodeStarter ns, Executor executor) throws NodeInitException { this.shutdownHook = SemiOrderedShutdownHook.get(); // Easy stuff String tmp = "Initializing Node using Freenet Build #"+Version.buildNumber()+" r"+Version.cvsRevision()+" and freenet-ext Build #"+NodeStarter.extBuildNumber+" r"+NodeStarter.extRevisionNumber+" with "+System.getProperty("java.vendor")+" JVM version "+System.getProperty("java.version")+" running on "+System.getProperty("os.arch")+' '+System.getProperty("os.name")+' '+System.getProperty("os.version"); fixCertsFiles(); Logger.normal(this, tmp); System.out.println(tmp); collector = new IOStatisticCollector(); this.executor = executor; nodeStarter=ns; if(logConfigHandler != lc) logConfigHandler=lc; getPubKey = new NodeGetPubkey(this); startupTime = System.currentTimeMillis(); SimpleFieldSet oldConfig = config.getSimpleFieldSet(); // Setup node-specific configuration final SubConfig nodeConfig = config.createSubConfig("node"); final SubConfig installConfig = config.createSubConfig("node.install"); int sortOrder = 0; // Directory for node-related files other than store this.userDir = setupProgramDir(installConfig, "userDir", ".", "Node.userDir", "Node.userDirLong", nodeConfig); this.cfgDir = setupProgramDir(installConfig, "cfgDir", getUserDir().toString(), "Node.cfgDir", "Node.cfgDirLong", nodeConfig); this.nodeDir = setupProgramDir(installConfig, "nodeDir", getUserDir().toString(), "Node.nodeDir", "Node.nodeDirLong", nodeConfig); this.runDir = setupProgramDir(installConfig, "runDir", getUserDir().toString(), "Node.runDir", "Node.runDirLong", nodeConfig); this.pluginDir = setupProgramDir(installConfig, "pluginDir", userDir().file("plugins").toString(), "Node.pluginDir", "Node.pluginDirLong", nodeConfig); // l10n stuffs nodeConfig.register("l10n", Locale.getDefault().getLanguage().toLowerCase(), sortOrder++, false, true, "Node.l10nLanguage", "Node.l10nLanguageLong", new L10nCallback()); try { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getString("l10n")), getCfgDir()); } catch (MissingResourceException e) { try { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getOption("l10n").getDefault()), getCfgDir()); } catch (MissingResourceException e1) { new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(BaseL10n.LANGUAGE.getDefault().shortCode), getCfgDir()); } } // FProxy config needs to be here too SubConfig fproxyConfig = config.createSubConfig("fproxy"); try { toadlets = new SimpleToadletServer(fproxyConfig, new ArrayBucketFactory(), executor, this); fproxyConfig.finishedInitialization(); toadlets.start(); } catch (IOException e4) { Logger.error(this, "Could not start web interface: "+e4, e4); System.err.println("Could not start web interface: "+e4); e4.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4); } catch (InvalidConfigValueException e4) { System.err.println("Invalid config value, cannot start web interface: "+e4); e4.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4); } final NativeThread entropyGatheringThread = new NativeThread(new Runnable() { long tLastAdded = -1; private void recurse(File f) { if(isPRNGReady) return; extendTimeouts(); File[] subDirs = f.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.exists() && pathname.canRead() && pathname.isDirectory(); } }); // @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086412 if(subDirs != null) for(File currentDir : subDirs) recurse(currentDir); } @Override public void run() { try { // Delay entropy generation helper hack if enough entropy available Thread.sleep(100); } catch (InterruptedException e) { } if(isPRNGReady) return; System.out.println("Not enough entropy available."); System.out.println("Trying to gather entropy (randomness) by reading the disk..."); if(File.separatorChar == '/') { if(new File("/dev/hwrng").exists()) System.out.println("/dev/hwrng exists - have you installed rng-tools?"); else System.out.println("You should consider installing a better random number generator e.g. haveged."); } extendTimeouts(); for(File root : File.listRoots()) { if(isPRNGReady) return; recurse(root); } } /** This is ridiculous, but for some users it can take more than an hour, and timing out sucks * a few bytes and then times out again. :( */ static final int EXTEND_BY = 60*60*1000; private void extendTimeouts() { long now = System.currentTimeMillis(); if(now - tLastAdded < EXTEND_BY/2) return; long target = tLastAdded + EXTEND_BY; while(target < now) target += EXTEND_BY; long extend = target - now; assert(extend < Integer.MAX_VALUE); assert(extend > 0); WrapperManager.signalStarting((int)extend); tLastAdded = now; } }, "Entropy Gathering Thread", NativeThread.MIN_PRIORITY, true); // Setup RNG if needed : DO NOT USE IT BEFORE THAT POINT! if (r == null) { // Preload required freenet.crypt.Util and freenet.crypt.Rijndael classes (selftest can delay Yarrow startup and trigger false lack-of-enthropy message) freenet.crypt.Util.mdProviders.size(); freenet.crypt.ciphers.Rijndael.getProviderName(); File seed = userDir.file("prng.seed"); FileUtil.setOwnerRW(seed); entropyGatheringThread.start(); // Can block. this.random = new Yarrow(seed); // http://bugs.sun.com/view_bug.do;jsessionid=ff625daf459fdffffffffcd54f1c775299e0?bug_id=4705093 // This might block on /dev/random while doing new SecureRandom(). Once it's created, it won't block. ECDH.blockingInit(); } else { this.random = r; // if it's not null it's because we are running in the simulator } // This can block too. this.secureRandom = NodeStarter.getGlobalSecureRandom(); isPRNGReady = true; toadlets.getStartupToadlet().setIsPRNGReady(); if(weakRandom == null) { byte buffer[] = new byte[16]; random.nextBytes(buffer); this.fastWeakRandom = new MersenneTwister(buffer); }else this.fastWeakRandom = weakRandom; nodeNameUserAlert = new MeaningfulNodeNameUserAlert(this); this.config = config; lm = new LocationManager(random, this); try { localhostAddress = InetAddress.getByName("127.0.0.1"); } catch (UnknownHostException e3) { // Does not do a reverse lookup, so this is impossible throw new Error(e3); } fLocalhostAddress = new FreenetInetAddress(localhostAddress); this.securityLevels = new SecurityLevels(this, config); // Location of master key nodeConfig.register("masterKeyFile", "master.keys", sortOrder++, true, true, "Node.masterKeyFile", "Node.masterKeyFileLong", new StringCallback() { @Override public String get() { if(masterKeysFile == null) return "none"; else return masterKeysFile.getPath(); } @Override public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException { // FIXME l10n // FIXME wipe the old one and move throw new InvalidConfigValueException("Node.masterKeyFile cannot be changed on the fly, you must shutdown, wipe the old file and reconfigure"); } }); String value = nodeConfig.getString("masterKeyFile"); File f; if (value.equalsIgnoreCase("none")) { f = null; } else { f = new File(value); if(f.exists() && !(f.canWrite() && f.canRead())) throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, "Cannot read from and write to master keys file "+f); } masterKeysFile = f; FileUtil.setOwnerRW(masterKeysFile); nodeConfig.register("showFriendsVisibilityAlert", false, sortOrder++, true, false, "Node.showFriendsVisibilityAlert", "Node.showFriendsVisibilityAlert", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return showFriendsVisibilityAlert; } } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { synchronized(this) { if(val == showFriendsVisibilityAlert) return; if(val) return; } unregisterFriendsVisibilityAlert(); } }); showFriendsVisibilityAlert = nodeConfig.getBoolean("showFriendsVisibilityAlert"); byte[] clientCacheKey = null; MasterSecret persistentSecret = null; for(int i=0;i<2; i++) { try { if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) { keys = MasterKeys.createRandom(secureRandom); } else { keys = MasterKeys.read(masterKeysFile, secureRandom, ""); } clientCacheKey = keys.clientCacheMasterKey; persistentSecret = keys.getPersistentMasterSecret(); databaseKey = keys.createDatabaseKey(secureRandom); if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.HIGH) { System.err.println("Physical threat level is set to HIGH but no password, resetting to NORMAL - probably timing glitch"); securityLevels.resetPhysicalThreatLevel(PHYSICAL_THREAT_LEVEL.NORMAL); } break; } catch (MasterKeysWrongPasswordException e) { break; } catch (MasterKeysFileSizeException e) { System.err.println("Impossible: master keys file "+masterKeysFile+" too " + e.sizeToString() + "! Deleting to enable startup, but you will lose your client cache."); masterKeysFile.delete(); } catch (IOException e) { break; } } // Boot ID bootID = random.nextLong(); // Fixed length file containing boot ID. Accessed with random access file. So hopefully it will always be // written. Note that we set lastBootID to -1 if we can't _write_ our ID as well as if we can't read it, // because if we can't write it then we probably couldn't write it on the last bootup either. File bootIDFile = runDir.file("bootID"); int BOOT_FILE_LENGTH = 64 / 4; // A long in padded hex bytes long oldBootID = -1; RandomAccessFile raf = null; try { raf = new RandomAccessFile(bootIDFile, "rw"); if(raf.length() < BOOT_FILE_LENGTH) { oldBootID = -1; } else { byte[] buf = new byte[BOOT_FILE_LENGTH]; raf.readFully(buf); String s = new String(buf, "ISO-8859-1"); try { oldBootID = Fields.bytesToLong(HexUtil.hexToBytes(s)); } catch (NumberFormatException e) { oldBootID = -1; } raf.seek(0); } String s = HexUtil.bytesToHex(Fields.longToBytes(bootID)); byte[] buf = s.getBytes("ISO-8859-1"); if(buf.length != BOOT_FILE_LENGTH) System.err.println("Not 16 bytes for boot ID "+bootID+" - WTF??"); raf.write(buf); } catch (IOException e) { oldBootID = -1; // If we have an error in reading, *or in writing*, we don't reliably know the last boot ID. } finally { Closer.close(raf); } lastBootID = oldBootID; nodeConfig.register("disableProbabilisticHTLs", false, sortOrder++, true, false, "Node.disablePHTLS", "Node.disablePHTLSLong", new BooleanCallback() { @Override public Boolean get() { return disableProbabilisticHTLs; } @Override public void set(Boolean val) throws InvalidConfigValueException { disableProbabilisticHTLs = val; } }); disableProbabilisticHTLs = nodeConfig.getBoolean("disableProbabilisticHTLs"); nodeConfig.register("maxHTL", DEFAULT_MAX_HTL, sortOrder++, true, false, "Node.maxHTL", "Node.maxHTLLong", new ShortCallback() { @Override public Short get() { return maxHTL; } @Override public void set(Short val) throws InvalidConfigValueException { if(val < 0) throw new InvalidConfigValueException("Impossible max HTL"); maxHTL = val; } }, false); maxHTL = nodeConfig.getShort("maxHTL"); class TrafficClassCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { return trafficClass.name(); } @Override public void set(String tcName) throws InvalidConfigValueException, NodeNeedRestartException { try { trafficClass = TrafficClass.fromNameOrValue(tcName); } catch (IllegalArgumentException e) { throw new InvalidConfigValueException(e); } throw new NodeNeedRestartException("TrafficClass cannot change on the fly"); } @Override public String[] getPossibleValues() { ArrayList<String> array = new ArrayList<String>(); for (TrafficClass tc : TrafficClass.values()) array.add(tc.name()); return array.toArray(new String[0]); } } nodeConfig.register("trafficClass", TrafficClass.getDefault().name(), sortOrder++, true, false, "Node.trafficClass", "Node.trafficClassLong", new TrafficClassCallback()); String trafficClassValue = nodeConfig.getString("trafficClass"); try { trafficClass = TrafficClass.fromNameOrValue(trafficClassValue); } catch (IllegalArgumentException e) { Logger.error(this, "Invalid trafficClass:"+trafficClassValue+" resetting the value to default.", e); trafficClass = TrafficClass.getDefault(); } // FIXME maybe these should persist? They need to be private. decrementAtMax = random.nextDouble() <= DECREMENT_AT_MAX_PROB; decrementAtMin = random.nextDouble() <= DECREMENT_AT_MIN_PROB; // Determine where to bind to usm = new MessageCore(executor); // FIXME maybe these configs should actually be under a node.ip subconfig? ipDetector = new NodeIPDetector(this); sortOrder = ipDetector.registerConfigs(nodeConfig, sortOrder); // ARKs enabled? nodeConfig.register("enableARKs", true, sortOrder++, true, false, "Node.enableARKs", "Node.enableARKsLong", new BooleanCallback() { @Override public Boolean get() { return enableARKs; } @Override public void set(Boolean val) throws InvalidConfigValueException { throw new InvalidConfigValueException("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enableARKs = nodeConfig.getBoolean("enableARKs"); nodeConfig.register("enablePerNodeFailureTables", true, sortOrder++, true, false, "Node.enablePerNodeFailureTables", "Node.enablePerNodeFailureTablesLong", new BooleanCallback() { @Override public Boolean get() { return enablePerNodeFailureTables; } @Override public void set(Boolean val) throws InvalidConfigValueException { throw new InvalidConfigValueException("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enablePerNodeFailureTables = nodeConfig.getBoolean("enablePerNodeFailureTables"); nodeConfig.register("enableULPRDataPropagation", true, sortOrder++, true, false, "Node.enableULPRDataPropagation", "Node.enableULPRDataPropagationLong", new BooleanCallback() { @Override public Boolean get() { return enableULPRDataPropagation; } @Override public void set(Boolean val) throws InvalidConfigValueException { throw new InvalidConfigValueException("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enableULPRDataPropagation = nodeConfig.getBoolean("enableULPRDataPropagation"); nodeConfig.register("enableSwapping", true, sortOrder++, true, false, "Node.enableSwapping", "Node.enableSwappingLong", new BooleanCallback() { @Override public Boolean get() { return enableSwapping; } @Override public void set(Boolean val) throws InvalidConfigValueException { throw new InvalidConfigValueException("Cannot change on the fly"); } @Override public boolean isReadOnly() { return true; } }); enableSwapping = nodeConfig.getBoolean("enableSwapping"); /* * Publish our peers' locations is enabled, even in MAXIMUM network security and/or HIGH friends security, * because a node which doesn't publish its peers' locations will get dramatically less traffic. * * Publishing our peers' locations does make us slightly more vulnerable to some attacks, but I don't think * it's a big difference: swapping reveals the same information, it just doesn't update as quickly. This * may help slightly, but probably not dramatically against a clever attacker. * * FIXME review this decision. */ nodeConfig.register("publishOurPeersLocation", true, sortOrder++, true, false, "Node.publishOurPeersLocation", "Node.publishOurPeersLocationLong", new BooleanCallback() { @Override public Boolean get() { return publishOurPeersLocation; } @Override public void set(Boolean val) throws InvalidConfigValueException { publishOurPeersLocation = val; } }); publishOurPeersLocation = nodeConfig.getBoolean("publishOurPeersLocation"); nodeConfig.register("routeAccordingToOurPeersLocation", true, sortOrder++, true, false, "Node.routeAccordingToOurPeersLocation", "Node.routeAccordingToOurPeersLocation", new BooleanCallback() { @Override public Boolean get() { return routeAccordingToOurPeersLocation; } @Override public void set(Boolean val) throws InvalidConfigValueException { routeAccordingToOurPeersLocation = val; } }); routeAccordingToOurPeersLocation = nodeConfig.getBoolean("routeAccordingToOurPeersLocation"); nodeConfig.register("enableSwapQueueing", true, sortOrder++, true, false, "Node.enableSwapQueueing", "Node.enableSwapQueueingLong", new BooleanCallback() { @Override public Boolean get() { return enableSwapQueueing; } @Override public void set(Boolean val) throws InvalidConfigValueException { enableSwapQueueing = val; } }); enableSwapQueueing = nodeConfig.getBoolean("enableSwapQueueing"); nodeConfig.register("enablePacketCoalescing", true, sortOrder++, true, false, "Node.enablePacketCoalescing", "Node.enablePacketCoalescingLong", new BooleanCallback() { @Override public Boolean get() { return enablePacketCoalescing; } @Override public void set(Boolean val) throws InvalidConfigValueException { enablePacketCoalescing = val; } }); enablePacketCoalescing = nodeConfig.getBoolean("enablePacketCoalescing"); // Determine the port number // @see #191 if(oldConfig != null && "-1".equals(oldConfig.get("node.listenPort"))) throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_BIND_USM, "Your freenet.ini file is corrupted! 'listenPort=-1'"); NodeCryptoConfig darknetConfig = new NodeCryptoConfig(nodeConfig, sortOrder++, false, securityLevels); sortOrder += NodeCryptoConfig.OPTION_COUNT; darknetCrypto = new NodeCrypto(this, false, darknetConfig, startupTime, enableARKs); // Must be created after darknetCrypto dnsr = new DNSRequester(this); ps = new PacketSender(this); ticker = new PrioritizedTicker(executor, getDarknetPortNumber()); if(executor instanceof PooledExecutor) ((PooledExecutor)executor).setTicker(ticker); Logger.normal(Node.class, "Creating node..."); shutdownHook.addEarlyJob(new Thread() { @Override public void run() { if (opennet != null) opennet.stop(false); } }); shutdownHook.addEarlyJob(new Thread() { @Override public void run() { darknetCrypto.stop(); } }); // Bandwidth limit nodeConfig.register("outputBandwidthLimit", "15K", sortOrder++, false, true, "Node.outBWLimit", "Node.outBWLimitLong", new IntCallback() { @Override public Integer get() { //return BlockTransmitter.getHardBandwidthLimit(); return outputBandwidthLimit; } @Override public void set(Integer obwLimit) throws InvalidConfigValueException { BandwidthManager.checkOutputBandwidthLimit(obwLimit); try { outputThrottle.changeNanosAndBucketSize(SECONDS.toNanos(1) / obwLimit, obwLimit/2); } catch (IllegalArgumentException e) { throw new InvalidConfigValueException(e); } synchronized(Node.this) { outputBandwidthLimit = obwLimit; } } }); int obwLimit = nodeConfig.getInt("outputBandwidthLimit"); if (obwLimit < minimumBandwidth) { obwLimit = minimumBandwidth; // upgrade slow nodes automatically Logger.normal(Node.class, "Output bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth."); } outputBandwidthLimit = obwLimit; try { BandwidthManager.checkOutputBandwidthLimit(outputBandwidthLimit); } catch (InvalidConfigValueException e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } // Bucket size of 0.5 seconds' worth of bytes. // Add them at a rate determined by the obwLimit. // Maximum forced bytes 80%, in other words, 20% of the bandwidth is reserved for // block transfers, so we will use that 20% for block transfers even if more than 80% of the limit is used for non-limited data (resends etc). int bucketSize = obwLimit/2; // Must have at least space for ONE PACKET. // FIXME: make compatible with alternate transports. bucketSize = Math.max(bucketSize, 2048); try { outputThrottle = new TokenBucket(bucketSize, SECONDS.toNanos(1) / obwLimit, obwLimit/2); } catch (IllegalArgumentException e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } nodeConfig.register("inputBandwidthLimit", "-1", sortOrder++, false, true, "Node.inBWLimit", "Node.inBWLimitLong", new IntCallback() { @Override public Integer get() { if(inputLimitDefault) return -1; return inputBandwidthLimit; } @Override public void set(Integer ibwLimit) throws InvalidConfigValueException { synchronized(Node.this) { BandwidthManager.checkInputBandwidthLimit(ibwLimit); if(ibwLimit == -1) { inputLimitDefault = true; ibwLimit = outputBandwidthLimit * 4; } else { inputLimitDefault = false; } inputBandwidthLimit = ibwLimit; } } }); int ibwLimit = nodeConfig.getInt("inputBandwidthLimit"); if(ibwLimit == -1) { inputLimitDefault = true; ibwLimit = obwLimit * 4; } else if (ibwLimit < minimumBandwidth) { ibwLimit = minimumBandwidth; // upgrade slow nodes automatically Logger.normal(Node.class, "Input bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth."); } inputBandwidthLimit = ibwLimit; try { BandwidthManager.checkInputBandwidthLimit(inputBandwidthLimit); } catch (InvalidConfigValueException e) { throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage()); } nodeConfig.register("amountOfDataToCheckCompressionRatio", "8MiB", sortOrder++, true, true, "Node.amountOfDataToCheckCompressionRatio", "Node.amountOfDataToCheckCompressionRatioLong", new LongCallback() { @Override public Long get() { return amountOfDataToCheckCompressionRatio; } @Override public void set(Long amountOfDataToCheckCompressionRatio) { synchronized(Node.this) { Node.this.amountOfDataToCheckCompressionRatio = amountOfDataToCheckCompressionRatio; } } }, true); amountOfDataToCheckCompressionRatio = nodeConfig.getLong("amountOfDataToCheckCompressionRatio"); nodeConfig.register("minimumCompressionPercentage", "10", sortOrder++, true, true, "Node.minimumCompressionPercentage", "Node.minimumCompressionPercentageLong", new IntCallback() { @Override public Integer get() { return minimumCompressionPercentage; } @Override public void set(Integer minimumCompressionPercentage) { synchronized(Node.this) { if (minimumCompressionPercentage < 0 || minimumCompressionPercentage > 100) { Logger.normal(Node.class, "Wrong minimum compression percentage" + minimumCompressionPercentage); return; } Node.this.minimumCompressionPercentage = minimumCompressionPercentage; } } }, Dimension.NOT); minimumCompressionPercentage = nodeConfig.getInt("minimumCompressionPercentage"); nodeConfig.register("maxTimeForSingleCompressor", "20m", sortOrder++, true, true, "Node.maxTimeForSingleCompressor", "Node.maxTimeForSingleCompressorLong", new IntCallback() { @Override public Integer get() { return maxTimeForSingleCompressor; } @Override public void set(Integer maxTimeForSingleCompressor) { synchronized(Node.this) { Node.this.maxTimeForSingleCompressor = maxTimeForSingleCompressor; } } }, Dimension.DURATION); maxTimeForSingleCompressor = nodeConfig.getInt("maxTimeForSingleCompressor"); nodeConfig.register("connectionSpeedDetection", true, sortOrder++, true, true, "Node.connectionSpeedDetection", "Node.connectionSpeedDetectionLong", new BooleanCallback() { @Override public Boolean get() { return connectionSpeedDetection; } @Override public void set(Boolean connectionSpeedDetection) { synchronized(Node.this) { Node.this.connectionSpeedDetection = connectionSpeedDetection; } } }); connectionSpeedDetection = nodeConfig.getBoolean("connectionSpeedDetection"); nodeConfig.register("throttleLocalTraffic", false, sortOrder++, true, false, "Node.throttleLocalTraffic", "Node.throttleLocalTrafficLong", new BooleanCallback() { @Override public Boolean get() { return throttleLocalData; } @Override public void set(Boolean val) throws InvalidConfigValueException { throttleLocalData = val; } }); throttleLocalData = nodeConfig.getBoolean("throttleLocalTraffic"); String s = "Testnet mode DISABLED. You may have some level of anonymity. :)\n"+ "Note that this version of Freenet is still a very early alpha, and may well have numerous bugs and design flaws.\n"+ "In particular: YOU ARE WIDE OPEN TO YOUR IMMEDIATE PEERS! They can eavesdrop on your requests with relatively little difficulty at present (correlation attacks etc)."; Logger.normal(this, s); System.err.println(s); File nodeFile = nodeDir.file("node-"+getDarknetPortNumber()); File nodeFileBackup = nodeDir.file("node-"+getDarknetPortNumber()+".bak"); // After we have set up testnet and IP address, load the node file try { // FIXME should take file directly? readNodeFile(nodeFile.getPath()); } catch (IOException e) { try { System.err.println("Trying to read node file backup ..."); readNodeFile(nodeFileBackup.getPath()); } catch (IOException e1) { if(nodeFile.exists() || nodeFileBackup.exists()) { System.err.println("No node file or cannot read, (re)initialising crypto etc"); System.err.println(e1.toString()); e1.printStackTrace(); System.err.println("After:"); System.err.println(e.toString()); e.printStackTrace(); } else { System.err.println("Creating new cryptographic keys..."); } initNodeFileSettings(); } } // Then read the peers peers = new PeerManager(this, shutdownHook); tracker = new RequestTracker(peers, ticker); usm.setDispatcher(dispatcher=new NodeDispatcher(this)); uptime = new UptimeEstimator(runDir, ticker, darknetCrypto.identityHash); // ULPRs failureTable = new FailureTable(this); nodeStats = new NodeStats(this, sortOrder, config.createSubConfig("node.load"), obwLimit, ibwLimit, lastVersion); // clientCore needs new load management and other settings from stats. clientCore = new NodeClientCore(this, config, nodeConfig, installConfig, getDarknetPortNumber(), sortOrder, oldConfig, fproxyConfig, toadlets, databaseKey, persistentSecret); toadlets.setCore(clientCore); if (JVMVersion.isEOL()) { clientCore.alerts.register(new JVMVersionAlert()); } if(showFriendsVisibilityAlert) registerFriendsVisibilityAlert(); // Node updater support System.out.println("Initializing Node Updater"); try { nodeUpdater = NodeUpdateManager.maybeCreate(this, config); } catch (InvalidConfigValueException e) { e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not create Updater: "+e); } // Opennet final SubConfig opennetConfig = config.createSubConfig("node.opennet"); opennetConfig.register("connectToSeednodes", true, 0, true, false, "Node.withAnnouncement", "Node.withAnnouncementLong", new BooleanCallback() { @Override public Boolean get() { return isAllowedToConnectToSeednodes; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if (get().equals(val)) return; synchronized(Node.this) { isAllowedToConnectToSeednodes = val; if(opennet != null) throw new NodeNeedRestartException(l10n("connectToSeednodesCannotBeChangedMustDisableOpennetOrReboot")); } } }); isAllowedToConnectToSeednodes = opennetConfig.getBoolean("connectToSeednodes"); // Can be enabled on the fly opennetConfig.register("enabled", false, 0, true, true, "Node.opennetEnabled", "Node.opennetEnabledLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return opennet != null; } } @Override public void set(Boolean val) throws InvalidConfigValueException { OpennetManager o; synchronized(Node.this) { if(val == (opennet != null)) return; if(val) { try { o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes); } catch (NodeInitException e) { opennet = null; throw new InvalidConfigValueException(e.getMessage()); } } else { o = opennet; opennet = null; } } if(val) o.start(); else o.stop(true); ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts()); } }); boolean opennetEnabled = opennetConfig.getBoolean("enabled"); opennetConfig.register("maxOpennetPeers", OpennetManager.MAX_PEERS_FOR_SCALING, 1, true, false, "Node.maxOpennetPeers", "Node.maxOpennetPeersLong", new IntCallback() { @Override public Integer get() { return maxOpennetPeers; } @Override public void set(Integer inputMaxOpennetPeers) throws InvalidConfigValueException { if(inputMaxOpennetPeers < 0) throw new InvalidConfigValueException(l10n("mustBePositive")); if(inputMaxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) throw new InvalidConfigValueException(l10n("maxOpennetPeersMustBeTwentyOrLess", "maxpeers", Integer.toString(OpennetManager.MAX_PEERS_FOR_SCALING))); maxOpennetPeers = inputMaxOpennetPeers; } } , false); maxOpennetPeers = opennetConfig.getInt("maxOpennetPeers"); if(maxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) { Logger.error(this, "maxOpennetPeers may not be over "+OpennetManager.MAX_PEERS_FOR_SCALING); maxOpennetPeers = OpennetManager.MAX_PEERS_FOR_SCALING; } opennetCryptoConfig = new NodeCryptoConfig(opennetConfig, 2 /* 0 = enabled */, true, securityLevels); if(opennetEnabled) { opennet = new OpennetManager(this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes); // Will be started later } else { opennet = null; } securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { @Override public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { if(newLevel == NETWORK_THREAT_LEVEL.HIGH || newLevel == NETWORK_THREAT_LEVEL.MAXIMUM) { OpennetManager om; synchronized(Node.this) { om = opennet; if(om != null) opennet = null; } if(om != null) { om.stop(true); ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts()); } } else if(newLevel == NETWORK_THREAT_LEVEL.NORMAL || newLevel == NETWORK_THREAT_LEVEL.LOW) { OpennetManager o = null; synchronized(Node.this) { if(opennet == null) { try { o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes); } catch (NodeInitException e) { opennet = null; Logger.error(this, "UNABLE TO ENABLE OPENNET: "+e, e); clientCore.alerts.register(new SimpleUserAlert(false, l10n("enableOpennetFailedTitle"), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), UserAlert.ERROR)); } } } if(o != null) { o.start(); ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts()); } } Node.this.config.store(); } }); opennetConfig.register("acceptSeedConnections", false, 2, true, true, "Node.acceptSeedConnectionsShort", "Node.acceptSeedConnections", new BooleanCallback() { @Override public Boolean get() { return acceptSeedConnections; } @Override public void set(Boolean val) throws InvalidConfigValueException { acceptSeedConnections = val; } }); acceptSeedConnections = opennetConfig.getBoolean("acceptSeedConnections"); if(acceptSeedConnections && opennet != null) opennet.crypto.socket.getAddressTracker().setHugeTracker(); opennetConfig.finishedInitialization(); nodeConfig.register("passOpennetPeersThroughDarknet", true, sortOrder++, true, false, "Node.passOpennetPeersThroughDarknet", "Node.passOpennetPeersThroughDarknetLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return passOpennetRefsThroughDarknet; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(Node.this) { passOpennetRefsThroughDarknet = val; } } }); passOpennetRefsThroughDarknet = nodeConfig.getBoolean("passOpennetPeersThroughDarknet"); this.extraPeerDataDir = userDir.file("extra-peer-data-"+getDarknetPortNumber()); if (!((extraPeerDataDir.exists() && extraPeerDataDir.isDirectory()) || (extraPeerDataDir.mkdir()))) { String msg = "Could not find or create extra peer data directory"; throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, msg); } // Name nodeConfig.register("name", myName, sortOrder++, false, true, "Node.nodeName", "Node.nodeNameLong", new NodeNameCallback()); myName = nodeConfig.getString("name"); // Datastore nodeConfig.register("storeForceBigShrinks", false, sortOrder++, true, false, "Node.forceBigShrink", "Node.forceBigShrinkLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return storeForceBigShrinks; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(Node.this) { storeForceBigShrinks = val; } } }); // Datastore nodeConfig.register("storeType", "ram", sortOrder++, true, true, "Node.storeType", "Node.storeTypeLong", new StoreTypeCallback()); storeType = nodeConfig.getString("storeType"); /* * Very small initial store size, since the node will preallocate it when starting up for the first time, * BLOCKING STARTUP, and since everyone goes through the wizard anyway... */ nodeConfig.register("storeSize", DEFAULT_STORE_SIZE, sortOrder++, false, true, "Node.storeSize", "Node.storeSizeLong", new LongCallback() { @Override public Long get() { return maxTotalDatastoreSize; } @Override public void set(Long storeSize) throws InvalidConfigValueException { if(storeSize < MIN_STORE_SIZE) throw new InvalidConfigValueException(l10n("invalidStoreSize")); long newMaxStoreKeys = storeSize / sizePerKey; if(newMaxStoreKeys == maxTotalKeys) return; // Update each datastore synchronized(Node.this) { maxTotalDatastoreSize = storeSize; maxTotalKeys = newMaxStoreKeys; maxStoreKeys = maxTotalKeys / 2; maxCacheKeys = maxTotalKeys - maxStoreKeys; } try { chkDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks); chkDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks); pubKeyDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks); pubKeyDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks); sskDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks); sskDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the datastore", e); System.err.println("Caught "+e+" resizing the datastore"); e.printStackTrace(); } //Perhaps a bit hackish...? Seems like this should be near it's definition in NodeStats. nodeStats.avgStoreCHKLocation.changeMaxReports((int)maxStoreKeys); nodeStats.avgCacheCHKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.avgSlashdotCacheCHKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.avgClientCacheCHKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.avgStoreSSKLocation.changeMaxReports((int)maxStoreKeys); nodeStats.avgCacheSSKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.avgSlashdotCacheSSKLocation.changeMaxReports((int)maxCacheKeys); nodeStats.avgClientCacheSSKLocation.changeMaxReports((int)maxCacheKeys); } }, true); maxTotalDatastoreSize = nodeConfig.getLong("storeSize"); if(maxTotalDatastoreSize < MIN_STORE_SIZE && !storeType.equals("ram")) { // totally arbitrary minimum! throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Store size too small"); } maxTotalKeys = maxTotalDatastoreSize / sizePerKey; nodeConfig.register("storeUseSlotFilters", true, sortOrder++, true, false, "Node.storeUseSlotFilters", "Node.storeUseSlotFiltersLong", new BooleanCallback() { public Boolean get() { synchronized(Node.this) { return storeUseSlotFilters; } } public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { synchronized(Node.this) { storeUseSlotFilters = val; } // FIXME l10n throw new NodeNeedRestartException("Need to restart to change storeUseSlotFilters"); } }); storeUseSlotFilters = nodeConfig.getBoolean("storeUseSlotFilters"); nodeConfig.register("storeSaltHashSlotFilterPersistenceTime", ResizablePersistentIntBuffer.DEFAULT_PERSISTENCE_TIME, sortOrder++, true, false, "Node.storeSaltHashSlotFilterPersistenceTime", "Node.storeSaltHashSlotFilterPersistenceTimeLong", new IntCallback() { @Override public Integer get() { return ResizablePersistentIntBuffer.getPersistenceTime(); } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { if(val >= -1) ResizablePersistentIntBuffer.setPersistenceTime(val); else throw new InvalidConfigValueException(l10n("slotFilterPersistenceTimeError")); } }, false); nodeConfig.register("storeSaltHashResizeOnStart", false, sortOrder++, true, false, "Node.storeSaltHashResizeOnStart", "Node.storeSaltHashResizeOnStartLong", new BooleanCallback() { @Override public Boolean get() { return storeSaltHashResizeOnStart; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { storeSaltHashResizeOnStart = val; } }); storeSaltHashResizeOnStart = nodeConfig.getBoolean("storeSaltHashResizeOnStart"); this.storeDir = setupProgramDir(installConfig, "storeDir", userDir().file("datastore").getPath(), "Node.storeDirectory", "Node.storeDirectoryLong", nodeConfig); installConfig.finishedInitialization(); final String suffix = getStoreSuffix(); maxStoreKeys = maxTotalKeys / 2; maxCacheKeys = maxTotalKeys - maxStoreKeys; /* * On Windows, setting the file length normally involves writing lots of zeros. * So it's an uninterruptible system call that takes a loooong time. On OS/X, * presumably the same is true. If the RNG is fast enough, this means that * setting the length and writing random data take exactly the same amount * of time. On most versions of Unix, holes can be created. However on all * systems, predictable disk usage is a good thing. So lets turn it on by * default for now, on all systems. The datastore can be read but mostly not * written while the random data is being written. */ nodeConfig.register("storePreallocate", true, sortOrder++, true, true, "Node.storePreallocate", "Node.storePreallocateLong", new BooleanCallback() { @Override public Boolean get() { return storePreallocate; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { storePreallocate = val; if (storeType.equals("salt-hash")) { setPreallocate(chkDatastore, val); setPreallocate(chkDatacache, val); setPreallocate(pubKeyDatastore, val); setPreallocate(pubKeyDatacache, val); setPreallocate(sskDatastore, val); setPreallocate(sskDatacache, val); } } private void setPreallocate(StoreCallback<?> datastore, boolean val) { // Avoid race conditions by checking first. FreenetStore<?> store = datastore.getStore(); if(store instanceof SaltedHashFreenetStore) ((SaltedHashFreenetStore<?>)store).setPreallocate(val); }} ); storePreallocate = nodeConfig.getBoolean("storePreallocate"); if(File.separatorChar == '/' && System.getProperty("os.name").toLowerCase().indexOf("mac os") < 0) { securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() { @Override public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) { try { if(newLevel == PHYSICAL_THREAT_LEVEL.LOW) nodeConfig.set("storePreallocate", false); else nodeConfig.set("storePreallocate", true); } catch (NodeNeedRestartException e) { // Ignore } catch (InvalidConfigValueException e) { // Ignore } } }); } securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() { @Override public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) { if(newLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) { synchronized(this) { clientCacheAwaitingPassword = false; databaseAwaitingPassword = false; } try { killMasterKeysFile(); clientCore.clientLayerPersister.disableWrite(); clientCore.clientLayerPersister.waitForNotWriting(); clientCore.clientLayerPersister.deleteAllFiles(); } catch (IOException e) { masterKeysFile.delete(); Logger.error(this, "Unable to securely delete "+masterKeysFile); System.err.println(NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile", "filename", masterKeysFile.getAbsolutePath())); clientCore.alerts.register(new SimpleUserAlert(true, NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), UserAlert.CRITICAL_ERROR)); } } if(oldLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM && newLevel != PHYSICAL_THREAT_LEVEL.HIGH) { // Not passworded. // Create the master.keys. // Keys must exist. try { MasterKeys keys; synchronized(this) { keys = Node.this.keys; } keys.changePassword(masterKeysFile, "", secureRandom); } catch (IOException e) { Logger.error(this, "Unable to create encryption keys file: "+masterKeysFile+" : "+e, e); System.err.println("Unable to create encryption keys file: "+masterKeysFile+" : "+e); e.printStackTrace(); } } } }); if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) { try { killMasterKeysFile(); } catch (IOException e) { String msg = "Unable to securely delete old master.keys file when switching to MAXIMUM seclevel!!"; System.err.println(msg); throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, msg); } } long defaultCacheSize; long memoryLimit = NodeStarter.getMemoryLimitBytes(); // This is tricky because systems with low memory probably also have slow disks, but using // up too much memory can be catastrophic... // Total alchemy, FIXME! if(memoryLimit == Long.MAX_VALUE || memoryLimit < 0) defaultCacheSize = 1024*1024; else if(memoryLimit <= 128*1024*1024) defaultCacheSize = 0; // Turn off completely for very small memory. else { // 9 stores, total should be 5% of memory, up to maximum of 1MB per store at 308MB+ defaultCacheSize = Math.min(1024*1024, (memoryLimit - 128*1024*1024) / (20*9)); } nodeConfig.register("cachingFreenetStoreMaxSize", defaultCacheSize, sortOrder++, true, false, "Node.cachingFreenetStoreMaxSize", "Node.cachingFreenetStoreMaxSizeLong", new LongCallback() { @Override public Long get() { synchronized(Node.this) { return cachingFreenetStoreMaxSize; } } @Override public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < 0) throw new InvalidConfigValueException(l10n("invalidMemoryCacheSize")); // Any positive value is legal. In particular, e.g. 1200 bytes would cause us to cache SSKs but not CHKs. synchronized(Node.this) { cachingFreenetStoreMaxSize = val; } throw new NodeNeedRestartException("Caching Maximum Size cannot be changed on the fly"); } }, true); cachingFreenetStoreMaxSize = nodeConfig.getLong("cachingFreenetStoreMaxSize"); if(cachingFreenetStoreMaxSize < 0) throw new NodeInitException(NodeInitException.EXIT_BAD_CONFIG, l10n("invalidMemoryCacheSize")); nodeConfig.register("cachingFreenetStorePeriod", "300k", sortOrder++, true, false, "Node.cachingFreenetStorePeriod", "Node.cachingFreenetStorePeriod", new LongCallback() { @Override public Long get() { synchronized(Node.this) { return cachingFreenetStorePeriod; } } @Override public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException { synchronized(Node.this) { cachingFreenetStorePeriod = val; } throw new NodeNeedRestartException("Caching Period cannot be changed on the fly"); } }, true); cachingFreenetStorePeriod = nodeConfig.getLong("cachingFreenetStorePeriod"); if(cachingFreenetStoreMaxSize > 0 && cachingFreenetStorePeriod > 0) { cachingFreenetStoreTracker = new CachingFreenetStoreTracker(cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, ticker); } boolean shouldWriteConfig = false; if(storeType.equals("bdb-index")) { System.err.println("Old format Berkeley DB datastore detected."); System.err.println("This datastore format is no longer supported."); System.err.println("The old datastore will be securely deleted."); storeType = "salt-hash"; shouldWriteConfig = true; deleteOldBDBIndexStoreFiles(); } if (storeType.equals("salt-hash")) { initRAMFS(); initSaltHashFS(suffix, false, null); } else { initRAMFS(); } if(databaseAwaitingPassword) createPasswordUserAlert(); // Client cache // Default is 10MB, in memory only. The wizard will change this. nodeConfig.register("clientCacheType", "ram", sortOrder++, true, true, "Node.clientCacheType", "Node.clientCacheTypeLong", new ClientCacheTypeCallback()); clientCacheType = nodeConfig.getString("clientCacheType"); nodeConfig.register("clientCacheSize", DEFAULT_CLIENT_CACHE_SIZE, sortOrder++, false, true, "Node.clientCacheSize", "Node.clientCacheSizeLong", new LongCallback() { @Override public Long get() { return maxTotalClientCacheSize; } @Override public void set(Long storeSize) throws InvalidConfigValueException { if(storeSize < MIN_CLIENT_CACHE_SIZE) throw new InvalidConfigValueException(l10n("invalidStoreSize")); long newMaxStoreKeys = storeSize / sizePerKey; if(newMaxStoreKeys == maxClientCacheKeys) return; // Update each datastore synchronized(Node.this) { maxTotalClientCacheSize = storeSize; maxClientCacheKeys = newMaxStoreKeys; } try { chkClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks); pubKeyClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks); sskClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the clientcache", e); System.err.println("Caught "+e+" resizing the clientcache"); e.printStackTrace(); } } }, true); maxTotalClientCacheSize = nodeConfig.getLong("clientCacheSize"); if(maxTotalClientCacheSize < MIN_CLIENT_CACHE_SIZE) { throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Client cache size too small"); } maxClientCacheKeys = maxTotalClientCacheSize / sizePerKey; boolean startedClientCache = false; if (clientCacheType.equals("salt-hash")) { if(clientCacheKey == null) { System.err.println("Cannot open client-cache, it is passworded"); setClientCacheAwaitingPassword(); } else { initSaltHashClientCacheFS(suffix, false, clientCacheKey); startedClientCache = true; } } else if(clientCacheType.equals("none")) { initNoClientCacheFS(); startedClientCache = true; } else { // ram initRAMClientCacheFS(); startedClientCache = true; } if(!startedClientCache) initRAMClientCacheFS(); if(!clientCore.loadedDatabase() && databaseKey != null) { try { lateSetupDatabase(databaseKey); } catch (MasterKeysWrongPasswordException e2) { System.err.println("Impossible: "+e2); e2.printStackTrace(); } catch (MasterKeysFileSizeException e2) { System.err.println("Impossible: "+e2); e2.printStackTrace(); } catch (IOException e2) { System.err.println("Unable to load database: "+e2); e2.printStackTrace(); } } nodeConfig.register("useSlashdotCache", true, sortOrder++, true, false, "Node.useSlashdotCache", "Node.useSlashdotCacheLong", new BooleanCallback() { @Override public Boolean get() { return useSlashdotCache; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { useSlashdotCache = val; } }); useSlashdotCache = nodeConfig.getBoolean("useSlashdotCache"); nodeConfig.register("writeLocalToDatastore", false, sortOrder++, true, false, "Node.writeLocalToDatastore", "Node.writeLocalToDatastoreLong", new BooleanCallback() { @Override public Boolean get() { return writeLocalToDatastore; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { writeLocalToDatastore = val; } }); writeLocalToDatastore = nodeConfig.getBoolean("writeLocalToDatastore"); // LOW network *and* physical seclevel = writeLocalToDatastore securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { @Override public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { if(newLevel == NETWORK_THREAT_LEVEL.LOW && securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.LOW) writeLocalToDatastore = true; else writeLocalToDatastore = false; } }); securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL>() { @Override public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) { if(newLevel == PHYSICAL_THREAT_LEVEL.LOW && securityLevels.getNetworkThreatLevel() == NETWORK_THREAT_LEVEL.LOW) writeLocalToDatastore = true; else writeLocalToDatastore = false; } }); nodeConfig.register("slashdotCacheLifetime", MINUTES.toMillis(30), sortOrder++, true, false, "Node.slashdotCacheLifetime", "Node.slashdotCacheLifetimeLong", new LongCallback() { @Override public Long get() { return chkSlashdotcacheStore.getLifetime(); } @Override public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < 0) throw new InvalidConfigValueException("Must be positive!"); chkSlashdotcacheStore.setLifetime(val); pubKeySlashdotcacheStore.setLifetime(val); sskSlashdotcacheStore.setLifetime(val); } }, false); long slashdotCacheLifetime = nodeConfig.getLong("slashdotCacheLifetime"); nodeConfig.register("slashdotCacheSize", DEFAULT_SLASHDOT_CACHE_SIZE, sortOrder++, false, true, "Node.slashdotCacheSize", "Node.slashdotCacheSizeLong", new LongCallback() { @Override public Long get() { return maxSlashdotCacheSize; } @Override public void set(Long storeSize) throws InvalidConfigValueException { if(storeSize < MIN_SLASHDOT_CACHE_SIZE) throw new InvalidConfigValueException(l10n("invalidStoreSize")); int newMaxStoreKeys = (int) Math.min(storeSize / sizePerKey, Integer.MAX_VALUE); if(newMaxStoreKeys == maxSlashdotCacheKeys) return; // Update each datastore synchronized(Node.this) { maxSlashdotCacheSize = storeSize; maxSlashdotCacheKeys = newMaxStoreKeys; } try { chkSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks); pubKeySlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks); sskSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks); } catch (IOException e) { // FIXME we need to be able to tell the user. Logger.error(this, "Caught "+e+" resizing the slashdotcache", e); System.err.println("Caught "+e+" resizing the slashdotcache"); e.printStackTrace(); } } }, true); maxSlashdotCacheSize = nodeConfig.getLong("slashdotCacheSize"); if(maxSlashdotCacheSize < MIN_SLASHDOT_CACHE_SIZE) { throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Slashdot cache size too small"); } maxSlashdotCacheKeys = (int) Math.min(maxSlashdotCacheSize / sizePerKey, Integer.MAX_VALUE); chkSlashdotcache = new CHKStore(); chkSlashdotcacheStore = new SlashdotStore<CHKBlock>(chkSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); pubKeySlashdotcache = new PubkeyStore(); pubKeySlashdotcacheStore = new SlashdotStore<DSAPublicKey>(pubKeySlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); getPubKey.setLocalSlashdotcache(pubKeySlashdotcache); sskSlashdotcache = new SSKStore(getPubKey); sskSlashdotcacheStore = new SlashdotStore<SSKBlock>(sskSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory); // MAXIMUM seclevel = no slashdot cache. securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { @Override public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { if(newLevel == NETWORK_THREAT_LEVEL.MAXIMUM) useSlashdotCache = false; else if(oldLevel == NETWORK_THREAT_LEVEL.MAXIMUM) useSlashdotCache = true; } }); nodeConfig.register("skipWrapperWarning", false, sortOrder++, true, false, "Node.skipWrapperWarning", "Node.skipWrapperWarningLong", new BooleanCallback() { @Override public void set(Boolean value) throws InvalidConfigValueException, NodeNeedRestartException { skipWrapperWarning = value; } @Override public Boolean get() { return skipWrapperWarning; } }); skipWrapperWarning = nodeConfig.getBoolean("skipWrapperWarning"); nodeConfig.register("maxPacketSize", 1280, sortOrder++, true, true, "Node.maxPacketSize", "Node.maxPacketSizeLong", new IntCallback() { @Override public Integer get() { synchronized(Node.this) { return maxPacketSize; } } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { synchronized(Node.this) { if(val == maxPacketSize) return; if(val < UdpSocketHandler.MIN_MTU) throw new InvalidConfigValueException("Must be over 576"); if(val > 1492) throw new InvalidConfigValueException("Larger than ethernet frame size unlikely to work!"); maxPacketSize = val; } updateMTU(); } }, true); maxPacketSize = nodeConfig.getInt("maxPacketSize"); nodeConfig.register("enableRoutedPing", false, sortOrder++, true, false, "Node.enableRoutedPing", "Node.enableRoutedPingLong", new BooleanCallback() { @Override public Boolean get() { synchronized(Node.this) { return enableRoutedPing; } } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { synchronized(Node.this) { enableRoutedPing = val; } } }); enableRoutedPing = nodeConfig.getBoolean("enableRoutedPing"); updateMTU(); // peers-offers/*.fref files peersOffersFrefFilesConfiguration(nodeConfig, sortOrder++); if (!peersOffersDismissed && checkPeersOffersFrefFiles()) PeersOffersUserAlert.createAlert(this); /* Take care that no configuration options are registered after this point; they will not persist * between restarts. */ nodeConfig.finishedInitialization(); if(shouldWriteConfig) config.store(); writeNodeFile(); // Initialize the plugin manager Logger.normal(this, "Initializing Plugin Manager"); System.out.println("Initializing Plugin Manager"); pluginManager = new PluginManager(this, lastVersion); shutdownHook.addEarlyJob(new NativeThread("Shutdown plugins", NativeThread.HIGH_PRIORITY, true) { @Override public void realRun() { pluginManager.stop(SECONDS.toMillis(30)); // FIXME make it configurable?? } }); // FIXME // Short timeouts and JVM timeouts with nothing more said than the above have been seen... // I don't know why... need a stack dump... // For now just give it an extra 2 minutes. If it doesn't start in that time, // it's likely (on reports so far) that a restart will fix it. // And we have to get a build out because ALL plugins are now failing to load, // including the absolutely essential (for most nodes) JSTUN and UPnP. WrapperManager.signalStarting((int) MINUTES.toMillis(2)); FetchContext ctx = clientCore.makeClient((short)0, true, false).getFetchContext(); ctx.allowSplitfiles = false; ctx.dontEnterImplicitArchives = true; ctx.maxArchiveRestarts = 0; ctx.maxMetadataSize = 256; ctx.maxNonSplitfileRetries = 10; ctx.maxOutputLength = 4096; ctx.maxRecursionLevel = 2; ctx.maxTempLength = 4096; this.arkFetcherContext = ctx; registerNodeToNodeMessageListener(N2N_MESSAGE_TYPE_FPROXY, fproxyN2NMListener); registerNodeToNodeMessageListener(Node.N2N_MESSAGE_TYPE_DIFFNODEREF, diffNoderefListener); // FIXME this is a hack // toadlet server should start after all initialized // see NodeClientCore line 437 if (toadlets.isEnabled()) { toadlets.finishStart(); toadlets.createFproxy(); toadlets.removeStartupToadlet(); } Logger.normal(this, "Node constructor completed"); System.out.println("Node constructor completed"); new BandwidthManager(this).start(); } private void peersOffersFrefFilesConfiguration(SubConfig nodeConfig, int configOptionSortOrder) { final Node node = this; nodeConfig.register("peersOffersDismissed", false, configOptionSortOrder, true, true, "Node.peersOffersDismissed", "Node.peersOffersDismissedLong", new BooleanCallback() { @Override public Boolean get() { return peersOffersDismissed; } @Override public void set(Boolean val) { if (val) { for (UserAlert alert : clientCore.alerts.getAlerts()) if (alert instanceof PeersOffersUserAlert) clientCore.alerts.unregister(alert); } else PeersOffersUserAlert.createAlert(node); peersOffersDismissed = val; } }); peersOffersDismissed = nodeConfig.getBoolean("peersOffersDismissed"); } private boolean checkPeersOffersFrefFiles() { File[] files = runDir.file("peers-offers").listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (file.isFile()) { String filename = file.getName(); if (filename.endsWith(".fref")) return true; } } } return false; } /** Delete files from old BDB-index datastore. */ private void deleteOldBDBIndexStoreFiles() { File dbDir = storeDir.file("database-"+getDarknetPortNumber()); FileUtil.removeAll(dbDir); File dir = storeDir.dir(); File[] list = dir.listFiles(); for(File f : list) { String name = f.getName(); if(f.isFile() && name.toLowerCase().matches("((chk)|(ssk)|(pubkey))-[0-9]*\\.((store)|(cache))(\\.((keys)|(lru)))?")) { System.out.println("Deleting old datastore file \""+f+"\""); try { FileUtil.secureDelete(f); } catch (IOException e) { System.err.println("Failed to delete old datastore file \""+f+"\": "+e); e.printStackTrace(); } } } } private void fixCertsFiles() { // Hack to update certificates file to fix update.cmd // startssl.pem: Might be useful for old versions of update.sh too? File certs = new File(PluginDownLoaderOfficialHTTPS.certfileOld); fixCertsFile(certs); if(FileUtil.detectedOS.isWindows) { // updater\startssl.pem: Needed for Windows update.cmd. certs = new File("updater", PluginDownLoaderOfficialHTTPS.certfileOld); fixCertsFile(certs); } } private void fixCertsFile(File certs) { long oldLength = certs.exists() ? certs.length() : -1; try { File tmpFile = File.createTempFile(PluginDownLoaderOfficialHTTPS.certfileOld, ".tmp", new File(".")); PluginDownLoaderOfficialHTTPS.writeCertsTo(tmpFile); if(FileUtil.renameTo(tmpFile, certs)) { long newLength = certs.length(); if(newLength != oldLength) System.err.println("Updated "+certs+" so that update scripts will work"); } else { if(certs.length() != tmpFile.length()) { System.err.println("Cannot update "+certs+" : last-resort update scripts (in particular update.cmd on Windows) may not work"); File manual = new File(PluginDownLoaderOfficialHTTPS.certfileOld+".new"); manual.delete(); if(tmpFile.renameTo(manual)) System.err.println("Please delete "+certs+" and rename "+manual+" over it"); else tmpFile.delete(); } } } catch (IOException e) { } } /** ** Sets up a program directory using the config value defined by the given ** parameters. */ public ProgramDirectory setupProgramDir(SubConfig installConfig, String cfgKey, String defaultValue, String shortdesc, String longdesc, String moveErrMsg, SubConfig oldConfig) throws NodeInitException { ProgramDirectory dir = new ProgramDirectory(moveErrMsg); int sortOrder = ProgramDirectory.nextOrder(); // forceWrite=true because currently it can't be changed on the fly, also for packages installConfig.register(cfgKey, defaultValue, sortOrder, true, true, shortdesc, longdesc, dir.getStringCallback()); String dirName = installConfig.getString(cfgKey); try { dir.move(dirName); } catch (IOException e) { throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, "could not set up directory: " + longdesc); } return dir; } protected ProgramDirectory setupProgramDir(SubConfig installConfig, String cfgKey, String defaultValue, String shortdesc, String longdesc, SubConfig oldConfig) throws NodeInitException { return setupProgramDir(installConfig, cfgKey, defaultValue, shortdesc, longdesc, null, oldConfig); } public void lateSetupDatabase(DatabaseKey databaseKey) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException { if(clientCore.loadedDatabase()) return; System.out.println("Starting late database initialisation"); try { if(!clientCore.lateInitDatabase(databaseKey)) failLateInitDatabase(); } catch (NodeInitException e) { failLateInitDatabase(); } } private void failLateInitDatabase() { System.err.println("Failed late initialisation of database, closing..."); } public void killMasterKeysFile() throws IOException { MasterKeys.killMasterKeys(masterKeysFile); } private void setClientCacheAwaitingPassword() { createPasswordUserAlert(); synchronized(this) { clientCacheAwaitingPassword = true; } } /** Called when the client layer needs the decryption password. */ void setDatabaseAwaitingPassword() { synchronized(this) { databaseAwaitingPassword = true; } } private final UserAlert masterPasswordUserAlert = new UserAlert() { final long creationTime = System.currentTimeMillis(); @Override public String anchor() { return "password"; } @Override public String dismissButtonText() { return null; } @Override public long getUpdatedTime() { return creationTime; } @Override public FCPMessage getFCPMessage() { return new FeedMessage(getTitle(), getShortText(), getText(), getPriorityClass(), getUpdatedTime()); } @Override public HTMLNode getHTMLText() { HTMLNode content = new HTMLNode("div"); SecurityLevelsToadlet.generatePasswordFormPage(false, clientCore.getToadletContainer(), content, false, false, false, null, null); return content; } @Override public short getPriorityClass() { return UserAlert.ERROR; } @Override public String getShortText() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public String getText() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public String getTitle() { return NodeL10n.getBase().getString("SecurityLevels.enterPassword"); } @Override public boolean isEventNotification() { return false; } @Override public boolean isValid() { synchronized(Node.this) { return clientCacheAwaitingPassword || databaseAwaitingPassword; } } @Override public void isValid(boolean validity) { // Ignore } @Override public void onDismiss() { // Ignore } @Override public boolean shouldUnregisterOnDismiss() { return false; } @Override public boolean userCanDismiss() { return false; } }; private void createPasswordUserAlert() { this.clientCore.alerts.register(masterPasswordUserAlert); } private void initRAMClientCacheFS() { chkClientcache = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); pubKeyClientcache = new PubkeyStore(); new RAMFreenetStore<DSAPublicKey>(pubKeyClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); sskClientcache = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys)); } private void initNoClientCacheFS() { chkClientcache = new CHKStore(); new NullFreenetStore<CHKBlock>(chkClientcache); pubKeyClientcache = new PubkeyStore(); new NullFreenetStore<DSAPublicKey>(pubKeyClientcache); sskClientcache = new SSKStore(getPubKey); new NullFreenetStore<SSKBlock>(sskClientcache); } private String getStoreSuffix() { return "-" + getDarknetPortNumber(); } private void finishInitSaltHashFS(final String suffix, NodeClientCore clientCore) { if(clientCore.alerts == null) throw new NullPointerException(); chkDatastore.getStore().setUserAlertManager(clientCore.alerts); chkDatacache.getStore().setUserAlertManager(clientCore.alerts); pubKeyDatastore.getStore().setUserAlertManager(clientCore.alerts); pubKeyDatacache.getStore().setUserAlertManager(clientCore.alerts); sskDatastore.getStore().setUserAlertManager(clientCore.alerts); sskDatacache.getStore().setUserAlertManager(clientCore.alerts); } private void initRAMFS() { chkDatastore = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); chkDatacache = new CHKStore(); new RAMFreenetStore<CHKBlock>(chkDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); pubKeyDatastore = new PubkeyStore(); new RAMFreenetStore<DSAPublicKey>(pubKeyDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); pubKeyDatacache = new PubkeyStore(); getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); new RAMFreenetStore<DSAPublicKey>(pubKeyDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); sskDatastore = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys)); sskDatacache = new SSKStore(getPubKey); new RAMFreenetStore<SSKBlock>(sskDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys)); } private long cachingFreenetStoreMaxSize; private long cachingFreenetStorePeriod; private CachingFreenetStoreTracker cachingFreenetStoreTracker; private void initSaltHashFS(final String suffix, boolean dontResizeOnStart, byte[] masterKey) throws NodeInitException { try { final CHKStore chkDatastore = new CHKStore(); final FreenetStore<CHKBlock> chkDataFS = makeStore("CHK", true, chkDatastore, dontResizeOnStart, masterKey); final CHKStore chkDatacache = new CHKStore(); final FreenetStore<CHKBlock> chkCacheFS = makeStore("CHK", false, chkDatacache, dontResizeOnStart, masterKey); ((SaltedHashFreenetStore<CHKBlock>) chkCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<CHKBlock>) chkDataFS.getUnderlyingStore())); final PubkeyStore pubKeyDatastore = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyDataFS = makeStore("PUBKEY", true, pubKeyDatastore, dontResizeOnStart, masterKey); final PubkeyStore pubKeyDatacache = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyCacheFS = makeStore("PUBKEY", false, pubKeyDatacache, dontResizeOnStart, masterKey); ((SaltedHashFreenetStore<DSAPublicKey>) pubkeyCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<DSAPublicKey>) pubkeyDataFS.getUnderlyingStore())); final SSKStore sskDatastore = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskDataFS = makeStore("SSK", true, sskDatastore, dontResizeOnStart, masterKey); final SSKStore sskDatacache = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskCacheFS = makeStore("SSK", false, sskDatacache, dontResizeOnStart, masterKey); ((SaltedHashFreenetStore<SSKBlock>) sskCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<SSKBlock>) sskDataFS.getUnderlyingStore())); boolean delay = chkDataFS.start(ticker, false) | chkCacheFS.start(ticker, false) | pubkeyDataFS.start(ticker, false) | pubkeyCacheFS.start(ticker, false) | sskDataFS.start(ticker, false) | sskCacheFS.start(ticker, false); if(delay) { System.err.println("Delayed init of datastore"); initRAMFS(); final Runnable migrate = new MigrateOldStoreData(false); this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { System.err.println("Starting delayed init of datastore"); try { chkDataFS.start(ticker, true); chkCacheFS.start(ticker, true); pubkeyDataFS.start(ticker, true); pubkeyCacheFS.start(ticker, true); sskDataFS.start(ticker, true); sskCacheFS.start(ticker, true); } catch (IOException e) { Logger.error(this, "Failed to start datastore: "+e, e); System.err.println("Failed to start datastore: "+e); e.printStackTrace(); return; } Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; finishInitSaltHashFS(suffix, clientCore); System.err.println("Finishing delayed init of datastore"); migrate.run(); } }, "Start store", 0, true, false); // Use Ticker to guarantee that this runs *after* constructors have completed. } else { Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { Node.this.chkDatastore = chkDatastore; Node.this.chkDatacache = chkDatacache; Node.this.pubKeyDatastore = pubKeyDatastore; Node.this.pubKeyDatacache = pubKeyDatacache; getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache); Node.this.sskDatastore = sskDatastore; Node.this.sskDatacache = sskDatacache; finishInitSaltHashFS(suffix, clientCore); } }, "Start store", 0, true, false); } } catch (IOException e) { System.err.println("Could not open store: " + e); e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage()); } } private void initSaltHashClientCacheFS(final String suffix, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws NodeInitException { try { final CHKStore chkClientcache = new CHKStore(); final FreenetStore<CHKBlock> chkDataFS = makeClientcache("CHK", true, chkClientcache, dontResizeOnStart, clientCacheMasterKey); final PubkeyStore pubKeyClientcache = new PubkeyStore(); final FreenetStore<DSAPublicKey> pubkeyDataFS = makeClientcache("PUBKEY", true, pubKeyClientcache, dontResizeOnStart, clientCacheMasterKey); final SSKStore sskClientcache = new SSKStore(getPubKey); final FreenetStore<SSKBlock> sskDataFS = makeClientcache("SSK", true, sskClientcache, dontResizeOnStart, clientCacheMasterKey); boolean delay = chkDataFS.start(ticker, false) | pubkeyDataFS.start(ticker, false) | sskDataFS.start(ticker, false); if(delay) { System.err.println("Delayed init of client-cache"); initRAMClientCacheFS(); final Runnable migrate = new MigrateOldStoreData(true); getTicker().queueTimedJob(new Runnable() { @Override public void run() { System.err.println("Starting delayed init of client-cache"); try { chkDataFS.start(ticker, true); pubkeyDataFS.start(ticker, true); sskDataFS.start(ticker, true); } catch (IOException e) { Logger.error(this, "Failed to start client-cache: "+e, e); System.err.println("Failed to start client-cache: "+e); e.printStackTrace(); return; } Node.this.chkClientcache = chkClientcache; Node.this.pubKeyClientcache = pubKeyClientcache; getPubKey.setLocalDataStore(pubKeyClientcache); Node.this.sskClientcache = sskClientcache; System.err.println("Finishing delayed init of client-cache"); migrate.run(); } }, "Migrate store", 0, true, false); } else { Node.this.chkClientcache = chkClientcache; Node.this.pubKeyClientcache = pubKeyClientcache; getPubKey.setLocalDataStore(pubKeyClientcache); Node.this.sskClientcache = sskClientcache; } } catch (IOException e) { System.err.println("Could not open store: " + e); e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage()); } } private <T extends StorableBlock> FreenetStore<T> makeClientcache(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException { FreenetStore<T> store = makeStore(type, "clientcache", maxClientCacheKeys, cb, dontResizeOnStart, clientCacheMasterKey); return store; } private <T extends StorableBlock> FreenetStore<T> makeStore(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException { String store = isStore ? "store" : "cache"; long maxKeys = isStore ? maxStoreKeys : maxCacheKeys; return makeStore(type, store, maxKeys, cb, dontResizeOnStart, clientCacheMasterKey); } private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException { Logger.normal(this, "Initializing "+type+" Data"+store); System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)"); SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb, random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey); cb.setStore(fs); if(cachingFreenetStoreMaxSize > 0) return new CachingFreenetStore<T>(cb, fs, cachingFreenetStoreTracker); else return fs; } public void start(boolean noSwaps) throws NodeInitException { // IMPORTANT: Read the peers only after we have finished initializing Node. // Peer constructors are complex and can call methods on Node. peers.tryReadPeers(nodeDir.file("peers-"+getDarknetPortNumber()).getPath(), darknetCrypto, null, false, false); peers.updatePMUserAlert(); dispatcher.start(nodeStats); // must be before usm dnsr.start(); peers.start(); // must be before usm nodeStats.start(); uptime.start(); failureTable.start(); darknetCrypto.start(); if(opennet != null) opennet.start(); ps.start(nodeStats); ticker.start(); scheduleVersionTransition(); usm.start(ticker); if(isUsingWrapper()) { Logger.normal(this, "Using wrapper correctly: "+nodeStarter); System.out.println("Using wrapper correctly: "+nodeStarter); } else { Logger.error(this, "NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated."); System.out.println("NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated."); } Logger.normal(this, "Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision()); System.out.println("Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision()); Logger.normal(this, "FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber()); System.out.println("FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber()); // Start services // SubConfig pluginManagerConfig = new SubConfig("pluginmanager3", config); // pluginManager3 = new freenet.plugin_new.PluginManager(pluginManagerConfig); ipDetector.start(); // Start sending swaps lm.start(); // Node Updater try{ Logger.normal(this, "Starting the node updater"); nodeUpdater.start(); }catch (Exception e) { e.printStackTrace(); throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not start Updater: "+e); } /* TODO: Make sure that this is called BEFORE any instances of HTTPFilter are created. * HTTPFilter uses checkForGCJCharConversionBug() which returns the value of the static * variable jvmHasGCJCharConversionBug - and this is initialized in the following function. * If this is not possible then create a separate function to check for the GCJ bug and * call this function earlier. */ checkForEvilJVMBugs(); if(!NativeThread.HAS_ENOUGH_NICE_LEVELS) clientCore.alerts.register(new NotEnoughNiceLevelsUserAlert()); this.clientCore.start(config); tracker.startDeadUIDChecker(); // After everything has been created, write the config file back to disk. if(config instanceof FreenetFilePersistentConfig) { FreenetFilePersistentConfig cfg = (FreenetFilePersistentConfig) config; cfg.finishedInit(this.ticker); cfg.setHasNodeStarted(); } config.store(); // Process any data in the extra peer data directory peers.readExtraPeerData(); Logger.normal(this, "Started node"); hasStarted = true; } private void scheduleVersionTransition() { long now = System.currentTimeMillis(); long transition = Version.transitionTime(); if(now < transition) ticker.queueTimedJob(new Runnable() { @Override public void run() { freenet.support.Logger.OSThread.logPID(this); for(PeerNode pn: peers.myPeers()) { pn.updateVersionRoutablity(); } } }, transition - now); } private static boolean jvmHasGCJCharConversionBug=false; private void checkForEvilJVMBugs() { // Now check whether we are likely to get the EvilJVMBug. // If we are running a Sun/Oracle or Blackdown JVM, on Linux, and LD_ASSUME_KERNEL is not set, then we are. String jvmVendor = System.getProperty("java.vm.vendor"); String jvmSpecVendor = System.getProperty("java.specification.vendor",""); String javaVersion = System.getProperty("java.version"); String jvmName = System.getProperty("java.vm.name"); String osName = System.getProperty("os.name"); String osVersion = System.getProperty("os.version"); boolean isOpenJDK = false; //boolean isOracle = false; if(logMINOR) Logger.minor(this, "JVM vendor: "+jvmVendor+", JVM name: "+jvmName+", JVM version: "+javaVersion+", OS name: "+osName+", OS version: "+osVersion); if(jvmName.startsWith("OpenJDK ")) { isOpenJDK = true; } //Add some checks for "Oracle" to futureproof against them renaming from "Sun". //Should have no effect because if a user has downloaded a new enough file for Oracle to have changed the name these bugs shouldn't apply. //Still, one never knows and this code might be extended to cover future bugs. if((!isOpenJDK) && (jvmVendor.startsWith("Sun ") || jvmVendor.startsWith("Oracle ")) || (jvmVendor.startsWith("The FreeBSD Foundation") && (jvmSpecVendor.startsWith("Sun ") || jvmSpecVendor.startsWith("Oracle "))) || (jvmVendor.startsWith("Apple "))) { //isOracle = true; // Sun/Oracle bugs // Spurious OOMs // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4855795 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138757 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138759 // Fixed in 1.5.0_10 and 1.4.2_13 boolean is150 = javaVersion.startsWith("1.5.0_"); boolean is160 = javaVersion.startsWith("1.6.0_"); if(is150 || is160) { String[] split = javaVersion.split("_"); String secondPart = split[1]; if(secondPart.indexOf("-") != -1) { split = secondPart.split("-"); secondPart = split[0]; } int subver = Integer.parseInt(secondPart); Logger.minor(this, "JVM version: "+javaVersion+" subver: "+subver+" from "+secondPart); } } else if (jvmVendor.startsWith("Apple ") || jvmVendor.startsWith("\"Apple ")) { //Note that Sun/Oracle does not produce VMs for the Macintosh operating system, dont ask the user to find one... } else if(!isOpenJDK) { if(jvmVendor.startsWith("Free Software Foundation")) { // GCJ/GIJ. try { javaVersion = System.getProperty("java.version").split(" ")[0].replaceAll("[.]",""); int jvmVersionInt = Integer.parseInt(javaVersion); if(jvmVersionInt <= 422 && jvmVersionInt >= 100) // make sure that no bogus values cause true jvmHasGCJCharConversionBug=true; } catch(Throwable t) { Logger.error(this, "GCJ version check is broken!", t); } clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingGCJTitle"), l10n("usingGCJ"), l10n("usingGCJTitle"), UserAlert.WARNING)); } } if(!isUsingWrapper() && !skipWrapperWarning) { clientCore.alerts.register(new SimpleUserAlert(true, l10n("notUsingWrapperTitle"), l10n("notUsingWrapper"), l10n("notUsingWrapperShort"), UserAlert.WARNING)); } // Unfortunately debian's version of OpenJDK appears to have segfaulting issues. // Which presumably are exploitable. // So we can't recommend people switch just yet. :( // if(isOracle && Rijndael.AesCtrProvider == null) { // if(!(FileUtil.detectedOS == FileUtil.OperatingSystem.Windows || FileUtil.detectedOS == FileUtil.OperatingSystem.MacOS)) // clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingOracleTitle"), l10n("usingOracle"), l10n("usingOracleTitle"), UserAlert.WARNING)); // } } public static boolean checkForGCJCharConversionBug() { return jvmHasGCJCharConversionBug; // should be initialized on early startup } private String l10n(String key) { return NodeL10n.getBase().getString("Node."+key); } private String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("Node."+key, pattern, value); } private String l10n(String key, String[] pattern, String[] value) { return NodeL10n.getBase().getString("Node."+key, pattern, value); } /** * Export volatile data about the node as a SimpleFieldSet */ public SimpleFieldSet exportVolatileFieldSet() { return nodeStats.exportVolatileFieldSet(); } /** * Do a routed ping of another node on the network by its location. * @param loc2 The location of the other node to ping. It must match * exactly. * @param pubKeyHash The hash of the pubkey of the target node. We match * by location; this is just a shortcut if we get close. * @return The number of hops it took to find the node, if it was found. * Otherwise -1. */ public int routedPing(double loc2, byte[] pubKeyHash) { long uid = random.nextLong(); int initialX = random.nextInt(); Message m = DMT.createFNPRoutedPing(uid, loc2, maxHTL, initialX, pubKeyHash); Logger.normal(this, "Message: "+m); dispatcher.handleRouted(m, null); // FIXME: might be rejected MessageFilter mf1 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedPong).setTimeout(5000); try { //MessageFilter mf2 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedRejected).setTimeout(5000); // Ignore Rejected - let it be retried on other peers m = usm.waitFor(mf1/*.or(mf2)*/, null); } catch (DisconnectedException e) { Logger.normal(this, "Disconnected in waiting for pong"); return -1; } if(m == null) return -1; if(m.getSpec() == DMT.FNPRoutedRejected) return -1; return m.getInt(DMT.COUNTER) - initialX; } /** * Look for a block in the datastore, as part of a request. * @param key The key to fetch. * @param uid The UID of the request (for logging only). * @param promoteCache Whether to promote the key if found. * @param canReadClientCache If the request is local, we can read the client cache. * @param canWriteClientCache If the request is local, and the client hasn't turned off * writing to the client cache, we can write to the client cache. * @param canWriteDatastore If the request HTL is too high, including if it is local, we * cannot write to the datastore. * @return A KeyBlock for the key requested or null. */ private KeyBlock makeRequestLocal(Key key, long uid, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean offersOnly) { KeyBlock kb = null; if (key instanceof NodeCHK) { kb = fetch(key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, null); } else if (key instanceof NodeSSK) { NodeSSK sskKey = (NodeSSK) key; DSAPublicKey pubKey = sskKey.getPubKey(); if (pubKey == null) { pubKey = getPubKey.getKey(sskKey.getPubKeyHash(), canReadClientCache, offersOnly, null); if (logMINOR) Logger.minor(this, "Fetched pubkey: " + pubKey); try { sskKey.setPubKey(pubKey); } catch (SSKVerifyException e) { Logger.error(this, "Error setting pubkey: " + e, e); } } if (pubKey != null) { if (logMINOR) Logger.minor(this, "Got pubkey: " + pubKey); kb = fetch(sskKey, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); } else { if (logMINOR) Logger.minor(this, "Not found because no pubkey: " + uid); } } else throw new IllegalStateException("Unknown key type: " + key.getClass()); if (kb != null) { // Probably somebody waiting for it. Trip it. if (clientCore != null && clientCore.requestStarters != null) { if (kb instanceof CHKBlock) { clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(kb); clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(kb); } else { clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(kb); clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(kb); } } failureTable.onFound(kb); return kb; } return null; } /** * Check the datastore, then if the key is not in the store, * check whether another node is requesting the same key at * the same HTL, and if all else fails, create a new * RequestSender for the key/htl. * @param closestLocation The closest location to the key so far. * @param localOnly If true, only check the datastore. * @return A KeyBlock if the data is in the store, otherwise * a RequestSender, unless the HTL is 0, in which case NULL. * RequestSender. */ public Object makeRequestSender(Key key, short htl, long uid, RequestTag tag, PeerNode source, boolean localOnly, boolean ignoreStore, boolean offersOnly, boolean canReadClientCache, boolean canWriteClientCache, boolean realTimeFlag) { boolean canWriteDatastore = canWriteDatastoreRequest(htl); if(logMINOR) Logger.minor(this, "makeRequestSender("+key+ ',' +htl+ ',' +uid+ ',' +source+") on "+getDarknetPortNumber()); // In store? if(!ignoreStore) { KeyBlock kb = makeRequestLocal(key, uid, canReadClientCache, canWriteClientCache, canWriteDatastore, offersOnly); if (kb != null) return kb; } if(localOnly) return null; if(logMINOR) Logger.minor(this, "Not in store locally"); // Transfer coalescing - match key only as HTL irrelevant RequestSender sender = key instanceof NodeCHK ? tracker.getTransferringRequestSenderByKey((NodeCHK)key, realTimeFlag) : null; if(sender != null) { if(logMINOR) Logger.minor(this, "Data already being transferred: "+sender); sender.setTransferCoalesced(); tag.setSender(sender, true); return sender; } // HTL == 0 => Don't search further if(htl == 0) { if(logMINOR) Logger.minor(this, "No HTL"); return null; } sender = new RequestSender(key, null, htl, uid, tag, this, source, offersOnly, canWriteClientCache, canWriteDatastore, realTimeFlag); tag.setSender(sender, false); sender.start(); if(logMINOR) Logger.minor(this, "Created new sender: "+sender); return sender; } /** Can we write to the datastore for a given request? * We do not write to the datastore until 2 hops below maximum. This is an average of 4 * hops from the originator. Thus, data returned from local requests is never cached, * finally solving The Register's attack, Bloom filter sharing doesn't give away your local * requests and inserts, and *anything starting at high HTL* is not cached, including stuff * from other nodes which hasn't been decremented far enough yet, so it's not ONLY local * requests that don't get cached. */ boolean canWriteDatastoreRequest(short htl) { return htl <= (maxHTL - 2); } /** Can we write to the datastore for a given insert? * We do not write to the datastore until 3 hops below maximum. This is an average of 5 * hops from the originator. Thus, data sent by local inserts is never cached, * finally solving The Register's attack, Bloom filter sharing doesn't give away your local * requests and inserts, and *anything starting at high HTL* is not cached, including stuff * from other nodes which hasn't been decremented far enough yet, so it's not ONLY local * inserts that don't get cached. */ boolean canWriteDatastoreInsert(short htl) { return htl <= (maxHTL - 3); } /** * Fetch a block from the datastore. * @param key * @param canReadClientCache * @param canWriteClientCache * @param canWriteDatastore * @param forULPR * @param mustBeMarkedAsPostCachingChanges If true, the key must have the * ENTRY_NEW_BLOCK flag (if saltedhash), indicating that it a) has been added * since the caching changes in 1224 (since we didn't delete the stores), and b) * that it wasn't added due to low network security caching everything, unless we * are currently in low network security mode. Only applies to main store. */ public KeyBlock fetch(Key key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { if(key instanceof NodeSSK) return fetch((NodeSSK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta); else if(key instanceof NodeCHK) return fetch((NodeCHK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta); else throw new IllegalArgumentException(); } public SSKBlock fetch(NodeSSK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { double loc=key.toNormalizedDouble(); double dist=Location.distance(lm.getLocation(), loc); if(canReadClientCache) { try { SSKBlock block = sskClientcache.fetch(key, dontPromote || !canWriteClientCache, canReadClientCache, forULPR, false, meta); if(block != null) { nodeStats.avgClientCacheSSKSuccess.report(loc); if (dist > nodeStats.furthestClientCacheSSKSuccess) nodeStats.furthestClientCacheSSKSuccess=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in client-cache"); return block; } } catch (IOException e) { Logger.error(this, "Could not read from client cache: "+e, e); } } if(forULPR || useSlashdotCache || canReadClientCache) { try { SSKBlock block = sskSlashdotcache.fetch(key, dontPromote, canReadClientCache, forULPR, false, meta); if(block != null) { nodeStats.avgSlashdotCacheSSKSuccess.report(loc); if (dist > nodeStats.furthestSlashdotCacheSSKSuccess) nodeStats.furthestSlashdotCacheSSKSuccess=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in slashdot-cache"); return block; } } catch (IOException e) { Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e); } } boolean ignoreOldBlocks = !writeLocalToDatastore; if(canReadClientCache) ignoreOldBlocks = false; if(logMINOR) dumpStoreHits(); try { nodeStats.avgRequestLocation.report(loc); SSKBlock block = sskDatastore.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); if(block == null) { SSKStore store = oldSSK; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); } if(block != null) { nodeStats.avgStoreSSKSuccess.report(loc); if (dist > nodeStats.furthestStoreSSKSuccess) nodeStats.furthestStoreSSKSuccess=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in store"); return block; } block=sskDatacache.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); if(block == null) { SSKStore store = oldSSKCache; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgCacheSSKSuccess.report(loc); if (dist > nodeStats.furthestCacheSSKSuccess) nodeStats.furthestCacheSSKSuccess=dist; if(logDEBUG) Logger.debug(this, "Found key "+key+" in cache"); } return block; } catch (IOException e) { Logger.error(this, "Cannot fetch data: "+e, e); return null; } } public CHKBlock fetch(NodeCHK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) { double loc=key.toNormalizedDouble(); double dist=Location.distance(lm.getLocation(), loc); if(canReadClientCache) { try { CHKBlock block = chkClientcache.fetch(key, dontPromote || !canWriteClientCache, false, meta); if(block != null) { nodeStats.avgClientCacheCHKSuccess.report(loc); if (dist > nodeStats.furthestClientCacheCHKSuccess) nodeStats.furthestClientCacheCHKSuccess=dist; return block; } } catch (IOException e) { Logger.error(this, "Could not read from client cache: "+e, e); } } if(forULPR || useSlashdotCache || canReadClientCache) { try { CHKBlock block = chkSlashdotcache.fetch(key, dontPromote, false, meta); if(block != null) { nodeStats.avgSlashdotCacheCHKSucess.report(loc); if (dist > nodeStats.furthestSlashdotCacheCHKSuccess) nodeStats.furthestSlashdotCacheCHKSuccess=dist; return block; } } catch (IOException e) { Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e); } } boolean ignoreOldBlocks = !writeLocalToDatastore; if(canReadClientCache) ignoreOldBlocks = false; if(logMINOR) dumpStoreHits(); try { nodeStats.avgRequestLocation.report(loc); CHKBlock block = chkDatastore.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); if(block == null) { CHKStore store = oldCHK; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgStoreCHKSuccess.report(loc); if (dist > nodeStats.furthestStoreCHKSuccess) nodeStats.furthestStoreCHKSuccess=dist; return block; } block=chkDatacache.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); if(block == null) { CHKStore store = oldCHKCache; if(store != null) block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta); } if (block != null) { nodeStats.avgCacheCHKSuccess.report(loc); if (dist > nodeStats.furthestCacheCHKSuccess) nodeStats.furthestCacheCHKSuccess=dist; } return block; } catch (IOException e) { Logger.error(this, "Cannot fetch data: "+e, e); return null; } } CHKStore getChkDatacache() { return chkDatacache; } CHKStore getChkDatastore() { return chkDatastore; } SSKStore getSskDatacache() { return sskDatacache; } SSKStore getSskDatastore() { return sskDatastore; } CHKStore getChkSlashdotCache() { return chkSlashdotcache; } CHKStore getChkClientCache() { return chkClientcache; } SSKStore getSskSlashdotCache() { return sskSlashdotcache; } SSKStore getSskClientCache() { return sskClientcache; } /** * This method returns all statistics info for our data store stats table * * @return map that has an entry for each data store instance type and corresponding stats */ public Map<DataStoreInstanceType, DataStoreStats> getDataStoreStats() { Map<DataStoreInstanceType, DataStoreStats> map = new LinkedHashMap<DataStoreInstanceType, DataStoreStats>(); map.put(new DataStoreInstanceType(CHK, STORE), new StoreCallbackStats(chkDatastore, nodeStats.chkStoreStats())); map.put(new DataStoreInstanceType(CHK, CACHE), new StoreCallbackStats(chkDatacache, nodeStats.chkCacheStats())); map.put(new DataStoreInstanceType(CHK, SLASHDOT), new StoreCallbackStats(chkSlashdotcache,nodeStats.chkSlashDotCacheStats())); map.put(new DataStoreInstanceType(CHK, CLIENT), new StoreCallbackStats(chkClientcache, nodeStats.chkClientCacheStats())); map.put(new DataStoreInstanceType(SSK, STORE), new StoreCallbackStats(sskDatastore, nodeStats.sskStoreStats())); map.put(new DataStoreInstanceType(SSK, CACHE), new StoreCallbackStats(sskDatacache, nodeStats.sskCacheStats())); map.put(new DataStoreInstanceType(SSK, SLASHDOT), new StoreCallbackStats(sskSlashdotcache, nodeStats.sskSlashDotCacheStats())); map.put(new DataStoreInstanceType(SSK, CLIENT), new StoreCallbackStats(sskClientcache, nodeStats.sskClientCacheStats())); map.put(new DataStoreInstanceType(PUB_KEY, STORE), new StoreCallbackStats(pubKeyDatastore, new NotAvailNodeStoreStats())); map.put(new DataStoreInstanceType(PUB_KEY, CACHE), new StoreCallbackStats(pubKeyDatacache, new NotAvailNodeStoreStats())); map.put(new DataStoreInstanceType(PUB_KEY, SLASHDOT), new StoreCallbackStats(pubKeySlashdotcache, new NotAvailNodeStoreStats())); map.put(new DataStoreInstanceType(PUB_KEY, CLIENT), new StoreCallbackStats(pubKeyClientcache, new NotAvailNodeStoreStats())); return map; } public long getMaxTotalKeys() { return maxTotalKeys; } long timeLastDumpedHits; public void dumpStoreHits() { long now = System.currentTimeMillis(); if(now - timeLastDumpedHits > 5000) { timeLastDumpedHits = now; } else return; Logger.minor(this, "Distribution of hits and misses over stores:\n"+ "CHK Datastore: "+chkDatastore.hits()+ '/' +(chkDatastore.hits()+chkDatastore.misses())+ '/' +chkDatastore.keyCount()+ "\nCHK Datacache: "+chkDatacache.hits()+ '/' +(chkDatacache.hits()+chkDatacache.misses())+ '/' +chkDatacache.keyCount()+ "\nSSK Datastore: "+sskDatastore.hits()+ '/' +(sskDatastore.hits()+sskDatastore.misses())+ '/' +sskDatastore.keyCount()+ "\nSSK Datacache: "+sskDatacache.hits()+ '/' +(sskDatacache.hits()+sskDatacache.misses())+ '/' +sskDatacache.keyCount()); } public void storeShallow(CHKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) { store(block, false, canWriteClientCache, canWriteDatastore, forULPR); } /** * Store a datum. * @param block * a KeyBlock * @param deep If true, insert to the store as well as the cache. Do not set * this to true unless the store results from an insert, and this node is the * closest node to the target; see the description of chkDatastore. */ public void store(KeyBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException { if(block instanceof CHKBlock) store((CHKBlock)block, deep, canWriteClientCache, canWriteDatastore, forULPR); else if(block instanceof SSKBlock) store((SSKBlock)block, deep, false, canWriteClientCache, canWriteDatastore, forULPR); else throw new IllegalArgumentException("Unknown keytype "); } private void store(CHKBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) { try { double loc = block.getKey().toNormalizedDouble(); if (canWriteClientCache) { chkClientcache.put(block, false); nodeStats.avgClientCacheCHKLocation.report(loc); } if ((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) { chkSlashdotcache.put(block, false); nodeStats.avgSlashdotCacheCHKLocation.report(loc); } if (canWriteDatastore || writeLocalToDatastore) { if (deep) { chkDatastore.put(block, !canWriteDatastore); nodeStats.avgStoreCHKLocation.report(loc); } chkDatacache.put(block, !canWriteDatastore); nodeStats.avgCacheCHKLocation.report(loc); } if (canWriteDatastore || forULPR || useSlashdotCache) failureTable.onFound(block); } catch (IOException e) { Logger.error(this, "Cannot store data: "+e, e); } catch (Throwable t) { System.err.println(t); t.printStackTrace(); Logger.error(this, "Caught "+t+" storing data", t); } if(clientCore != null && clientCore.requestStarters != null) { clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(block); clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(block); } } /** Store the block if this is a sink. Call for inserts. */ public void storeInsert(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyCollisionException { store(block, deep, overwrite, canWriteClientCache, canWriteDatastore, false); } /** Store only to the cache, and not the store. Called by requests, * as only inserts cause data to be added to the store. */ public void storeShallow(SSKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean fromULPR) throws KeyCollisionException { store(block, false, canWriteClientCache, canWriteDatastore, fromULPR); } public void store(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException { try { // Store the pubkey before storing the data, otherwise we can get a race condition and // end up deleting the SSK data. double loc = block.getKey().toNormalizedDouble(); getPubKey.cacheKey((block.getKey()).getPubKeyHash(), (block.getKey()).getPubKey(), deep, canWriteClientCache, canWriteDatastore, forULPR || useSlashdotCache, writeLocalToDatastore); if(canWriteClientCache) { sskClientcache.put(block, overwrite, false); nodeStats.avgClientCacheSSKLocation.report(loc); } if((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) { sskSlashdotcache.put(block, overwrite, false); nodeStats.avgSlashdotCacheSSKLocation.report(loc); } if(canWriteDatastore || writeLocalToDatastore) { if(deep) { sskDatastore.put(block, overwrite, !canWriteDatastore); nodeStats.avgStoreSSKLocation.report(loc); } sskDatacache.put(block, overwrite, !canWriteDatastore); nodeStats.avgCacheSSKLocation.report(loc); } if(canWriteDatastore || forULPR || useSlashdotCache) failureTable.onFound(block); } catch (IOException e) { Logger.error(this, "Cannot store data: "+e, e); } catch (KeyCollisionException e) { throw e; } catch (Throwable t) { System.err.println(t); t.printStackTrace(); Logger.error(this, "Caught "+t+" storing data", t); } if(clientCore != null && clientCore.requestStarters != null) { clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(block); clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(block); } } final boolean decrementAtMax; final boolean decrementAtMin; /** * Decrement the HTL according to the policy of the given * NodePeer if it is non-null, or do something else if it is * null. */ public short decrementHTL(PeerNode source, short htl) { if(source != null) return source.decrementHTL(htl); // Otherwise... if(htl >= maxHTL) htl = maxHTL; if(htl <= 0) { return 0; } if(htl == maxHTL) { if(decrementAtMax || disableProbabilisticHTLs) htl--; return htl; } if(htl == 1) { if(decrementAtMin || disableProbabilisticHTLs) htl--; return htl; } return --htl; } /** * Fetch or create an CHKInsertSender for a given key/htl. * @param key The key to be inserted. * @param htl The current HTL. We can't coalesce inserts across * HTL's. * @param uid The UID of the caller's request chain, or a new * one. This is obviously not used if there is already an * CHKInsertSender running. * @param source The node that sent the InsertRequest, or null * if it originated locally. * @param ignoreLowBackoff * @param preferInsert */ public CHKInsertSender makeInsertSender(NodeCHK key, short htl, long uid, InsertTag tag, PeerNode source, byte[] headers, PartiallyReceivedBlock prb, boolean fromStore, boolean canWriteClientCache, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) { if(logMINOR) Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore); CHKInsertSender is = null; is = new CHKInsertSender(key, uid, tag, headers, htl, source, this, prb, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff,realTimeFlag); is.start(); // CHKInsertSender adds itself to insertSenders return is; } /** * Fetch or create an SSKInsertSender for a given key/htl. * @param key The key to be inserted. * @param htl The current HTL. We can't coalesce inserts across * HTL's. * @param uid The UID of the caller's request chain, or a new * one. This is obviously not used if there is already an * SSKInsertSender running. * @param source The node that sent the InsertRequest, or null * if it originated locally. * @param ignoreLowBackoff * @param preferInsert */ public SSKInsertSender makeInsertSender(SSKBlock block, short htl, long uid, InsertTag tag, PeerNode source, boolean fromStore, boolean canWriteClientCache, boolean canWriteDatastore, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) { NodeSSK key = block.getKey(); if(key.getPubKey() == null) { throw new IllegalArgumentException("No pub key when inserting"); } getPubKey.cacheKey(key.getPubKeyHash(), key.getPubKey(), false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore); Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore); SSKInsertSender is = null; is = new SSKInsertSender(block, uid, tag, htl, source, this, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag); is.start(); return is; } /** * @return Some status information. */ public String getStatus() { StringBuilder sb = new StringBuilder(); if (peers != null) sb.append(peers.getStatus()); else sb.append("No peers yet"); sb.append(tracker.getNumTransferringRequestSenders()); sb.append('\n'); return sb.toString(); } /** * @return TMCI peer list */ public String getTMCIPeerList() { StringBuilder sb = new StringBuilder(); if (peers != null) sb.append(peers.getTMCIPeerList()); else sb.append("No peers yet"); return sb.toString(); } /** Length of signature parameters R and S */ static final int SIGNATURE_PARAMETER_LENGTH = 32; public ClientKeyBlock fetchKey(ClientKey key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyVerifyException { if(key instanceof ClientCHK) return fetch((ClientCHK)key, canReadClientCache, canWriteClientCache, canWriteDatastore); else if(key instanceof ClientSSK) return fetch((ClientSSK)key, canReadClientCache, canWriteClientCache, canWriteDatastore); else throw new IllegalStateException("Don't know what to do with "+key); } public ClientKeyBlock fetch(ClientSSK clientSSK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws SSKVerifyException { DSAPublicKey key = clientSSK.getPubKey(); if(key == null) { key = getPubKey.getKey(clientSSK.pubKeyHash, canReadClientCache, false, null); } if(key == null) return null; clientSSK.setPublicKey(key); SSKBlock block = fetch((NodeSSK)clientSSK.getNodeKey(true), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); if(block == null) { if(logMINOR) Logger.minor(this, "Could not find key for "+clientSSK); return null; } // Move the pubkey to the top of the LRU, and fix it if it // was corrupt. getPubKey.cacheKey(clientSSK.pubKeyHash, key, false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore); return ClientSSKBlock.construct(block, clientSSK); } private ClientKeyBlock fetch(ClientCHK clientCHK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws CHKVerifyException { CHKBlock block = fetch(clientCHK.getNodeCHK(), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null); if(block == null) return null; return new ClientCHKBlock(block, clientCHK); } public void exit(int reason) { try { this.park(); System.out.println("Goodbye."); System.out.println(reason); } finally { System.exit(reason); } } public void exit(String reason){ try { this.park(); System.out.println("Goodbye. from "+this+" ("+reason+ ')'); } finally { System.exit(0); } } /** * Returns true if the node is shutting down. * The packet receiver calls this for every packet, and boolean is atomic, so this method is not synchronized. */ public boolean isStopping() { return isStopping; } /** * Get the node into a state where it can be stopped safely * May be called twice - once in exit (above) and then again * from the wrapper triggered by calling System.exit(). Beware! */ public void park() { synchronized(this) { if(isStopping) return; isStopping = true; } try { Message msg = DMT.createFNPDisconnect(false, false, -1, new ShortBuffer(new byte[0])); peers.localBroadcast(msg, true, false, peers.ctrDisconn); } catch (Throwable t) { try { // E.g. if we haven't finished startup Logger.error(this, "Failed to tell peers we are going down: "+t, t); } catch (Throwable t1) { // Ignore. We don't want to mess up the exit process! } } config.store(); if(random instanceof PersistentRandomSource) { ((PersistentRandomSource) random).write_seed(true); } } public NodeUpdateManager getNodeUpdater(){ return nodeUpdater; } public DarknetPeerNode[] getDarknetConnections() { return peers.getDarknetPeers(); } public boolean addPeerConnection(PeerNode pn) { boolean retval = peers.addPeer(pn); peers.writePeersUrgent(pn.isOpennet()); return retval; } public void removePeerConnection(PeerNode pn) { peers.disconnectAndRemove(pn, true, false, false); } public void onConnectedPeer() { if(logMINOR) Logger.minor(this, "onConnectedPeer()"); ipDetector.onConnectedPeer(); } public int getFNPPort(){ return this.getDarknetPortNumber(); } public boolean isOudated() { return peers.isOutdated(); } private Map<Integer, NodeToNodeMessageListener> n2nmListeners = new HashMap<Integer, NodeToNodeMessageListener>(); public synchronized void registerNodeToNodeMessageListener(int type, NodeToNodeMessageListener listener) { n2nmListeners.put(type, listener); } /** * Handle a received node to node message */ public void receivedNodeToNodeMessage(Message m, PeerNode src) { int type = ((Integer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_TYPE)).intValue(); ShortBuffer messageData = (ShortBuffer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_DATA); receivedNodeToNodeMessage(src, type, messageData, false); } public void receivedNodeToNodeMessage(PeerNode src, int type, ShortBuffer messageData, boolean partingMessage) { boolean fromDarknet = src instanceof DarknetPeerNode; NodeToNodeMessageListener listener = null; synchronized(this) { listener = n2nmListeners.get(type); } if(listener == null) { Logger.error(this, "Unknown n2nm ID: "+type+" - discarding packet length "+messageData.getLength()); return; } listener.handleMessage(messageData.getData(), fromDarknet, src, type); } private NodeToNodeMessageListener diffNoderefListener = new NodeToNodeMessageListener() { @Override public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) { Logger.normal(this, "Received differential node reference node to node message from "+src.getPeer()); SimpleFieldSet fs = null; try { fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false); } catch (IOException e) { Logger.error(this, "IOException while parsing node to node message data", e); return; } if(fs.get("n2nType") != null) { fs.removeValue("n2nType"); } try { src.processDiffNoderef(fs); } catch (FSParseException e) { Logger.error(this, "FSParseException while parsing node to node message data", e); return; } } }; private NodeToNodeMessageListener fproxyN2NMListener = new NodeToNodeMessageListener() { @Override public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) { if(!fromDarknet) { Logger.error(this, "Got N2NTM from non-darknet node ?!?!?!: from "+src); return; } DarknetPeerNode darkSource = (DarknetPeerNode) src; Logger.normal(this, "Received N2NTM from '"+darkSource.getPeer()+"'"); SimpleFieldSet fs = null; try { fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } catch (IOException e) { Logger.error(this, "IOException while parsing node to node message data", e); return; } fs.putOverwrite("n2nType", Integer.toString(type)); fs.putOverwrite("receivedTime", Long.toString(System.currentTimeMillis())); fs.putOverwrite("receivedAs", "nodeToNodeMessage"); int fileNumber = darkSource.writeNewExtraPeerDataFile( fs, EXTRA_PEER_DATA_TYPE_N2NTM); if( fileNumber == -1 ) { Logger.error( this, "Failed to write N2NTM to extra peer data file for peer "+darkSource.getPeer()); } // Keep track of the fileNumber so we can potentially delete the extra peer data file later, the file is authoritative try { handleNodeToNodeTextMessageSimpleFieldSet(fs, darkSource, fileNumber); } catch (FSParseException e) { // Shouldn't happen throw new Error(e); } } }; /** * Handle a node to node text message SimpleFieldSet * @throws FSParseException */ public void handleNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException { if(logMINOR) Logger.minor(this, "Got node to node message: \n"+fs); int overallType = fs.getInt("n2nType"); fs.removeValue("n2nType"); if(overallType == Node.N2N_MESSAGE_TYPE_FPROXY) { handleFproxyNodeToNodeTextMessageSimpleFieldSet(fs, source, fileNumber); } else { Logger.error(this, "Received unknown node to node message type '"+overallType+"' from "+source.getPeer()); } } private void handleFproxyNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException { int type = fs.getInt("type"); if(type == Node.N2N_TEXT_MESSAGE_TYPE_USERALERT) { source.handleFproxyN2NTM(fs, fileNumber); } else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER) { source.handleFproxyFileOffer(fs, fileNumber); } else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED) { source.handleFproxyFileOfferAccepted(fs, fileNumber); } else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED) { source.handleFproxyFileOfferRejected(fs, fileNumber); } else if(type == Node.N2N_TEXT_MESSAGE_TYPE_BOOKMARK) { source.handleFproxyBookmarkFeed(fs, fileNumber); } else if(type == Node.N2N_TEXT_MESSAGE_TYPE_DOWNLOAD) { source.handleFproxyDownloadFeed(fs, fileNumber); } else { Logger.error(this, "Received unknown fproxy node to node message sub-type '"+type+"' from "+source.getPeer()); } } public String getMyName() { return myName; } public MessageCore getUSM() { return usm; } public LocationManager getLocationManager() { return lm; } public int getSwaps() { return LocationManager.swaps; } public int getNoSwaps() { return LocationManager.noSwaps; } public int getStartedSwaps() { return LocationManager.startedSwaps; } public int getSwapsRejectedAlreadyLocked() { return LocationManager.swapsRejectedAlreadyLocked; } public int getSwapsRejectedNowhereToGo() { return LocationManager.swapsRejectedNowhereToGo; } public int getSwapsRejectedRateLimit() { return LocationManager.swapsRejectedRateLimit; } public int getSwapsRejectedRecognizedID() { return LocationManager.swapsRejectedRecognizedID; } public PeerNode[] getPeerNodes() { return peers.myPeers(); } public PeerNode[] getConnectedPeers() { return peers.connectedPeers(); } /** * Return a peer of the node given its ip and port, name or identity, as a String */ public PeerNode getPeerNode(String nodeIdentifier) { for(PeerNode pn: peers.myPeers()) { Peer peer = pn.getPeer(); String nodeIpAndPort = ""; if(peer != null) { nodeIpAndPort = peer.toString(); } String identity = pn.getIdentityString(); if(pn instanceof DarknetPeerNode) { DarknetPeerNode dpn = (DarknetPeerNode) pn; String name = dpn.myName; if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier) || name.equals(nodeIdentifier)) { return pn; } } else { if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier)) { return pn; } } } return null; } public boolean isHasStarted() { return hasStarted; } public void queueRandomReinsert(KeyBlock block) { clientCore.queueRandomReinsert(block); } public String getExtraPeerDataDir() { return extraPeerDataDir.getPath(); } public boolean noConnectedPeers() { return !peers.anyConnectedPeers(); } public double getLocation() { return lm.getLocation(); } public double getLocationChangeSession() { return lm.getLocChangeSession(); } public int getAverageOutgoingSwapTime() { return lm.getAverageSwapTime(); } public long getSendSwapInterval() { return lm.getSendSwapInterval(); } public int getNumberOfRemotePeerLocationsSeenInSwaps() { return lm.numberOfRemotePeerLocationsSeenInSwaps; } public boolean isAdvancedModeEnabled() { if(clientCore == null) return false; return clientCore.isAdvancedModeEnabled(); } public boolean isFProxyJavascriptEnabled() { return clientCore.isFProxyJavascriptEnabled(); } // FIXME convert these kind of threads to Checkpointed's and implement a handler // using the PacketSender/Ticker. Would save a few threads. public int getNumARKFetchers() { int x = 0; for(PeerNode p: peers.myPeers()) { if(p.isFetchingARK()) x++; } return x; } // FIXME put this somewhere else private volatile Object statsSync = new Object(); /** The total number of bytes of real data i.e.&nbsp;payload sent by the node */ private long totalPayloadSent; public void sentPayload(int len) { synchronized(statsSync) { totalPayloadSent += len; } } /** * Get the total number of bytes of payload (real data) sent by the node * * @return Total payload sent in bytes */ public long getTotalPayloadSent() { synchronized(statsSync) { return totalPayloadSent; } } public void setName(String key) throws InvalidConfigValueException, NodeNeedRestartException { config.get("node").getOption("name").setValue(key); } public Ticker getTicker() { return ticker; } public int getUnclaimedFIFOSize() { return usm.getUnclaimedFIFOSize(); } /** * Connect this node to another node (for purposes of testing) */ public void connectToSeednode(SeedServerTestPeerNode node) throws OpennetDisabledException, FSParseException, PeerParseException, ReferenceSignatureVerificationException { peers.addPeer(node,false,false); } public void connect(Node node, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException { peers.connect(node.darknetCrypto.exportPublicFieldSet(), darknetCrypto.packetMangler, trust, visibility); } public short maxHTL() { return maxHTL; } public int getDarknetPortNumber() { return darknetCrypto.portNumber; } public synchronized int getOutputBandwidthLimit() { return outputBandwidthLimit; } public synchronized int getInputBandwidthLimit() { if(inputLimitDefault) return outputBandwidthLimit * 4; return inputBandwidthLimit; } /** * @return total datastore size in bytes. */ public synchronized long getStoreSize() { return maxTotalDatastoreSize; } @Override public synchronized void setTimeSkewDetectedUserAlert() { if(timeSkewDetectedUserAlert == null) { timeSkewDetectedUserAlert = new TimeSkewDetectedUserAlert(); clientCore.alerts.register(timeSkewDetectedUserAlert); } } public File getNodeDir() { return nodeDir.dir(); } public File getCfgDir() { return cfgDir.dir(); } public File getUserDir() { return userDir.dir(); } public File getRunDir() { return runDir.dir(); } public File getStoreDir() { return storeDir.dir(); } public File getPluginDir() { return pluginDir.dir(); } public ProgramDirectory nodeDir() { return nodeDir; } public ProgramDirectory cfgDir() { return cfgDir; } public ProgramDirectory userDir() { return userDir; } public ProgramDirectory runDir() { return runDir; } public ProgramDirectory storeDir() { return storeDir; } public ProgramDirectory pluginDir() { return pluginDir; } public DarknetPeerNode createNewDarknetNode(SimpleFieldSet fs, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException { return new DarknetPeerNode(fs, this, darknetCrypto, false, trust, visibility); } public OpennetPeerNode createNewOpennetNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException { if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled"); return new OpennetPeerNode(fs, this, opennet.crypto, opennet, false); } public SeedServerTestPeerNode createNewSeedServerTestPeerNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException { if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled"); return new SeedServerTestPeerNode(fs, this, opennet.crypto, true); } public OpennetPeerNode addNewOpennetNode(SimpleFieldSet fs, ConnectionType connectionType) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException { // FIXME: perhaps this should throw OpennetDisabledExcemption rather than returing false? if(opennet == null) return null; return opennet.addNewOpennetNode(fs, connectionType, false); } public byte[] getOpennetPubKeyHash() { return opennet.crypto.ecdsaPubKeyHash; } public byte[] getDarknetPubKeyHash() { return darknetCrypto.ecdsaPubKeyHash; } public synchronized boolean isOpennetEnabled() { return opennet != null; } public SimpleFieldSet exportDarknetPublicFieldSet() { return darknetCrypto.exportPublicFieldSet(); } public SimpleFieldSet exportOpennetPublicFieldSet() { return opennet.crypto.exportPublicFieldSet(); } public SimpleFieldSet exportDarknetPrivateFieldSet() { return darknetCrypto.exportPrivateFieldSet(); } public SimpleFieldSet exportOpennetPrivateFieldSet() { return opennet.crypto.exportPrivateFieldSet(); } /** * Should the IP detection code only use the IP address override and the bindTo information, * rather than doing a full detection? */ public synchronized boolean dontDetect() { // Only return true if bindTo is set on all ports which are in use if(!darknetCrypto.getBindTo().isRealInternetAddress(false, true, false)) return false; if(opennet != null) { if(opennet.crypto.getBindTo().isRealInternetAddress(false, true, false)) return false; } return true; } public int getOpennetFNPPort() { if(opennet == null) return -1; return opennet.crypto.portNumber; } public OpennetManager getOpennet() { return opennet; } public synchronized boolean passOpennetRefsThroughDarknet() { return passOpennetRefsThroughDarknet; } /** * Get the set of public ports that need to be forwarded. These are internal * ports, not necessarily external - they may be rewritten by the NAT. * @return A Set of ForwardPort's to be fed to port forward plugins. */ public Set<ForwardPort> getPublicInterfacePorts() { HashSet<ForwardPort> set = new HashSet<ForwardPort>(); // FIXME IPv6 support set.add(new ForwardPort("darknet", false, ForwardPort.PROTOCOL_UDP_IPV4, darknetCrypto.portNumber)); if(opennet != null) { NodeCrypto crypto = opennet.crypto; if(crypto != null) { set.add(new ForwardPort("opennet", false, ForwardPort.PROTOCOL_UDP_IPV4, crypto.portNumber)); } } return set; } /** * Get the time since the node was started in milliseconds. * * @return Uptime in milliseconds */ public long getUptime() { return System.currentTimeMillis() - usm.getStartedTime(); } public synchronized UdpSocketHandler[] getPacketSocketHandlers() { // FIXME better way to get these! if(opennet != null) { return new UdpSocketHandler[] { darknetCrypto.socket, opennet.crypto.socket }; // TODO Auto-generated method stub } else { return new UdpSocketHandler[] { darknetCrypto.socket }; } } public int getMaxOpennetPeers() { return maxOpennetPeers; } public void onAddedValidIP() { OpennetManager om; synchronized(this) { om = opennet; } if(om != null) { Announcer announcer = om.announcer; if(announcer != null) { announcer.maybeSendAnnouncement(); } } } public boolean isSeednode() { return acceptSeedConnections; } /** * Returns true if the packet receiver should try to decode/process packets that are not from a peer (i.e. from a seed connection) * The packet receiver calls this upon receiving an unrecognized packet. */ public boolean wantAnonAuth(boolean isOpennet) { if(isOpennet) return opennet != null && acceptSeedConnections; else return false; } // FIXME make this configurable // Probably should wait until we have non-opennet anon auth so we can add it to NodeCrypto. public boolean wantAnonAuthChangeIP(boolean isOpennet) { return !isOpennet; } public boolean opennetDefinitelyPortForwarded() { OpennetManager om; synchronized(this) { om = this.opennet; } if(om == null) return false; NodeCrypto crypto = om.crypto; if(crypto == null) return false; return crypto.definitelyPortForwarded(); } public boolean darknetDefinitelyPortForwarded() { if(darknetCrypto == null) return false; return darknetCrypto.definitelyPortForwarded(); } public boolean hasKey(Key key, boolean canReadClientCache, boolean forULPR) { // FIXME optimise! if(key instanceof NodeCHK) return fetch((NodeCHK)key, true, canReadClientCache, false, false, forULPR, null) != null; else return fetch((NodeSSK)key, true, canReadClientCache, false, false, forULPR, null) != null; } /** * Warning: does not announce change in location! */ public void setLocation(double loc) { lm.setLocation(loc); } public boolean peersWantKey(Key key) { return failureTable.peersWantKey(key, null); } private SimpleUserAlert alertMTUTooSmall; public final RequestClient nonPersistentClientBulk = new RequestClientBuilder().build(); public final RequestClient nonPersistentClientRT = new RequestClientBuilder().realTime().build(); public void setDispatcherHook(NodeDispatcherCallback cb) { this.dispatcher.setHook(cb); } public boolean shallWePublishOurPeersLocation() { return publishOurPeersLocation; } public boolean shallWeRouteAccordingToOurPeersLocation(int htl) { return routeAccordingToOurPeersLocation && htl > 1; } /** Can be called to decrypt client.dat* etc, or can be called when switching from another * security level to HIGH. */ public void setMasterPassword(String password, boolean inFirstTimeWizard) throws AlreadySetPasswordException, MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException { MasterKeys k; synchronized(this) { if(keys == null) { // Decrypting. keys = MasterKeys.read(masterKeysFile, secureRandom, password); databaseKey = keys.createDatabaseKey(secureRandom); } else { // Setting password when changing to HIGH from another mode. keys.changePassword(masterKeysFile, password, secureRandom); return; } k = keys; } setPasswordInner(k, inFirstTimeWizard); } private void setPasswordInner(MasterKeys keys, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException { MasterSecret secret = keys.getPersistentMasterSecret(); clientCore.setupMasterSecret(secret); boolean wantClientCache = false; boolean wantDatabase = false; synchronized(this) { wantClientCache = clientCacheAwaitingPassword; wantDatabase = databaseAwaitingPassword; databaseAwaitingPassword = false; } if(wantClientCache) activatePasswordedClientCache(keys); if(wantDatabase) lateSetupDatabase(keys.createDatabaseKey(secureRandom)); } private void activatePasswordedClientCache(MasterKeys keys) { synchronized(this) { if(clientCacheType.equals("ram")) { System.err.println("RAM client cache cannot be passworded!"); return; } if(!clientCacheType.equals("salt-hash")) { System.err.println("Unknown client cache type, cannot activate passworded store: "+clientCacheType); return; } } Runnable migrate = new MigrateOldStoreData(true); String suffix = getStoreSuffix(); try { initSaltHashClientCacheFS(suffix, true, keys.clientCacheMasterKey); } catch (NodeInitException e) { Logger.error(this, "Unable to activate passworded client cache", e); System.err.println("Unable to activate passworded client cache: "+e); e.printStackTrace(); return; } synchronized(this) { clientCacheAwaitingPassword = false; } executor.execute(migrate, "Migrate data from previous store"); } public void changeMasterPassword(String oldPassword, String newPassword, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException, AlreadySetPasswordException { if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM) Logger.error(this, "Changing password while physical threat level is at MAXIMUM???"); if(masterKeysFile.exists()) { keys.changePassword(masterKeysFile, newPassword, secureRandom); setPasswordInner(keys, inFirstTimeWizard); } else { setMasterPassword(newPassword, inFirstTimeWizard); } } public static class AlreadySetPasswordException extends Exception { final private static long serialVersionUID = -7328456475029374032L; } public synchronized File getMasterPasswordFile() { return masterKeysFile; } boolean hasPanicked() { return hasPanicked; } public void panic() { hasPanicked = true; clientCore.clientLayerPersister.panic(); clientCore.clientLayerPersister.killAndWaitForNotRunning(); try { MasterKeys.killMasterKeys(getMasterPasswordFile()); } catch (IOException e) { System.err.println("Unable to wipe master passwords key file!"); System.err.println("Please delete " + getMasterPasswordFile() + " to ensure that nobody can recover your old downloads."); } // persistent-temp will be cleaned on restart. } public void finishPanic() { WrapperManager.restart(); System.exit(0); } public boolean awaitingPassword() { if(clientCacheAwaitingPassword) return true; if(databaseAwaitingPassword) return true; return false; } public boolean wantEncryptedDatabase() { return this.securityLevels.getPhysicalThreatLevel() != PHYSICAL_THREAT_LEVEL.LOW; } public boolean wantNoPersistentDatabase() { return this.securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM; } public boolean hasDatabase() { return !clientCore.clientLayerPersister.isKilledOrNotLoaded(); } /** * @return canonical path of the database file in use. */ public String getDatabasePath() throws IOException { return clientCore.clientLayerPersister.getWriteFilename().toString(); } /** Should we commit the block to the store rather than the cache? * * <p>We used to check whether we are a sink by checking whether any peer has * a closer location than we do. Then we made low-uptime nodes exempt from * this calculation: if we route to a low uptime node with a closer location, * we want to store it anyway since he may go offline. The problem was that * if we routed to a low-uptime node, and there was another option that wasn't * low-uptime but was closer to the target than we were, then we would not * store in the store. Also, routing isn't always by the closest peer location: * FOAF and per-node failure tables change it. So now, we consider the nodes * we have actually routed to:</p> * * <p>Store in datastore if our location is closer to the target than:</p><ol> * <li>the source location (if any, and ignoring if low-uptime)</li> * <li>the locations of the nodes we just routed to (ditto)</li> * </ol> * * @param key * @param source * @param routedTo * @return */ public boolean shouldStoreDeep(Key key, PeerNode source, PeerNode[] routedTo) { double myLoc = getLocation(); double target = key.toNormalizedDouble(); double myDist = Location.distance(myLoc, target); // First, calculate whether we would have stored it using the old formula. if(logMINOR) Logger.minor(this, "Should store for "+key+" ?"); // Don't sink store if any of the nodes we routed to, or our predecessor, is both high-uptime and closer to the target than we are. if(source != null && !source.isLowUptime()) { if(Location.distance(source, target) < myDist) { if(logMINOR) Logger.minor(this, "Not storing because source is closer to target for "+key+" : "+source); return false; } } for(PeerNode pn : routedTo) { if(Location.distance(pn, target) < myDist && !pn.isLowUptime()) { if(logMINOR) Logger.minor(this, "Not storing because peer "+pn+" is closer to target for "+key+" his loc "+pn.getLocation()+" my loc "+myLoc+" target is "+target); return false; } else { if(logMINOR) Logger.minor(this, "Should store maybe, peer "+pn+" loc = "+pn.getLocation()+" my loc is "+myLoc+" target is "+target+" low uptime is "+pn.isLowUptime()); } } if(logMINOR) Logger.minor(this, "Should store returning true for "+key+" target="+target+" myLoc="+myLoc+" peers: "+routedTo.length); return true; } public boolean getWriteLocalToDatastore() { return writeLocalToDatastore; } public boolean getUseSlashdotCache() { return useSlashdotCache; } // FIXME remove the visibility alert after a few builds. public void createVisibilityAlert() { synchronized(this) { if(showFriendsVisibilityAlert) return; showFriendsVisibilityAlert = true; } // Wait until startup completed. this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { config.store(); } }, 0); registerFriendsVisibilityAlert(); } private UserAlert visibilityAlert = new SimpleUserAlert(true, l10n("pleaseSetPeersVisibilityAlertTitle"), l10n("pleaseSetPeersVisibilityAlert"), l10n("pleaseSetPeersVisibilityAlert"), UserAlert.ERROR) { @Override public void onDismiss() { synchronized(Node.this) { showFriendsVisibilityAlert = false; } config.store(); unregisterFriendsVisibilityAlert(); } }; private void registerFriendsVisibilityAlert() { if(clientCore == null || clientCore.alerts == null) { // Wait until startup completed. this.getTicker().queueTimedJob(new Runnable() { @Override public void run() { registerFriendsVisibilityAlert(); } }, 0); return; } clientCore.alerts.register(visibilityAlert); } private void unregisterFriendsVisibilityAlert() { clientCore.alerts.unregister(visibilityAlert); } public int getMinimumMTU() { int mtu; synchronized(this) { mtu = maxPacketSize; } if(ipDetector != null) { int detected = ipDetector.getMinimumDetectedMTU(); if(detected < mtu) return detected; } return mtu; } public void updateMTU() { this.darknetCrypto.socket.calculateMaxPacketSize(); OpennetManager om = opennet; if(om != null) { om.crypto.socket.calculateMaxPacketSize(); } } public static boolean isTestnetEnabled() { return false; } public MersenneTwister createRandom() { byte[] buf = new byte[16]; random.nextBytes(buf); return new MersenneTwister(buf); } public boolean enableNewLoadManagement(boolean realTimeFlag) { NodeStats stats = this.nodeStats; if(stats == null) { Logger.error(this, "Calling enableNewLoadManagement before Node constructor completes! FIX THIS!", new Exception("error")); return false; } return stats.enableNewLoadManagement(realTimeFlag); } /** FIXME move to Probe.java? */ public boolean enableRoutedPing() { return enableRoutedPing; } public boolean updateIsUrgent() { OpennetManager om = getOpennet(); if(om != null) { if(om.announcer != null && om.announcer.isWaitingForUpdater()) return true; } if(peers.getPeerNodeStatusSize(PeerManager.PEER_NODE_STATUS_TOO_NEW, true) > PeerManager.OUTDATED_MIN_TOO_NEW_DARKNET) return true; return false; } public byte[] getPluginStoreKey(String storeIdentifier) { DatabaseKey key; synchronized(this) { key = databaseKey; } if(key != null) return key.getPluginStoreKey(storeIdentifier); else return null; } public PluginManager getPluginManager() { return pluginManager; } DatabaseKey getDatabaseKey() { return databaseKey; } }
Java
/* $Id: style.css,v 1.38.2.4 2009/09/14 13:10:47 goba Exp $ */ /** * Garland, for Drupal 6.x * Stefan Nagtegaal, iStyledThis [dot] nl * Steven Wittens, acko [dot] net` * * If you use a customized color scheme, you must regenerate it after * modifying this file. */ /** * Generic elements */ body { margin: 0; padding: 0; font: 12px/170% Arial, Helvetica, sans-serif; color: #494949; } input { font: 12px/100% Arial, Helvetica, sans-serif; color: #494949; } textarea, select { font: 12px/160% Arial, Helvetica, sans-serif; color: #494949; } h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; font-weight: normal; font-family: Arial, Helvetica, sans-serif; } h1 { font-size: 170%; } h2 { font-size: 160%; line-height: 130%; } h3 { font-size: 140%; } h4 { font-size: 130%; } h5 { font-size: 120%; } h6 { font-size: 110%; } ul, quote, code, fieldset { margin: .5em 0; } p { margin: 0.6em 0 1.2em; padding: 0; } a:link, a:visited { color: #027AC6; text-decoration: none; } a:hover { color: #0062A0; text-decoration: underline; } a:active, a.active { color: #5895be; } hr { margin: 0; padding: 0; border: none; height: 1px; background: #5294c1; } ul { margin: 0.5em 0 1em; padding: 0; } ol { margin: 0.75em 0 1.25em; padding: 0; } ol li, ul li { margin: 0.4em 0 0.4em .5em; /* LTR */ } ul.menu, .item-list ul { margin: 0.35em 0 0 -0.5em; /* LTR */ padding: 0; } ul.menu ul, .item-list ul ul { margin-left: 0em; /* LTR */ } ol li, ul li, ul.menu li, .item-list ul li, li.leaf { margin: 0.15em 0 0.15em .5em; /* LTR */ } ul li, ul.menu li, .item-list ul li, li.leaf { padding: 0 0 .2em 1.5em; list-style-type: none; list-style-image: none; background: transparent url(images/menu-leaf.gif) no-repeat 1px .35em; /* LTR */ } ol li { padding: 0 0 .3em; margin-left: 2em; /* LTR */ } ul li.expanded { background: transparent url(images/menu-expanded.gif) no-repeat 1px .35em; /* LTR */ } ul li.collapsed { background: transparent url(images/menu-collapsed.gif) no-repeat 0px .35em; /* LTR */ } ul li.leaf a, ul li.expanded a, ul li.collapsed a { display: block; } ul.inline li { background: none; margin: 0; padding: 0 1em 0 0; /* LTR */ } ol.task-list { margin-left: 0; /* LTR */ list-style-type: none; list-style-image: none; } ol.task-list li { padding: 0.5em 1em 0.5em 2em; /* LTR */ } ol.task-list li.active { background: transparent url(images/task-list.png) no-repeat 3px 50%; /* LTR */ } ol.task-list li.done { color: #393; background: transparent url(../../misc/watchdog-ok.png) no-repeat 0px 50%; /* LTR */ } ol.task-list li.active { margin-right: 1em; /* LTR */ } fieldset ul.clear-block li { margin: 0; padding: 0; background-image: none; } dl { margin: 0.5em 0 1em 1.5em; /* LTR */ } dl dt { } dl dd { margin: 0 0 .5em 1.5em; /* LTR */ } img, a img { border: none; } table { margin: 1em 0; width: 100%; } thead th { border-bottom: 2px solid #d3e7f4; color: #494949; font-weight: bold; } th a:link, th a:visited { color: #6f9dbd; } td, th { padding: .3em .5em; } tr.even, tr.odd, tbody th { border: solid #d3e7f4; border-width: 1px 0; } tr.odd, tr.info { background-color: #edf5fa; } tr.even { background-color: #fff; } tr.drag { background-color: #fffff0; } tr.drag-previous { background-color: #ffd; } tr.odd td.active { background-color: #ddecf5; } tr.even td.active { background-color: #e6f1f7; } td.region, td.module, td.container, td.category { border-top: 1.5em solid #fff; border-bottom: 1px solid #b4d7f0; background-color: #d4e7f3; color: #455067; font-weight: bold; } tr:first-child td.region, tr:first-child td.module, tr:first-child td.container, tr:first-child td.category { border-top-width: 0; } span.form-required { color: #ffae00; } span.submitted, .description { font-size: 0.92em; color: #898989; } .description { line-height: 150%; margin-bottom: 0.75em; color: #898989; } .messages, .preview { margin: .75em 0 .75em; padding: .5em 1em; } .messages ul { margin: 0; } .form-checkboxes, .form-radios, .form-checkboxes .form-item, .form-radios .form-item { margin: 0.25em 0; } #center form { margin-bottom: 2em; } .form-button, .form-submit { margin: 2em 0.5em 1em 0; /* LTR */ } #dblog-form-overview .form-submit, .confirmation .form-submit, .search-form .form-submit, .poll .form-submit, fieldset .form-button, fieldset .form-submit, .sidebar .form-button, .sidebar .form-submit, table .form-button, table .form-submit { margin: 0; } .box { margin-bottom: 2.5em; } /** * Layout */ #header-region { min-height: 1em; background: #d2e6f3 url(images/bg-navigation.png) repeat-x 50% 100%; } #header-region .block { display: block; margin: 0 1em; } #header-region .block-region { display: block; margin: 0 0.5em 1em; padding: 0.5em; position: relative; top: 0.5em; } #header-region * { display: inline; line-height: 1.5em; margin-top: 0; margin-bottom: 0; } /* Header part*/ .headerMain{ background:url(images/bg.png) repeat-x 0 0; height:83px; width:100%; } .headertop{ width:885px; margin:0 auto; background:url(images/header.png) no-repeat top center; height:83px; } .headerLogo{ width:180px; float:left; } /* Prevent the previous directive from showing the content of script elements in Mozilla browsers. */ #header-region script { display: none; } #header-region p, #header-region img { margin-top: 0.5em; } #header-region h2 { margin: 0 1em 0 0; /* LTR */ } #header-region h3, #header-region label, #header-region li { margin: 0 1em; padding: 0; background: none; } #wrapper { background:#bebab8 url(images/main_bg.png) repeat 0 0; } #wrapper #container { margin: 0 auto; padding: 0 20px; max-width: 980px; } #wrapper #container #header { height: 80px; } #wrapper #container #header #logo-floater { position: absolute; } #wrapper #container #header h1, #wrapper #container #header h1 a:link, #wrapper #container #header h1 a:visited { line-height: 120px; position: relative; z-index: 2; white-space: nowrap; } #wrapper #container #header h1 span { font-weight: bold; } #wrapper #container #header h1 img { padding-top: 14px; padding-right: 20px; /* LTR */ float: left; /* LTR */ } /* With 3 columns, require a minimum width of 1000px to ensure there is enough horizontal space. */ body.sidebars { min-width: 980px; } /* With 2 columns, require a minimum width of 800px. */ body.sidebar-left, body.sidebar-right { min-width: 780px; } /* We must define 100% width to avoid the body being too narrow for near-empty pages */ #wrapper #container #center { margin:0px auto; width: 100%; } /* So we move the #center container over the sidebars to compensate */ body.sidebar-left #center { margin-left: -210px; } body.sidebar-right #center { margin-right: 0px; } body.sidebars #center { margin: 0 0px; } /* And add blanks left and right for the sidebars to fill */ body.sidebar-left #squeeze { margin-left: 0px; } body.sidebar-right #squeeze { margin-right: 0px; } body.sidebars #squeeze { margin: 0 0px; } /* We ensure the sidebars are still clickable using z-index */ #wrapper #container .sidebar { margin: 60px 0 5em; width: 210px; float: left; z-index: 2; position: relative; } #wrapper #container .sidebar .block { margin: 0 0 1.5em 0; } #sidebar-left .block { padding: 0 15px 0 0px; } #sidebar-right .block { padding: 0 0px 0 15px; } .block .content { margin: 0.5em 0; } #sidebar-left .block-region { margin: 0 15px 0 0px; /* LTR */ } #sidebar-right .block-region { margin: 0 0px 0 15px; /* LTR */ } .block-region { padding: 1em; background: transparent; border: 2px dashed #b4d7f0; text-align: center; font-size: 1.3em; } /* Now we add the backgrounds for the main content shading */ #wrapper #container #center #squeeze { background: #fff url(images/bg-content.png) repeat-x 50% 0; position: relative; } #wrapper #container #center .right-corner { background: #e3e0df; position: relative; left: 10px; border-right:1px solid #FFF; } #wrapper #container #center .right-corner .left-corner { padding: 60px 25px 5em 35px; background: #e3e0df; border:1px solid #FFF; border-right:0px; margin-left: -10px; position: relative; left: -10px; min-height: 400px; } #wrapper #container #footer { float: none; clear: both; text-align: center; margin: 4em 0 -3em; color: #898989; } #wrapper #container .breadcrumb { position: absolute; top: 15px; left: 35px; /* LTR */ z-index: 3; } body.sidebar-left #footer { margin-left: -210px; } body.sidebar-right #footer { margin-right: -210px; } body.sidebars #footer { margin: 0 -210px; } /** * Header */ #wrapper #container #header h1, #wrapper #container #header h1 a:link, #wrapper #container #header h1 a:visited { color: #fff; font-weight: normal; text-shadow: #1659ac 0px 1px 3px; font-size: 1.5em; } #wrapper #container #header h1 a:hover { text-decoration: none; } #wrapper #container .breadcrumb { font-size: 0.92em; } #wrapper #container .breadcrumb, #wrapper #container .breadcrumb a { color: #529ad6; } #mission { padding: 1em; background-color: #fff; border: 1px solid #e0e5fb; margin-bottom: 2em; } /** * Primary navigation */ ul.primary-links { margin: 0; padding: 0; float: right; /* LTR */ position: relative; z-index: 4; } ul.primary-links li { margin: 0; padding: 0; float: left; /* LTR */ background-image: none; } ul.primary-links li a, ul.primary-links li a:link, ul.primary-links li a:visited { display: block; margin: 0 1em; padding: .75em 0 0; color: #fff; background: transparent url(images/bg-navigation-item.png) no-repeat 50% 0; } ul.primary-links li a:hover, ul.primary-links li a.active { color: #fff; background: transparent url(images/bg-navigation-item-hover.png) no-repeat 50% 0; } /** * Secondary navigation */ ul.secondary-links { margin: 0; padding: 18px 0 0; float: right; /* LTR */ clear: right; /* LTR */ position: relative; z-index: 4; } ul.secondary-links li { margin: 0; padding: 0; float: left; /* LTR */ background-image: none; } ul.secondary-links li a, ul.secondary-links li a:link, ul.secondary-links li a:visited { display: block; margin: 0 1em; padding: .75em 0 0; color: #cde3f1; background: transparent; } ul.secondary-links li a:hover, ul.secondary-links li a.active { color: #cde3f1; background: transparent; } /** * Local tasks */ ul.primary, ul.primary li, ul.secondary, ul.secondary li { border: 0; background: none; margin: 0; padding: 0; } #tabs-wrapper { margin: 0 -26px 1em; padding: 0 26px; border-bottom: 1px solid #e9eff3; position: relative; } ul.primary { padding: 0.5em 0 10px; float: left; /* LTR */ } ul.secondary { clear: both; text-align: left; /* LTR */ border-bottom: 1px solid #e9eff3; margin: -0.2em -26px 1em; padding: 0 26px 0.6em; } h2.with-tabs { float: left; /* LTR */ margin: 0 2em 0 0; /* LTR */ padding: 0; } ul.primary li a, ul.primary li.active a, ul.primary li a:hover, ul.primary li a:visited, ul.secondary li a, ul.secondary li.active a, ul.secondary li a:hover, ul.secondary li a:visited { border: 0; background: transparent; padding: 4px 1em; margin: 0 0 0 1px; /* LTR */ height: auto; text-decoration: none; position: relative; top: -1px; display: inline-block; } ul.primary li.active a, ul.primary li.active a:link, ul.primary li.active a:visited, ul.primary li a:hover, ul.secondary li.active a, ul.secondary li.active a:link, ul.secondary li.active a:visited, ul.secondary li a:hover { background: url(images/bg-tab.png) repeat-x 0 50%; color: #fff; } ul.primary li.active a, ul.secondary li.active a { font-weight: bold; } /** * Nodes & comments */ .node { border-bottom: 1px solid #e9eff3; margin: 0 -26px 1.5em; padding: 1.5em 26px; } ul.links li, ul.inline li { margin-left: 0; margin-right: 0; padding-left: 0; /* LTR */ padding-right: 1em; /* LTR */ background-image: none; } .node .links, .comment .links { text-align: left; /* LTR */ } .node .links ul.links li, .comment .links ul.links li {} .terms ul.links li { margin-left: 0; margin-right: 0; padding-right: 0; padding-left: 1em; } .picture, .comment .submitted { float: right; /* LTR */ clear: right; /* LTR */ padding-left: 1em; /* LTR */ } .new { color: #ffae00; font-size: 0.92em; font-weight: bold; float: right; /* LTR */ } .terms { float: right; /* LTR */ } .preview .node, .preview .comment, .sticky { margin: 0; padding: 0.5em 0; border: 0; background: 0; } .sticky { padding: 1em; background-color: #fff; border: 1px solid #e0e5fb; margin-bottom: 2em; } #comments { position: relative; top: -1px; border-bottom: 1px solid #e9eff3; margin: -1.5em -25px 0; padding: 0 25px; } #comments h2.comments { margin: 0 -25px; padding: .5em 25px; background: #fff url(images/gradient-inner.png) repeat-x 0 0; } .comment { margin: 0 -25px; padding: 1.5em 25px 1.5em; border-top: 1px solid #e9eff3; } .indented { margin-left: 25px; /* LTR */ } .comment h3 a.active { color: #494949; } .node .content, .comment .content { margin: 0.6em 0; } /** * Aggregator.module */ #aggregator { margin-top: 1em; } #aggregator .feed-item-title { font-size: 160%; line-height: 130%; } #aggregator .feed-item { border-bottom: 1px solid #e9eff3; margin: -1.5em -31px 1.75em; padding: 1.5em 31px; } #aggregator .feed-item-categories { font-size: 0.92em; } #aggregator .feed-item-meta { font-size: 0.92em; color: #898989; } /** * Color.module */ #palette .form-item { border: 1px solid #fff; } #palette .item-selected { background: #fff url(images/gradient-inner.png) repeat-x 0 0; border: 1px solid #d9eaf5; } /** * Menu.module */ tr.menu-disabled { opacity: 0.5; } tr.odd td.menu-disabled { background-color: #edf5fa; } tr.even td.menu-disabled { background-color: #fff; } /** * Poll.module */ .poll .bar { background: #fff url(images/bg-bar-white.png) repeat-x 0 0; border: solid #f0f0f0; border-width: 0 1px 1px; } .poll .bar .foreground { background: #71a7cc url(images/bg-bar.png) repeat-x 0 100%; } .poll .percent { font-size: .9em; } /** * Autocomplete. */ #autocomplete li { cursor: default; padding: 2px; margin: 0; } /** * Collapsible fieldsets */ fieldset { margin: 1em 0; padding: 1em; border: 1px solid #d9eaf5; background: #fff url(images/gradient-inner.png) repeat-x 0 0; } /* Targets IE 7. Fixes background image in field sets. */ *:first-child+html fieldset { padding: 0 1em 1em; background-position: 0 .75em; background-color: transparent; } *:first-child+html fieldset > .description, *:first-child+html fieldset .fieldset-wrapper .description { padding-top: 1em; } fieldset legend { /* Fix disappearing legend in FFox */ display: block; } *:first-child+html fieldset legend, *:first-child+html fieldset.collapsed legend { display: inline; } html.js fieldset.collapsed { background: transparent; padding-top: 0; padding-bottom: .6em; } html.js fieldset.collapsible legend a { padding-left: 2em; /* LTR */ background: url(images/menu-expanded.gif) no-repeat 0% 50%; /* LTR */ } html.js fieldset.collapsed legend a { background: url(images/menu-collapsed.gif) no-repeat 0% 50%; /* LTR */ } /** * Syndication icons and block */ #block-node-0 h2 { float: left; /* LTR */ padding-right: 20px; /* LTR */ } #block-node-0 img, .feed-icon { float: right; /* LTR */ padding-top: 4px; } #block-node-0 .content { clear: right; /* LTR */ } /** * Login Block */ #user-login-form { text-align: center; } #user-login-form ul { text-align: left; /* LTR */ } /** * User profiles. */ .profile { margin-top: 1.5em; } .profile h3 { border-bottom: 0; margin-bottom: 1em; } .profile dl { margin: 0; } .profile dt { font-weight: normal; color: #898989; font-size: 0.92em; line-height: 1.3em; margin-top: 1.4em; margin-bottom: 0.45em; } .profile dd { margin-bottom: 1.6em; } /** * Admin Styles */ div.admin-panel, div.admin-panel .description, div.admin-panel .body, div.admin, div.admin .left, div.admin .right, div.admin .expert-link, div.item-list, .menu { margin: 0; padding: 0; } div.admin .left { float: left; /* LTR */ width: 48%; } div.admin .right { float: right; /* LTR */ width: 48%; } div.admin-panel { background: #fff url(images/gradient-inner.png) repeat-x 0 0; padding: 1em 1em 1.5em; } div.admin-panel .description { margin-bottom: 1.5em; } div.admin-panel dl { margin: 0; } div.admin-panel dd { color: #898989; font-size: 0.92em; line-height: 1.3em; margin-top: -.2em; margin-bottom: .65em; } table.system-status-report th { border-color: #d3e7f4; } #autocomplete li.selected, tr.selected td, tr.selected td.active { background: #027ac6; color: #fff; } tr.selected td a:link, tr.selected td a:visited, tr.selected td a:active { color: #d3e7f4; } tr.taxonomy-term-preview { opacity: 0.5; } tr.taxonomy-term-divider-top { border-bottom: none; } tr.taxonomy-term-divider-bottom { border-top: 1px dotted #CCC; } /** * CSS support */ /******************************************************************* * Color Module: Don't touch * *******************************************************************/ /** * Generic elements. */ .messages { background-color: #fff; border: 1px solid #b8d3e5; } .preview { background-color: #fcfce8; border: 1px solid #e5e58f; } div.status { color: #33a333; border-color: #c7f2c8; } div.error, tr.error { color: #a30000; background-color: #FFCCCC; } .form-item input.error, .form-item textarea.error { border: 1px solid #c52020; color: #363636; } /** * dblog.module */ tr.dblog-user { background-color: #fcf9e5; } tr.dblog-user td.active { background-color: #fbf5cf; } tr.dblog-content { background-color: #fefefe; } tr.dblog-content td.active { background-color: #f5f5f5; } tr.dblog-warning { background-color: #fdf5e6; } tr.dblog-warning td.active { background-color: #fdf2de; } tr.dblog-error { background-color: #fbe4e4; } tr.dblog-error td.active { background-color: #fbdbdb; } tr.dblog-page-not-found, tr.dblog-access-denied { background: #d7ffd7; } tr.dblog-page-not-found td.active, tr.dblog-access-denied td.active { background: #c7eec7; } /** * Status report colors. */ table.system-status-report tr.error, table.system-status-report tr.error th { background-color: #fcc; border-color: #ebb; color: #200; } table.system-status-report tr.warning, table.system-status-report tr.warning th { background-color: #ffd; border-color: #eeb; } table.system-status-report tr.ok, table.system-status-report tr.ok th { background-color: #dfd; border-color: #beb; } /* footer part*/ .footerMain{ background:#000 url(images/footer.png) repeat-x 0 0; height:159px; width:100%; float:left; } .footer{ width:885px; margin:0 auto; color:#FFF; padding-top:30px; letter-spacing:1px; } .footerCopyright{ width:885px; clear:both; padding-top:10px; } .footerLogo{ width:197px; background: url(images/qualcomm.png) no-repeat top left; height:49px; float:left; } .footerLink{ color: #FFFFFF; float: left; height: auto; padding: 10px 0 0 35px; width: 610px; } .footerLink span{ margin:0 5px; color:#666; } .footerLink a{ text-decoration:none; color:#FFF; text-transform:uppercase; font-weight:normal; } .footerLink a:hover{ text-decoration:none; color:#09C; }
Java
/* Copyright (C) 2014 InfiniDB, Inc. 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; version 2 of the License. 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. */ /***************************************************************************** * $Id: sessionmanagerserver.cpp 1906 2013-06-14 19:15:32Z rdempsey $ * ****************************************************************************/ /* * This class issues Transaction ID and keeps track of the current version ID */ #include <sys/types.h> #include <sys/stat.h> #include <cerrno> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <string> #include <stdexcept> #include <limits> #ifdef _MSC_VER #include <io.h> #include <psapi.h> #endif using namespace std; #include <boost/thread/mutex.hpp> #include <boost/scoped_ptr.hpp> using namespace boost; #include "brmtypes.h" #include "calpontsystemcatalog.h" using namespace execplan; #include "configcpp.h" #include "atomicops.h" #define SESSIONMANAGERSERVER_DLLEXPORT #include "sessionmanagerserver.h" #undef SESSIONMANAGERSERVER_DLLEXPORT #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_DIRECT #define O_DIRECT 0 #endif #ifndef O_LARGEFILE #define O_LARGEFILE 0 #endif #ifndef O_NOATIME #define O_NOATIME 0 #endif #include "IDBDataFile.h" #include "IDBPolicy.h" using namespace idbdatafile; namespace BRM { const uint32_t SessionManagerServer::SS_READY = 1 << 0; // Set by dmlProc one time when dmlProc is ready const uint32_t SessionManagerServer::SS_SUSPENDED = 1 << 1; // Set by console when the system has been suspended by user. const uint32_t SessionManagerServer::SS_SUSPEND_PENDING = 1 << 2; // Set by console when user wants to suspend, but writing is occuring. const uint32_t SessionManagerServer::SS_SHUTDOWN_PENDING = 1 << 3; // Set by console when user wants to shutdown, but writing is occuring. const uint32_t SessionManagerServer::SS_ROLLBACK = 1 << 4; // In combination with a PENDING flag, force a rollback as soom as possible. const uint32_t SessionManagerServer::SS_FORCE = 1 << 5; // In combination with a PENDING flag, force a shutdown without rollback. const uint32_t SessionManagerServer::SS_QUERY_READY = 1 << 6; // Set by ProcManager when system is ready for queries SessionManagerServer::SessionManagerServer() : unique32(0), unique64(0) { config::Config* conf; string stmp; const char* ctmp; conf = config::Config::makeConfig(); try { stmp = conf->getConfig("SessionManager", "MaxConcurrentTransactions"); } catch (const std::exception& e) { cout << e.what() << endl; stmp.clear(); } if (stmp != "") { int64_t tmp; ctmp = stmp.c_str(); tmp = config::Config::fromText(ctmp); if (tmp < 1) maxTxns = 1; else maxTxns = static_cast<int>(tmp); } else maxTxns = 1; txnidFilename = conf->getConfig("SessionManager", "TxnIDFile"); semValue = maxTxns; _verID = 0; _sysCatVerID = 0; systemState = 0; try { loadState(); } catch (...) { // first-time run most likely, ignore the error } } SessionManagerServer::~SessionManagerServer() { } void SessionManagerServer::reset() { mutex.try_lock(); semValue = maxTxns; condvar.notify_all(); activeTxns.clear(); mutex.unlock(); } void SessionManagerServer::loadState() { int lastTxnID; int err; int lastSysCatVerId; again: // There are now 3 pieces of info stored in the txnidfd file: last // transaction id, last system catalog version id, and the // system state flags. All these values are stored in shared, an // instance of struct Overlay. // If we fail to read a full four bytes for any value, then the // value isn't in the file, and we start with the default. if (IDBPolicy::exists(txnidFilename.c_str())) { scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open( IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "rb", 0)); if (!txnidfp) { perror("SessionManagerServer(): open"); throw runtime_error("SessionManagerServer: Could not open the transaction ID file"); } // Last transaction id txnidfp->seek(0, SEEK_SET); err = txnidfp->read(&lastTxnID, 4); if (err < 0 && errno != EINTR) { perror("Sessionmanager::initSegment(): read"); throw runtime_error("SessionManagerServer: read failed, aborting"); } else if (err < 0) goto again; else if (err == sizeof(int)) _verID = lastTxnID; // last system catalog version id err = txnidfp->read(&lastSysCatVerId, 4); if (err < 0 && errno != EINTR) { perror("Sessionmanager::initSegment(): read"); throw runtime_error("SessionManagerServer: read failed, aborting"); } else if (err < 0) goto again; else if (err == sizeof(int)) _sysCatVerID = lastSysCatVerId; // System state. Contains flags regarding the suspend state of the system. err = txnidfp->read(&systemState, 4); if (err < 0 && errno == EINTR) { goto again; } else if (err == sizeof(int)) { // Turn off the pending and force flags. They make no sense for a clean start. // Turn off the ready flag. DMLProc will set it back on when // initialized. systemState &= ~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_ROLLBACK | SS_FORCE); } else { // else no problem. System state wasn't saved. Might be an upgraded system. systemState = 0; } } } /* Save the systemState flags of the Overlay * segment. This is saved in the third * word of txnid File */ void SessionManagerServer::saveSystemState() { saveSMTxnIDAndState(); } const QueryContext SessionManagerServer::verID() { QueryContext ret; boost::mutex::scoped_lock lk(mutex); ret.currentScn = _verID; for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i) ret.currentTxns->push_back(i->second); return ret; } const QueryContext SessionManagerServer::sysCatVerID() { QueryContext ret; boost::mutex::scoped_lock lk(mutex); ret.currentScn = _sysCatVerID; for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i) ret.currentTxns->push_back(i->second); return ret; } const TxnID SessionManagerServer::newTxnID(const SID session, bool block, bool isDDL) { TxnID ret; // ctor must set valid = false iterator it; boost::mutex::scoped_lock lk(mutex); // if it already has a txn... it = activeTxns.find(session); if (it != activeTxns.end()) { ret.id = it->second; ret.valid = true; return ret; } if (!block && semValue == 0) return ret; else while (semValue == 0) condvar.wait(lk); semValue--; idbassert(semValue <= (uint32_t)maxTxns); ret.id = ++_verID; ret.valid = true; activeTxns[session] = ret.id; if (isDDL) ++_sysCatVerID; saveSMTxnIDAndState(); return ret; } void SessionManagerServer::finishTransaction(TxnID& txn) { iterator it; boost::mutex::scoped_lock lk(mutex); bool found = false; if (!txn.valid) throw invalid_argument("SessionManagerServer::finishTransaction(): transaction is invalid"); for (it = activeTxns.begin(); it != activeTxns.end();) { if (it->second == txn.id) { activeTxns.erase(it++); txn.valid = false; found = true; // we could probably break at this point, but there won't be that many active txns, and, // even though it'd be an error to have multiple entries for the same txn, we might // well just get rid of them... } else ++it; } if (found) { semValue++; idbassert(semValue <= (uint32_t)maxTxns); condvar.notify_one(); } else throw invalid_argument("SessionManagerServer::finishTransaction(): transaction doesn't exist"); } const TxnID SessionManagerServer::getTxnID(const SID session) { TxnID ret; iterator it; boost::mutex::scoped_lock lk(mutex); it = activeTxns.find(session); if (it != activeTxns.end()) { ret.id = it->second; ret.valid = true; } return ret; } shared_array<SIDTIDEntry> SessionManagerServer::SIDTIDMap(int& len) { int j; shared_array<SIDTIDEntry> ret; boost::mutex::scoped_lock lk(mutex); iterator it; ret.reset(new SIDTIDEntry[activeTxns.size()]); len = activeTxns.size(); for (it = activeTxns.begin(), j = 0; it != activeTxns.end(); ++it, ++j) { ret[j].sessionid = it->first; ret[j].txnid.id = it->second; ret[j].txnid.valid = true; } return ret; } void SessionManagerServer::setSystemState(uint32_t state) { boost::mutex::scoped_lock lk(mutex); systemState |= state; saveSystemState(); } void SessionManagerServer::clearSystemState(uint32_t state) { boost::mutex::scoped_lock lk(mutex); systemState &= ~state; saveSystemState(); } uint32_t SessionManagerServer::getTxnCount() { boost::mutex::scoped_lock lk(mutex); return activeTxns.size(); } void SessionManagerServer::saveSMTxnIDAndState() { // caller holds the lock scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open( IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "wb", 0)); if (!txnidfp) { perror("SessionManagerServer(): open"); throw runtime_error("SessionManagerServer: Could not open the transaction ID file"); } int filedata[2]; filedata[0] = _verID; filedata[1] = _sysCatVerID; int err = txnidfp->write(filedata, 8); if (err < 0) { perror("SessionManagerServer::newTxnID(): write(verid)"); throw runtime_error("SessionManagerServer::newTxnID(): write(verid) failed"); } uint32_t lSystemState = systemState; // We don't save the pending flags, the force flag or the ready flags. lSystemState &= ~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_FORCE); err = txnidfp->write(&lSystemState, sizeof(int)); if (err < 0) { perror("SessionManagerServer::saveSystemState(): write(systemState)"); throw runtime_error("SessionManagerServer::saveSystemState(): write(systemState) failed"); } txnidfp->flush(); } } // namespace BRM
Java
package org.adempiere.impexp.impl; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2015 metas GmbH * %% * 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 2 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.HashMap; import java.util.Map; import org.adempiere.exceptions.AdempiereException; import org.adempiere.impexp.BPartnerImportProcess; import org.adempiere.impexp.IImportProcess; import org.adempiere.impexp.IImportProcessFactory; import org.adempiere.impexp.ProductImportProcess; import org.adempiere.impexp.spi.IAsyncImportProcessBuilder; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.Check; import org.compiere.model.I_I_BPartner; import org.compiere.model.I_I_Product; import com.google.common.base.Supplier; public class ImportProcessFactory implements IImportProcessFactory { private final Map<Class<?>, Class<?>> modelImportClass2importProcessClasses = new HashMap<>(); private final Map<String, Class<?>> tableName2importProcessClasses = new HashMap<>(); private Supplier<IAsyncImportProcessBuilder> asyncImportProcessBuilderSupplier; public ImportProcessFactory() { // Register standard import processes registerImportProcess(I_I_BPartner.class, BPartnerImportProcess.class); registerImportProcess(I_I_Product.class, ProductImportProcess.class); } @Override public <ImportRecordType> void registerImportProcess(final Class<ImportRecordType> modelImportClass, final Class<? extends IImportProcess<ImportRecordType>> importProcessClass) { Check.assumeNotNull(modelImportClass, "modelImportClass not null"); Check.assumeNotNull(importProcessClass, "importProcessClass not null"); modelImportClass2importProcessClasses.put(modelImportClass, importProcessClass); final String tableName = InterfaceWrapperHelper.getTableName(modelImportClass); tableName2importProcessClasses.put(tableName, importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcess(final Class<ImportRecordType> modelImportClass) { final IImportProcess<ImportRecordType> importProcess = newImportProcessOrNull(modelImportClass); Check.assumeNotNull(importProcess, "importProcess not null for {}", modelImportClass); return importProcess; } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessOrNull(final Class<ImportRecordType> modelImportClass) { Check.assumeNotNull(modelImportClass, "modelImportClass not null"); final Class<?> importProcessClass = modelImportClass2importProcessClasses.get(modelImportClass); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass) { try { @SuppressWarnings("unchecked") final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance(); return importProcess; } catch (Exception e) { throw new AdempiereException("Failed instantiating " + importProcessClass, e); } } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableNameOrNull(final String tableName) { Check.assumeNotNull(tableName, "tableName not null"); final Class<?> importProcessClass = tableName2importProcessClasses.get(tableName); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableName(final String tableName) { final IImportProcess<ImportRecordType> importProcess = newImportProcessForTableNameOrNull(tableName); Check.assumeNotNull(importProcess, "importProcess not null for {}", tableName); return importProcess; } @Override public IAsyncImportProcessBuilder newAsyncImportProcessBuilder() { Check.assumeNotNull(asyncImportProcessBuilderSupplier, "A supplier for {} shall be registered first", IAsyncImportProcessBuilder.class); return asyncImportProcessBuilderSupplier.get(); } @Override public void setAsyncImportProcessBuilderSupplier(Supplier<IAsyncImportProcessBuilder> asyncImportProcessBuilderSupplier) { Check.assumeNotNull(asyncImportProcessBuilderSupplier, "asyncImportProcessBuilderSupplier not null"); this.asyncImportProcessBuilderSupplier = asyncImportProcessBuilderSupplier; } }
Java