code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/*************************************************************************** * Copyright (C) 2012 by David Edmundson <[email protected]> * * * * 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); } }
Ziemin/ktp-text-ui
logviewer/message-view.cpp
C++
gpl-2.0
9,205
<!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>
chrissalij/Wiki-Reputation-Predictor
weka/doc/weka/classifiers/functions/package-tree.html
HTML
gpl-2.0
14,287
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' ]}
ytsapras/robonet_site
scripts/rome_fields_dict.py
Python
gpl-2.0
1,964
<?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 = '[email protected], [email protected]'; $subject = 'New member requesting membership type.'; $body = 'New member ' . $username . ' ' . $fname . ' ' . $lname . ' ' . $email . ' requesting membership type of ' . $member_type . ''; $headers = "From: [email protected]\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: [email protected]\r\n"; $mailed = mail($to, $subject, $message, $headers); header("location: register-success.php"); exit(); } else { die("Query failed"); } ?>
Enjabain/My-NP
register-exec.php
PHP
gpl-2.0
3,724
<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>
TamasSzerb/zabbix
frontends/php/app/views/administration.mediatype.edit.js.php
PHP
gpl-2.0
2,993
/* 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. */ }
jaapweel/os134
loader.c
C
gpl-2.0
3,002
/************************************************** * 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>'); } }); } }); } }
airwaves-pl/WroclawskaMapaBarier
web/lib/js/wmb.comment.js
JavaScript
gpl-2.0
5,969
<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>
rahulrathore44/Park-and-Company
test-output/old/Default suite/methods-alphabetical.html
HTML
gpl-2.0
1,415
/*********************************************** * 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"); }
pappacurds/csi385-FAT12-OS
package/cd/cd.c
C
gpl-2.0
7,028
<?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', ));
vinny/share-on
language/el/shareon.php
PHP
gpl-2.0
1,990
<?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>
dspinellis/bib2xhtml
test.ok/named-n-c-UCR.html
HTML
gpl-2.0
8,467
# -*- 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
poderomedia/kfdata
kgrants/spiders/grants.py
Python
gpl-2.0
3,682
/* 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; }
barbareshet/achdut
style.css
CSS
gpl-2.0
6,962
/** * */ 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:[email protected]">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:[email protected]">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); } }
kaisenlean/rentavoz3
src/main/java/co/innovate/rentavoz/services/almacen/impl/CuotaServiceImpl.java
Java
gpl-2.0
2,414
;(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));
Great-Bee/NVWA-Client
js/bower_components/lodash/perf/perf.js
JavaScript
gpl-2.0
60,255
// // 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
MadArkitekt/SelfyApp
Selfy/SLFSettingsViewController.h
C
gpl-2.0
233
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
wes596/PHPIntermediate
README.md
Markdown
gpl-2.0
3,113
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, } }
hechenqingyuan/gitwms
Git.Storage.Common/EEquipmentStatus.cs
C#
gpl-2.0
794
--[[ @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
arne182/chdk-eyefi
CHDK/SCRIPTS/4Pack/Lua/motion.lua
Lua
gpl-2.0
1,005
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; }
boboulder101/My-game
Home.css
CSS
gpl-2.0
275
<?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(); ?>
Aks-1357/akhildhanuka-connectupmyhome
components/com_fss/views/admin/tmpl/moderate.php
PHP
gpl-2.0
1,553
/* * Copyright (C) 2010 Xavier Claessens <[email protected]> * 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; }
freedesktop-unofficial-mirror/telepathy__telepathy-ssh-contact
src/service.c
C
gpl-2.0
5,471
/* 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 */
w2pc/front_accounting
js/behaviour.js
JavaScript
gpl-2.0
8,278
/***************************************************************************** * macroblock.c: macroblock encoding ***************************************************************************** * Copyright (C) 2003-2017 x264 project * * Authors: Laurent Aimar <[email protected]> * Loren Merritt <[email protected]> * Fiona Glaser <[email protected]> * Henrik Gramner <[email protected]> * * 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 [email protected]. *****************************************************************************/ #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 ); }
kodabb/x264
encoder/macroblock.c
C
gpl-2.0
57,854
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; } }
longluo/DesignPatterns
src/oo/Prototype/SymbolLoader.java
Java
gpl-2.0
385
/* 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 */
holke/t8code
src/t8_cmesh_readmshfile.h
C
gpl-2.0
2,708
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(); } } }
doomdagger/CompetitionHub
src/main/java/com/djtu/signExam/util/Bootstrap.java
Java
gpl-2.0
625
/* 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, <[email protected]>. N32/64 ABI support added by Mark Mitchell, CodeSourcery, LLC. <[email protected]> Traditional MIPS targets support added by Koundinya.K, Dansk Data Elektronik & Operations Research Group. <[email protected]> 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; }
sribits/gdb
bfd/elfxx-mips.c
C
gpl-2.0
300,480
/* * 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
kammce/SJSU-DEV-Linux
firmware/default/lib/L2_Drivers/src/can.c
C
gpl-2.0
36,142
<?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; } ?>
thomasbodin/baltazare-test
wp-content/plugins/advanced-custom-fields-pro/api/api-helpers.php
PHP
gpl-2.0
54,778
<?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>
bjoernmainz/simple-contact-form
config/select_countries.xml.php
PHP
gpl-2.0
755
import { Query } from "../services"; export interface QueryState { queries?: Query[]; loading?: boolean; error?: String; visibilityFilter?: string; }
mickem/nscp
web/src/state/query.state.ts
TypeScript
gpl-2.0
161
<?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 [email protected] 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; } }
salem/aman
application/modules/news/services/Rss.php
PHP
gpl-2.0
4,158
/* * 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); }
Scorpio92/linux_kernel_3.16.1
fs/xfs/xfs_trans_ail.c
C
gpl-2.0
20,742
{- | 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
nevrenato/Hets_Fork
GMP/versioning/gmp-0.0.1/GMP/Main.hs
Haskell
gpl-2.0
3,633
<?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 } } }
igum/www.gamer31.ru
wp-admin/includes/class-wp-plugin-install-list-table.php
PHP
gpl-2.0
7,870
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"; } }
srubbiolo/SYSO
src/main/java/com/ues21/ferreteria/login/LoginController.java
Java
gpl-2.0
2,293
<?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 -->
ddksaku/twis
wp-content/themes/twis/sidebar-en.php
PHP
gpl-2.0
654
<?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); ?>
webtsys/phango2
modules/users/models/models_users.php
PHP
gpl-2.0
1,137
<?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]; } } } }
havran/Drupal.sk
docroot/drupal/core/modules/migrate_drupal/src/Tests/MigrateFullDrupalTestBase.php
PHP
gpl-2.0
3,949
<?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.'); } }
vothequang113/Joomla
tests/suites/unit/joomla/filesystem/JPathTest.php
PHP
gpl-2.0
3,267
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; }
auchri/AOTP
css/basic.css
CSS
gpl-2.0
3,279
/* 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; } }
nextgens/fred
src/freenet/node/Node.java
Java
gpl-2.0
177,426
/* $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; }
ninthlink/m2m
sites/all/themes/m2madmin/style.css
CSS
gpl-2.0
20,973
/* 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
mariadb-corporation/mariadb-columnstore-engine
versioning/BRM/sessionmanagerserver.cpp
C++
gpl-2.0
10,706
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; } }
klst-com/metasfresh
de.metas.business/src/main/java/org/adempiere/impexp/impl/ImportProcessFactory.java
Java
gpl-2.0
5,016
#pragma once #include <MellowPlayer/Presentation/Notifications/ISystemTrayIcon.hpp> #include <QMenu> #include <QSystemTrayIcon> namespace MellowPlayer::Domain { class ILogger; class IPlayer; class Setting; class Settings; } class SystemTrayIconStrings : public QObject { Q_OBJECT public: QString playPause() const; QString next() const; QString previous() const; QString restoreWindow() const; QString quit() const; }; namespace MellowPlayer::Infrastructure { class IApplication; } namespace MellowPlayer::Presentation { class IMainWindow; class SystemTrayIcon : public QObject, public ISystemTrayIcon { Q_OBJECT public: SystemTrayIcon(Domain::IPlayer& player, IMainWindow& mainWindow, Domain::Settings& settings); void show() override; void hide() override; void showMessage(const QString& title, const QString& message) override; public slots: void onActivated(QSystemTrayIcon::ActivationReason reason); void togglePlayPause(); void next(); void previous(); void restoreWindow(); void quit(); private slots: void onShowTrayIconSettingValueChanged(); private: void setUpMenu(); Domain::ILogger& logger_; Domain::IPlayer& player_; IMainWindow& mainWindow_; Domain::Settings& settings_; Domain::Setting& showTrayIconSetting_; QSystemTrayIcon qSystemTrayIcon_; QMenu menu_; QAction* playPauseAction_; QAction* previousSongAction_; QAction* nextSongAction_; QAction* restoreWindowAction_; QAction* quitApplicationAction_; }; }
ColinDuquesnoy/MellowPlayer
src/lib/presentation/include/MellowPlayer/Presentation/Notifications/SystemTrayIcon.hpp
C++
gpl-2.0
1,712
/* * ecgen, tool for generating Elliptic curve domain parameters * Copyright (C) 2017-2018 J08nY */ #include "hex.h" #include "exhaustive/arg.h" #include "field.h" #include "util/bits.h" #include "util/memory.h" #include "util/str.h" static char *hex_point(point_t *point) { GEN fx = field_elementi(gel(point->point, 1)); GEN fy = field_elementi(gel(point->point, 2)); char *fxs = pari_sprintf("%P0#*x", cfg->hex_digits, fx); char *fxy = pari_sprintf("%P0#*x", cfg->hex_digits, fy); char *result = str_joinv(",", fxs, fxy, NULL); pari_free(fxs); pari_free(fxy); return result; } static char *hex_points(point_t *points[], size_t len) { char *p[len]; for (size_t i = 0; i < len; ++i) { point_t *pt = points[i]; p[i] = hex_point(pt); } size_t total = 1; for (size_t i = 0; i < len; ++i) { total += strlen(p[i]); } char *result = try_calloc(total); for (size_t i = 0; i < len; ++i) { strcat(result, p[i]); try_free(p[i]); } return result; } CHECK(hex_check_param) { HAS_ARG(args); char *search_hex = try_strdup(args->args); char *p = search_hex; for (; *p; ++p) *p = (char)tolower(*p); char *params[OFFSET_END] = {NULL}; bool pari[OFFSET_END] = {false}; if (state >= OFFSET_SEED) { if (curve->seed && curve->seed->seed) { params[OFFSET_SEED] = bits_to_hex(curve->seed->seed); } } if (state >= OFFSET_FIELD) { if (cfg->field == FIELD_PRIME) { params[OFFSET_FIELD] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->field); pari[OFFSET_FIELD] = true; } else if (cfg->field == FIELD_BINARY) { } } if (state >= OFFSET_A) { params[OFFSET_A] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->a)); pari[OFFSET_A] = true; } if (state >= OFFSET_B) { params[OFFSET_B] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->b)); pari[OFFSET_B] = true; } if (state >= OFFSET_ORDER) { params[OFFSET_ORDER] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->order); pari[OFFSET_ORDER] = true; } if (state >= OFFSET_GENERATORS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_point(curve->generators[i]->generator); } params[OFFSET_GENERATORS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } if (state >= OFFSET_POINTS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_points(curve->generators[i]->points, curve->generators[i]->npoints); } params[OFFSET_POINTS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } int result = OFFSET_FIELD - state; for (offset_e i = OFFSET_SEED; i < OFFSET_END; ++i) { if (params[i]) { if (result != 1 && strstr(params[i], search_hex)) { result = 1; } if (pari[i]) { pari_free(params[i]); } else { try_free(params[i]); } } } try_free(search_hex); return result; }
J08nY/ecgen
src/gen/hex.c
C
gpl-2.0
3,044
package irc.bot; import java.io.*; public class OutHandler implements Runnable { OutHandler(Connection connection) { this.connection = connection; } private Connection connection; public void run() {} }
propheh/IRCBot
irc/bot/OutHandler.java
Java
gpl-2.0
225
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.ellcs.stack.android; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class string { public static final int app_name=0x7f030000; } public static final class style { public static final int GdxTheme=0x7f040000; } }
ellcs/point
android/build/generated/source/r/debug/com/ellcs/stack/android/R.java
Java
gpl-2.0
582
PageProcessor::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 # config.middleware.insert 0, "Rack::WWWhisper" end
ttfnrob/wd3
config/environments/production.rb
Ruby
gpl-2.0
2,540
This is a first attempt at constructing a Django wrapper around playing_god
joshsmith2/playing_django
README.md
Markdown
gpl-2.0
76
<?php function edd_rp_settings( $settings ) { $suggested_download_settings = array( array( 'id' => 'edd_rp_header', 'name' => '<strong>' . __('Recommended Products', 'edd-rp-txt') . '</strong>', 'desc' => '', 'type' => 'header', 'size' => 'regular' ), array( 'id' => 'edd_rp_display_single', 'name' => __('Show on Downloads', 'edd-rp-txt'), 'desc' => __('Display the recommended products on the download post type', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'edd_rp_display_checkout', 'name' => __('Show on Checkout', 'edd-rp-txt'), 'desc' => __('Display the recommended products after the Checkout Cart, and before the Checkout Form', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'edd_rp_suggestion_count', 'name' => __('Number of Recommendations', 'edd-rp-txt'), 'desc' => __('How many recommendations should be shown to users', 'edd-rp-txt'), 'type' => 'select', 'options' => edd_rp_suggestion_count() ), array( 'id' => 'edd_rp_show_free', 'name' => __('Show Free Products', 'edd-rp-txt'), 'desc' => __('Allows free products to be shown in the recommendations. (Requires Refresh of Recommendations after save)', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'rp_settings_additional', 'name' => '', 'desc' => '', 'type' => 'hook' ) ); return array_merge( $settings, $suggested_download_settings ); } add_filter( 'edd_settings_extensions', 'edd_rp_settings' ); function edd_rp_suggestion_count() { for ( $i = 1; $i <= 5; $i++ ) { $count[$i] = $i; } $count[3] = __( '3 - Default', 'edd-rp-txt' ); return apply_filters( 'edd_rp_suggestion_counts', $count ); } function edd_rp_recalc_suggestions_button() { echo '<a href="' . wp_nonce_url( add_query_arg( array( 'edd_action' => 'refresh_edd_rp' ) ), 'edd-rp-recalculate' ) . '" class="button-secondary">' . __( 'Refresh Recommendations', 'edd-rp-txt' ) . '</a>'; } add_action( 'edd_rp_settings_additional', 'edd_rp_recalc_suggestions_button' ); function refresh_edd_rp( $data ) { if ( ! wp_verify_nonce( $data['_wpnonce'], 'edd-rp-recalculate' ) ) { return; } // Refresh Suggestions edd_rp_generate_stats(); add_action( 'admin_notices', 'edd_rp_recalc_notice' ); } add_action( 'edd_refresh_edd_rp', 'refresh_edd_rp' ); function edd_rp_recalc_notice() { printf( '<div class="updated settings-error"> <p> %s </p> </div>', esc_html__( 'Recommendations Updated.', 'edd-rp-txt' ) ); }
SelaInc/eassignment
wp-content/plugins/edd-recommended-products/includes/settings.php
PHP
gpl-2.0
2,572
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest06598") public class BenchmarkTest06598 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("foo"); java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value try { java.util.Properties Benchmarkprops = new java.util.Properties(); Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties")); String algorithm = Benchmarkprops.getProperty("cryptoAlg2", "AES/ECB/PKCS5Padding"); javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed"); } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest06598.java
Java
gpl-2.0
2,819
define(function(require) { var Model = require("web/common/model"); var SpsrModel = Model.extend({ idAttribute: "recordId", defaults: { name: "SDI1", kzck: 0, ydsd: 0, srjkxh: 0, ld: 123, dbd: 124, bhd: 125, sppy: 126, czpy: 127 }, urls: { "create": "spsr.psp", "update": "spsr.psp", "delete": "spsr.psp", "read": "spsr.psp" } }); return SpsrModel; });
huang147300/EDSFrontEnd
js/index/pz/spsr/spsr_model.js
JavaScript
gpl-2.0
413
/** * Copyright (c) 2008-2012 Indivica Inc. * * This software is made available under the terms of the * GNU General Public License, Version 2, 1991 (GPLv2). * License details are available via "indivica.ca/gplv2" * and "gnu.org/licenses/gpl-2.0.html". */ package org.oscarehr.document.web; import java.io.File; import java.io.FileInputStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.oscarehr.common.dao.CtlDocumentDao; import org.oscarehr.common.dao.DocumentDao; import org.oscarehr.common.dao.PatientLabRoutingDao; import org.oscarehr.common.dao.ProviderInboxRoutingDao; import org.oscarehr.common.dao.ProviderLabRoutingDao; import org.oscarehr.common.dao.QueueDocumentLinkDao; import org.oscarehr.common.model.CtlDocument; import org.oscarehr.common.model.CtlDocumentPK; import org.oscarehr.common.model.Document; import org.oscarehr.common.model.PatientLabRouting; import org.oscarehr.common.model.ProviderInboxItem; import org.oscarehr.common.model.ProviderLabRoutingModel; import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.SpringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import oscar.dms.EDoc; import oscar.dms.EDocUtil; import oscar.oscarLab.ca.all.upload.ProviderLabRouting; public class SplitDocumentAction extends DispatchAction { private DocumentDao documentDao = SpringUtils.getBean(DocumentDao.class); public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String docNum = request.getParameter("document"); String[] commands = request.getParameterValues("page[]"); Document doc = documentDao.getDocument(docNum); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); new File(docdownload); String newFilename = doc.getDocfilename(); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); PDDocument newPdf = new PDDocument(); List pages = pdf.getDocumentCatalog().getAllPages(); if (commands != null) { for (String c : commands) { String[] command = c.split(","); int pageNum = Integer.parseInt(command[0]); int rotation = Integer.parseInt(command[1]); PDPage p = (PDPage)pages.get(pageNum-1); p.setRotation(rotation); newPdf.addPage(p); } } //newPdf.save(docdownload + newFilename); if (newPdf.getNumberOfPages() > 0) { LoggedInInfo loggedInInfo=LoggedInInfo.loggedInInfo.get(); EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0); newDoc.setDocPublic("0"); newDoc.setContentType("application/pdf"); newDoc.setNumberOfPages(newPdf.getNumberOfPages()); String newDocNo = EDocUtil.addDocumentSQL(newDoc); newPdf.save(docdownload + newDoc.getFileName()); newPdf.close(); WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx.getBean("providerInboxRoutingDAO"); providerInboxRoutingDao.addToProviderInbox("0", Integer.parseInt(newDocNo), "DOC"); List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC", Integer.parseInt(docNum)); for (ProviderInboxItem i : routeList) { providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), Integer.parseInt(newDocNo), "DOC"); } providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), Integer.parseInt(newDocNo), "DOC"); QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO"); Integer qid = 1; Integer did= Integer.parseInt(newDocNo.trim()); queueDocumentLinkDAO.addToQueueDocumentLink(qid,did); ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils.getBean("providerLabRoutingDao"); List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(Integer.parseInt(docNum)); if (!result.isEmpty()) { new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(),"DOC"); } PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils.getBean("patientLabRoutingDao"); List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(Integer.parseInt(docNum)); if (!result2.isEmpty()) { PatientLabRouting newPatientRoute = new PatientLabRouting(); newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo()); newPatientRoute.setLabNo(Integer.parseInt(newDocNo)); newPatientRoute.setLabType("DOC"); patientLabRoutingDao.persist(newPatientRoute); } CtlDocumentDao ctlDocumentDao = SpringUtils.getBean(CtlDocumentDao.class); CtlDocument result3 = ctlDocumentDao.getCtrlDocument(Integer.parseInt(docNum)); if (result3!=null) { CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic"); CtlDocument newCtlDocument = new CtlDocument(); newCtlDocument.setId(ctlDocumentPK); newCtlDocument.getId().setModuleId(result3.getId().getModuleId()); newCtlDocument.setStatus(result3.getStatus()); documentDao.persist(newCtlDocument); } } pdf.close(); input.close(); return mapping.findForward("success"); } public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage)p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r+180)%360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage)p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r+90)%360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } public ActionForward removeFirstPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); // Documents must have at least 2 pages, for the first page to be removed. if (pdf.getNumberOfPages() <= 1) { return null; } int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.removePage(0); EDocUtil.subtractOnePage(request.getParameter("document")); pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } }
hexbinary/landing
src/main/java/org/oscarehr/document/web/SplitDocumentAction.java
Java
gpl-2.0
8,755
<?php if (!defined('TFUSE')) exit('Direct access forbidden.'); /** * Class UPDATER. Check for new versions of the theme, framework, or modules. Installs if found. */ class TF_UPDATER extends TF_TFUSE { public $_the_class_name = 'UPDATER'; public $themefuse_update = false; public $check_url; #http://themefuse.com/update-themes/ public function __construct() { parent::__construct(); //$this->check_url = 'http://' . $_SERVER['HTTP_HOST'] . '/wp-updater/'; $this->check_url = 'http://themefuse.com/update-themes/'; } public function __init() { $this->themefuse_update = $this->themefuse_update_check(); if (get_option(TF_THEME_PREFIX . '_disable_updates') != 1) { add_action('admin_menu', array($this, 'updates_item_menu_page'), 20); if ($this->themefuse_update) { add_action('admin_notices', array($this, 'themefuse_update_nag')); } } } function updates_item_menu_page() { if (!empty($this->themefuse_update->response[TF_THEME_PREFIX])) $count = count($this->themefuse_update->response[TF_THEME_PREFIX]); $title = !empty($count) ? __('Updates', 'tfuse') . '<span class="update-plugins count-' . $count . '"><span class="update-count">' . number_format_i18n($count) . '</span></span>' : __('Updates', 'tfuse'); add_submenu_page('themefuse', __('Updates', 'tfuse'), $title, 'manage_options', 'tfupdates', array($this, 'themefuse_update_page')); } /** * This function pings an http://themefuse.com/ asking if a new * version of this theme is available. If not, it returns FALSE. * If so, the external server passes serialized data back to this * function, which gets unserialized and returned for use. * * @since 2.0 */ function themefuse_update_check() { if (!current_user_can('update_themes')) return false; if (!$this->request->empty_GET('action') && $this->request->GET('action') == 'checkagain') { delete_site_transient('themefuse-update'); wp_redirect(self_admin_url('admin.php?page=tfupdates')); } $themefuse_update = get_site_transient('themefuse-update'); if (!$themefuse_update) { $url = $this->check_url; $options = array( 'body' => $this->update_params() ); $request = wp_remote_post($url, $options); $response = wp_remote_retrieve_body($request); $themefuse_update = new stdClass(); $themefuse_update->last_checked = time(); // If an error occurred, return FALSE, store for 1 hour if ($response == 'error' || is_wp_error($response) || !is_serialized($response)) { $themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] = $this->theme->framework_version; $themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] = $this->theme->mods_version; $themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] = $this->theme->theme_version; set_site_transient('themefuse-update', $themefuse_update, 60 * 60); // store for 1 hour return false; } // Else, unserialize $themefuse_update->response[TF_THEME_PREFIX] = maybe_unserialize($response); // And store in transient set_site_transient('themefuse-update', $themefuse_update, 60 * 60 * 24); // store for 24 hours } if (!(@$themefuse_update->response[TF_THEME_PREFIX])) { // If response is empty return false; } else if (!empty($themefuse_update->response[TF_THEME_PREFIX]['suspended'])) { // Verify if updates for this theme are not suspended from themefuse return false; } else if ( version_compare( $this->theme->framework_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Framework']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->mods_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']) ? @$themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->theme_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Templates']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] : '0' ), '>=' ) ) { // If we're already using the latest version, return FALSE return false; } return $themefuse_update; } function update_params() { global $wp_version, $wpdb; $params = array( 'theme_name' => $this->theme->theme_name, 'prefix' => $this->theme->prefix, 'framework_version' => $this->theme->framework_version, 'mods_version' => $this->theme->mods_version, 'theme_version' => $this->theme->theme_version, 'wp_version' => $wp_version, 'php_version' => phpversion(), 'mysql_version' => $wpdb->db_version(), 'uri' => home_url(), 'locale' => get_locale(), 'is_multi' => is_multisite(), 'is_child' => is_child_theme() ); return apply_filters('tf_update_param', $params); } /** * This function displays the update nag at the top of the * dashboard if there is an ThemeFuse update available. * * @since 2.0 */ function themefuse_update_nag() { global $upgrading; if (!$this->request->empty_GET('page') && $this->request->GET('page') == 'tfupdates') return; echo apply_filters('tf_update_nag_notice', $this->load->view('updater/update_nag', NULL, true) ); } function themefuse_update_page() { if ('tf-do-upgrade' == $this->theme->action || 'tf-do-reinstall' == $this->theme->action || ($this->request->isset_POST('upgrade') && $this->request->POST('upgrade') == __('Proceed', 'tfuse'))) { check_admin_referer('themefuse-bulk-update'); $updates = !empty($this->themefuse_update->response[TF_THEME_PREFIX]) ? array_keys($this->themefuse_update->response[TF_THEME_PREFIX]) : array(); $updates = array_map('urldecode', $updates); $this->load->view('updater/update_page'); if ($this->request->isset_POST('connection_type') && $this->request->POST('connection_type') == 'ftp') { $filesystem = WP_Filesystem($this->request->POST()); } $this->do_core_upgrade($updates); } else { $this->themefuse_upgrade_preamble(); } } function themefuse_upgrade_preamble() { $updates = get_site_transient('themefuse-update'); $data = array( 'updates' => $updates ); if (isset($this->themefuse_update->response)) $data['response'] = $this->themefuse_update->response; $this->load->view('updater/upgrade_preamble', $data); } public function do_core_upgrade($updates) { $this->load->helper('UPGRADER'); $updates = array_map('urldecode', $updates); $url = 'admin.php?page=tfupdates&amp;updates=' . urlencode(implode(',', $updates)); $nonce = 'themefuse-bulk-update'; //wp_enqueue_script('jquery'); //iframe_header(); $upgrader = new TF_Theme_Upgrader(new TF_Bulk_Theme_Upgrader_Skin(compact('nonce', 'url'))); $upgrader->bulk_upgrade($updates); //iframe_footer(); } }
reginas/callan-consulting
wp-content/themes/interakt-parent/framework/core/UPDATER.php
PHP
gpl-2.0
8,320
from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
maxiee/LearnPythonTheHardWayExercises
ex20.py
Python
gpl-2.0
601
<?php session_start(); $_SESSION["Status"]=0; include("dbconn.php"); require ('../xajax.inc.php'); include("../dbinfo.inc.php"); $memid=$_SESSION['userId']; $_SESSION["userid"]=$memid; function viewuseralbums($userid,$jumpto) {//list all the albums owned by the user $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 5; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query = "select * from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid' limit $start, $rowsPerPage"; $result=mysql_query($query)or die(mysql_error()); $count =mysql_numrows($result); $msg; if($count==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else{ //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$count;$S++) { $albumid =mysql_result($result,$S,"album.AlbumId"); $albumname= mysql_result($result,$S,"album.AlbumName"); //now display the album pic //1st get the image path of the pic // call a function Getpath2 $path = Getpath2($albumid); // now display the album //3 by 2 $msg.="<td>"; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"javascript:void(null);\"onclick = \"xajax_createAlbumView($albumid,''); \" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160> </a> </td > <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"td-shadows-bottomright\"> </td> </tr> <tr><td width = 50 class =\"mytext_account\">$albumname</td></tr> </table><!--end of table shadows--> </td>";//end of echo //if no if col = 5 then new row if(($S %5 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; //############## End of display stuff // how many rows we have in database $query="select COUNT(*) AS numrows from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid'"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); //#################################### // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_viewuseralbums($userid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"xajax_viewuseralbums($userid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"xajax_viewuseralbums($userid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_viewuseralbums($userid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.="<div class =\"mytext_account\">"; $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $msg.="</div>"; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function function Getpath2($albumid) { $query="SELECT images.Url FROM images,albumcontainsimages where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=$albumid"; $result=mysql_query($query); $num=mysql_numrows($result); //check $msg; if($num==0) $msg= "No Records founds"; else { $Url=mysql_result($result,$num-1,"images.Url"); $msg="../Images/".$Url; }//else return $msg; }//end of function function createAlbumView($albumid,$jumpto) { $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 15; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query="select * from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid limit $start, $rowsPerPage"; $result=mysql_query($query); $num=mysql_numrows($result); $msg; if($num==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else { //display Album Name $AlbumName= mysql_result($result,0,'album.AlbumName'); //display Creation Date $Date = mysql_result($result,0,'album.CreationDate'); //display description of album $des= mysql_result($result,0,'album.Description'); //display no of times viewed //call function GetViewed($albumid) //create a table to display album details first $msg="<table ><tr >";//end of echo $msg.= "<td class =\"td-thumbnails-navi\">Album Name :$AlbumName</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Created on :$Date</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Description :$des</td></tr>"; $msg.= "</table>"; //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$num;$S++) { //get path of image $path="../Images/"; $path .= mysql_result($result,$S,"images.Url"); //get des of image $imgdescription= mysql_result($result,$S,"images.Description"); //get dateuploaded of image $dateUploaded=mysql_result($result,$S,"images.DateUploaded"); //get name of image $ImgName=mysql_result($result,$S,"images.ImageName"); //get datecreated of image $imageId=mysql_result($result,$S,"images.ImageId"); $msg.="<td> "; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"ImageZoom.php?ImgId=$imageId\" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160 align=bottom alt=$ImgName> </a> </td> <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"td-shadows-bottomright\"> </td> </tr> </table><!--end of table shadows--> </td>";//end of echo //if no if col = 5 then new row if(($S %4 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; //############## End of display stuff // how many rows we have in database $query="select COUNT(*) AS numrows from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid "; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); //#################################### // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_createAlbumView($albumid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"xajax_createAlbumView($albumid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"xajax_createAlbumView($albumid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_createAlbumView($albumid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function //////////////////////////////// $xajax = new xajax(); $xajax->registerFunction("viewuseralbums"); $xajax->registerFunction("createAlbumView"); $xajax->processRequests(); ?> <html><head><?php $xajax->printJavascript("../"); ?><title>Select Album</title> <link href="../css/style.css" type="text/css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../icons/spgm_style.css" /> </head><body onload = "xajax_viewuseralbums(<?php echo $memid ; ?>,'');"> <!--Start of footer table--> <table id="wapper" border=0> <tr> <td id="topleft">&nbsp;</td> <td id="top">&nbsp;</td> <td id="topright">&nbsp;</td> </tr> <tr><td id="left"></td> <td id="logocenter"> <p><span id="title">&nbsp;Select Album</span></p> <div id = "mytable"></div> </td> <td id="right">&nbsp;</td> </tr> <tr> <td id="bottomleft">&nbsp;</td> <td id="bottom">&nbsp;</td> <td id="bottomright">&nbsp;</td> </tr> </table> <!--End of footer table--> <br> <?php ?> </body> </html>
avinash/nuzimazz
Image_edit/SelectAlbum.php
PHP
gpl-2.0
11,067
all: 484.out %.out: %.R R --no-save < $< > $@ clean: -rm *.out *.pdf *.png *~ *swp view: -open *.png
dankelley/oce-issues
04xx/484/Makefile
Makefile
gpl-2.0
104
package edu.ucsd.ncmir.WIB.client.core.components; import com.google.gwt.user.client.ui.Widget; import edu.ucsd.ncmir.WIB.client.core.message.Message; import edu.ucsd.ncmir.WIB.client.core.message.MessageListener; import edu.ucsd.ncmir.WIB.client.core.message.MessageManager; import edu.ucsd.ncmir.WIB.client.core.messages.ResetMessage; /** * HorizontalSlider bar. * @author spl */ public class HorizontalSlider extends SliderHorizontal implements HorizontalSliderInterface, MessageListener, SliderValueUpdateHandler { private final Message _message; /** * Creates a <code>HorizontalSlider</code> object. */ public HorizontalSlider( Message message ) { super( "150px" ); this._message = message; super.addSliderValueUpdateHandler( this ); MessageManager.registerListener( ResetMessage.class, this ); } private int _min_value = 0; private int _max_value = 1; private int _default_value = 0; @Override public final void setSliderParameters( int min_value, int max_value, int default_value ) { this._min_value = min_value; this._max_value = max_value; this._default_value = default_value; this.setMaxValue( this._max_value - this._min_value ); this.setSliderValue( default_value ); super.setMinMarkStep( 1 ); } @Override public void setWidth( String size ) { this._transmit_value = false; double value = super.getValue(); super.setWidth( size ); super.setValue( value ); this._transmit_value = true; } private boolean _transmit_value = true; /** * Updates the value of the slider without firing the handler. * @param value The value to be set. */ @Override public void setSliderValueOnly( int value ) { // Turn off the handler. this._transmit_value = false; this.setSliderValue( value ); this._transmit_value = true; } @Override public void setSliderValue( double value ) { super.setValue( value - this._min_value ); } @Override public void action( Message m, Object o ) { this.setSliderValue( this._default_value ); } private boolean _initial = true; // To prevent premature Message firing. /** * Fired when the bar value changes. * @param event The <code>BarValueChangedEvent</code>. */ @Override public void onBarValueChanged( SliderValueUpdateEvent event ) { if ( this._transmit_value && !this._initial ) this.updateHandler( event.getValue() + this._min_value ); // Turn off the initial flag. The SliderBar object fires a // spurious BarValueChangedEvent when the object is loaded. // This prevents it being propagated. this._initial = false; } @Override public void updateHandler( double value ) { this._message.send( value ); } @Override public Widget widget() { return this; } @Override public double getSliderValue() { return this.getValue(); } }
imclab/WebImageBrowser
WIB/src/java/edu/ucsd/ncmir/WIB/client/core/components/HorizontalSlider.java
Java
gpl-2.0
3,160
# datasciencecoursera This repository is created as a part of the data science class
alurepo/datasciencecoursera
README.md
Markdown
gpl-2.0
85
# The absolute path of the main script(p4_tools.rb) ROOT = File.expand_path('..', File.dirname(__FILE__)) # The absolute path of the folder which contains the command files COMMANDS_ROOT = ROOT + '/commands' # The absolute path of the folder which contains the custom command files CUSTOM_COMMANDS_ROOT = COMMANDS_ROOT + '/custom' # The absolute path of the folder which contains the configuration files CONFIG_ROOT = ROOT + '/config' # Array of command names, read from the COMMAND_ROOT folder SUB_COMMANDS = Dir[COMMANDS_ROOT + '/*.rb'].collect { |file| File.basename(file, '.rb') } $LOAD_PATH.unshift(CUSTOM_COMMANDS_ROOT, COMMANDS_ROOT)
ncsibra/P4Tools
lib/p4tools/environment.rb
Ruby
gpl-2.0
671
-- Thalorien Dawnseeker's Remains SET @ENTRY := 37552; UPDATE `creature_template` SET `faction`=1770 WHERE `entry`=@ENTRY; -- Phase DELETE FROM `spell_area` WHERE `spell`=70193; INSERT INTO `spell_area` (`spell`, `area`, `quest_start`, `quest_end`, `aura_spell`, `racemask`, `gender`, `autocast`, `quest_start_status`, `quest_end_status`) VALUES ('70193', '4075', '24535', '0', '0', '0', '2', '1', '8', '11'), ('70193', '4075', '24563', '0', '0', '0', '2', '1', '8', '11'); SET @CGUID := 600009; DELETE FROM `creature` WHERE `guid`=@CGUID;
Declipe/ElunaTrinityWotlk
sql/2016_03_01_NPC_THALORIEN_DAWNSEEKER_world.sql
SQL
gpl-2.0
546
# Lesson-1---Review ### Create a song class #### Attributes: 1. Title 2. Band members: a dictionary with name as the key and instrument as the values. 3. (Highest) place on the charts. #### Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the song from the file. 2. __str__ Output the attributes in a nice way 3. save Save a song to a file, the filepointer should be a parameter. ### Create an album class #### Attributes: 1. Title 2. Year 3. Producer 4. Songs - a list of songs each of which are of type class song. #### Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the album from the file. In both cases, when you input a song make sure to use the songs method for input. The song attribute should be an optional parameter. If the value is None keep inputting songs until the user is done. 2. __str__ Output the attributes of the album in a nice way. 3. save saves the entire album to a file, makes use of the song.save attribute for the songs. The filepointer is a parameter. ### Create a menu #### Options: 1. Input a new album 2. Print albums 3. Quit When your program is opened it should read in the albums into a list of albums from the file, and when the user quits it should write the albums in the list to a file. Option 1 should add a new album to the album list.
CSCI157/Lesson-1---Data-structures
README.md
Markdown
gpl-2.0
1,537
<?php include 'init.php'; $output = ''; $setup = new ON_Settings(); $setup->load(); $setup->registerForm('setup'); // fill form with elements $setup->fillForm(); // process forms if posted if ($setup->form->isSubmitted() && $setup->form->validate()) { $values =& $setup->form->exportValues(); $setup->setValues($values); if($setup->globalid > 0) { $res = $setup->update(); if ($res) { ON_Say::add(fmtSuccess(_('Settings updated successfuly'))); $defaults = $setup->defaults(); $setup->form->resetDefaults($defaults); } else { ON_Say::add(fmtError(_('Database error: settings update failed'))); } } else { $res = $setup->insert(); if ($res) { ON_Say::add(fmtSuccess(_('Settings inserted successfuly'))); } else { ON_Say::add(fmtError(_('Database error: settings insert failed'))); } } } $output .= $setup->form->toHtml(); include 'theme.php'; ?>
uzaytek/orion
admin/settings-store.php
PHP
gpl-2.0
935
# Find Python # ~~~~~~~~~~~ # Find the Python interpreter and related Python directories. # # This file defines the following variables: # # PYTHON_EXECUTABLE - The path and filename of the Python interpreter. # # PYTHON_SHORT_VERSION - The version of the Python interpreter found, # excluding the patch version number. (e.g. 2.5 and not 2.5.1)) # # PYTHON_LONG_VERSION - The version of the Python interpreter found as a human # readable string. # # PYTHON_SITE_PACKAGES_DIR - Location of the Python site-packages directory. # # PYTHON_INCLUDE_PATH - Directory holding the python.h include file. # # PYTHON_LIBRARY, PYTHON_LIBRARIES- Location of the Python library. # Copyright (c) 2007, Simon Edwards <[email protected]> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. INCLUDE(CMakeFindFrameworks) if(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}") # Already in cache, be silent set(PYTHONLIBRARY_FOUND TRUE) else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}") set(_custom_python_fw FALSE) if(APPLE AND PYTHON_CUSTOM_FRAMEWORK) if("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") STRING(REGEX REPLACE "(.*Python\\.framework).*$" "\\1" _python_fw "${PYTHON_CUSTOM_FRAMEWORK}") set(PYTHON_EXECUTABLE "${_python_fw}/Versions/Current/bin/python") set(PYTHON_INCLUDE_PATH "${_python_fw}/Versions/Current/Headers") set(PYTHON_LIBRARY "${_python_fw}/Versions/Current/Python") if(EXISTS "${PYTHON_EXECUTABLE}" AND EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}") set(_custom_python_fw TRUE) endif() endif("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") endif(APPLE AND PYTHON_CUSTOM_FRAMEWORK) IF (ENABLE_QT5) FIND_PACKAGE(PythonInterp 3) ADD_DEFINITIONS(-DPYTHON3) ELSE (ENABLE_QT5) FIND_PACKAGE(PythonInterp 2) ADD_DEFINITIONS(-DPYTHON2) ENDIF (ENABLE_QT5) if(PYTHONINTERP_FOUND) FIND_FILE(_find_lib_python_py FindLibPython.py PATHS ${CMAKE_MODULE_PATH}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_lib_python_py} OUTPUT_VARIABLE python_config) if(python_config) STRING(REGEX REPLACE ".*exec_prefix:([^\n]+).*$" "\\1" PYTHON_PREFIX ${python_config}) STRING(REGEX REPLACE ".*\nshort_version:([^\n]+).*$" "\\1" PYTHON_SHORT_VERSION ${python_config}) STRING(REGEX REPLACE ".*\nlong_version:([^\n]+).*$" "\\1" PYTHON_LONG_VERSION ${python_config}) STRING(REGEX REPLACE ".*\npy_inc_dir:([^\n]+).*$" "\\1" PYTHON_INCLUDE_PATH ${python_config}) if(NOT PYTHON_SITE_PACKAGES_DIR) if(NOT PYTHON_LIBS_WITH_KDE_LIBS) STRING(REGEX REPLACE ".*\nsite_packages_dir:([^\n]+).*$" "\\1" PYTHON_SITE_PACKAGES_DIR ${python_config}) else(NOT PYTHON_LIBS_WITH_KDE_LIBS) set(PYTHON_SITE_PACKAGES_DIR ${KDE4_LIB_INSTALL_DIR}/python${PYTHON_SHORT_VERSION}/site-packages) endif(NOT PYTHON_LIBS_WITH_KDE_LIBS) endif(NOT PYTHON_SITE_PACKAGES_DIR) STRING(REGEX REPLACE "([0-9]+).([0-9]+)" "\\1\\2" PYTHON_SHORT_VERSION_NO_DOT ${PYTHON_SHORT_VERSION}) set(PYTHON_LIBRARY_NAMES python${PYTHON_SHORT_VERSION} python${PYTHON_SHORT_VERSION_NO_DOT} python${PYTHON_SHORT_VERSION}m python${PYTHON_SHORT_VERSION_NO_DOT}m) if(WIN32) STRING(REPLACE "\\" "/" PYTHON_SITE_PACKAGES_DIR ${PYTHON_SITE_PACKAGES_DIR}) endif(WIN32) FIND_LIBRARY(PYTHON_LIBRARY NAMES ${PYTHON_LIBRARY_NAMES}) set(PYTHON_INCLUDE_PATH ${PYTHON_INCLUDE_PATH} CACHE FILEPATH "Directory holding the python.h include file" FORCE) set(PYTHONLIBRARY_FOUND TRUE) endif(python_config) # adapted from cmake's builtin FindPythonLibs if(APPLE AND NOT _custom_python_fw) CMAKE_FIND_FRAMEWORKS(Python) set(PYTHON_FRAMEWORK_INCLUDES) if(Python_FRAMEWORKS) # If a framework has been selected for the include path, # make sure "-framework" is used to link it. if("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") set(PYTHON_LIBRARY "") set(PYTHON_DEBUG_LIBRARY "") endif("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") if(NOT PYTHON_LIBRARY) set (PYTHON_LIBRARY "-framework Python" CACHE FILEPATH "Python Framework" FORCE) endif(NOT PYTHON_LIBRARY) set(PYTHONLIBRARY_FOUND TRUE) endif(Python_FRAMEWORKS) endif(APPLE AND NOT _custom_python_fw) endif(PYTHONINTERP_FOUND) if(PYTHONLIBRARY_FOUND) if(APPLE) # keep reference to system or custom python site-packages # useful during app-bundling operations set(PYTHON_SITE_PACKAGES_SYS ${PYTHON_SITE_PACKAGES_DIR}) endif(APPLE) set(PYTHON_LIBRARIES ${PYTHON_LIBRARY}) if(NOT PYTHONLIBRARY_FIND_QUIETLY) message(STATUS "Found Python executable: ${PYTHON_EXECUTABLE}") message(STATUS "Found Python version: ${PYTHON_LONG_VERSION}") message(STATUS "Found Python library: ${PYTHON_LIBRARY}") endif(NOT PYTHONLIBRARY_FIND_QUIETLY) else(PYTHONLIBRARY_FOUND) if(PYTHONLIBRARY_FIND_REQUIRED) message(FATAL_ERROR "Could not find Python") endif(PYTHONLIBRARY_FIND_REQUIRED) endif(PYTHONLIBRARY_FOUND) endif (EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}")
supergis/QGIS
cmake/FindPythonLibrary.cmake
CMake
gpl-2.0
5,481
/* linux/drivers/mmc/host/sdhci-s3c.c * * Copyright 2008 Openmoko Inc. * Copyright 2008 Simtec Electronics * Ben Dooks <[email protected]> * http://armlinux.simtec.co.uk/ * * SDHCI (HSMMC) support for Samsung SoC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <mach/regs-clock.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/mmc/host.h> #include <plat/sdhci.h> #include <plat/regs-sdhci.h> #include <plat/clock.h> #include <plat/clock-clksrc.h> #include <linux/kernel.h> #include "sdhci.h" #define MAX_BUS_CLK (1) void mmc_valid(u16 valid, struct mmc_host *host); /* add by cym 20130328 */ #if CONFIG_MTK_COMBO_MT66XX /* skip do suspend for mmc2 host. But it would fail because clock is stopped * but NOT restored automatically after resume. */ #define MMC2_SKIP_SUSPEND (0) /* Enable the following pm capabilities for mmc2 host for wlan suspend/resume: * MMC_PM_KEEP_POWER * MMC_PM_WAKE_SDIO_IRQ * MMC_PM_IGNORE_PM_NOTIFY * It works on mldk4x12. */ #define MMC2_DO_SUSPEND_KEEP_PWR (1) #endif /* end add */ /** * struct sdhci_s3c - S3C SDHCI instance * @host: The SDHCI host created * @pdev: The platform device we where created from. * @ioarea: The resource created when we claimed the IO area. * @pdata: The platform data for this controller. * @cur_clk: The index of the current bus clock. * @clk_io: The clock for the internal bus interface. * @clk_bus: The clocks that are available for the SD/MMC bus clock. */ struct sdhci_s3c { struct sdhci_host *host; struct platform_device *pdev; struct resource *ioarea; struct s3c_sdhci_platdata *pdata; unsigned int cur_clk; int ext_cd_irq; int ext_cd_gpio; struct clk *clk_io; struct clk *clk_bus[MAX_BUS_CLK]; }; static inline struct sdhci_s3c *to_s3c(struct sdhci_host *host) { return sdhci_priv(host); } /** * get_curclk - convert ctrl2 register to clock source number * @ctrl2: Control2 register value. */ static u32 get_curclk(u32 ctrl2) { ctrl2 &= S3C_SDHCI_CTRL2_SELBASECLK_MASK; ctrl2 >>= S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; return ctrl2; } static void sdhci_s3c_check_sclk(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); u32 tmp = readl(host->ioaddr + S3C_SDHCI_CONTROL2); if (get_curclk(tmp) != ourhost->cur_clk) { dev_dbg(&ourhost->pdev->dev, "restored ctrl2 clock setting\n"); tmp &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; tmp |= ourhost->cur_clk << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; writel(tmp, host->ioaddr + 0x80); } } /** * sdhci_s3c_get_max_clk - callback to get maximum clock frequency. * @host: The SDHCI host instance. * * Callback to return the maximum clock rate acheivable by the controller. */ static unsigned int sdhci_s3c_get_max_clk(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *busclk; unsigned int rate, max; int clk; /* note, a reset will reset the clock source */ sdhci_s3c_check_sclk(host); for (max = 0, clk = 0; clk < MAX_BUS_CLK; clk++) { busclk = ourhost->clk_bus[clk]; if (!busclk) continue; rate = clk_get_rate(busclk); if (rate > max) max = rate; } return max; } static inline struct clksrc_clk *to_clksrc(struct clk *clk)//lisw sd { return container_of(clk, struct clksrc_clk, clk); } /** * sdhci_s3c_consider_clock - consider one the bus clocks for current setting * @ourhost: Our SDHCI instance. * @src: The source clock index. * @wanted: The clock frequency wanted. */ static unsigned int sdhci_s3c_consider_clock(struct sdhci_s3c *ourhost, unsigned int src, unsigned int wanted) { unsigned long rate; struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); struct clk *clksrc = clksrc_parent->sources->sources[src]; int div; if (!clksrc) return UINT_MAX; /* * Clock divider's step is different as 1 from that of host controller * when 'clk_type' is S3C_SDHCI_CLK_DIV_EXTERNAL. */ // if (ourhost->pdata->clk_type) { // rate = clk_round_rate(clksrc, wanted); // return wanted - rate; // } rate = clk_get_rate(clksrc); for (div = 1; div < 256; div++) { if ((rate / div) <= wanted) break; } dev_dbg(&ourhost->pdev->dev, "clk %d: rate %ld, want %d, got %ld\n", src, rate, wanted, rate / div); return (wanted - (rate / div)); } /** * sdhci_s3c_set_clock_src - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ int s3c_setrate_clksrc_two_div(struct clk *clk, unsigned long rate);//lisw sd int clk_set_parent(struct clk *clk, struct clk *parent);//lisw sd static void sdhci_s3c_set_clock_src(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; if(MAX_BUS_CLK==1){ for (src = 6; src < clksrc_parent->sources->nr_sources; src++) {//lisw ms : set 6 as firsrt selection because XXTI 24Mhz is not stable delta = sdhci_s3c_consider_clock(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } } else return; //printk("selected source %d, clock %d, delta %d\n", // best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = clksrc_parent->sources->sources[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); // ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); // ctrl &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; // ctrl |= best_src << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; // writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); //***use base clock select funtion in CMU instread in SD host controller***// if (clk_set_parent(clk_sclk_mmc->parent, clk)) printk("Unable to set parent %s of clock %s.\n", clk->name, clksrc_parent->clk.name); clk_sclk_mmc->parent->parent = clk; } // s3c_setrate_clksrc_two_div(clk_sclk_mmc,clock); /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * sdhci_s3c_set_clock - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ static void sdhci_s3c_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; for (src = 0; src < MAX_BUS_CLK; src++) { delta = sdhci_s3c_consider_clock(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } dev_dbg(&ourhost->pdev->dev, "selected source %d, clock %d, delta %d\n", best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = ourhost->clk_bus[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); ctrl &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; ctrl |= best_src << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); } /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * sdhci_s3c_get_min_clock - callback to get minimal supported clock value * @host: The SDHCI host being queried * * To init mmc host properly a minimal clock value is needed. For high system * bus clock's values the standard formula gives values out of allowed range. * The clock still can be set to lower values, if clock source other then * system bus is selected. */ static unsigned int sdhci_s3c_get_min_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int delta, min = UINT_MAX; int src; for (src = 0; src < MAX_BUS_CLK; src++) { delta = sdhci_s3c_consider_clock(ourhost, src, 0); if (delta == UINT_MAX) continue; /* delta is a negative value in this case */ if (-delta < min) min = -delta; } return min; } /* sdhci_cmu_get_max_clk - callback to get maximum clock frequency.*/ static unsigned int sdhci_cmu_get_max_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); host->max_clk = clk_get_rate(to_clksrc(ourhost->clk_bus[0]->parent)->sources->sources[ourhost->cur_clk]); return host->max_clk;//clk_round_rate(ourhost->clk_bus[ourhost->cur_clk], UINT_MAX); } /* sdhci_cmu_get_min_clock - callback to get minimal supported clock value. */ static unsigned int sdhci_cmu_get_min_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); /* * initial clock can be in the frequency range of * 100KHz-400KHz, so we set it as max value. */ return sdhci_cmu_get_max_clock(host)/((1 << to_clksrc(ourhost->clk_bus[0]->parent)->reg_div.size)*(1 << to_clksrc(ourhost->clk_bus[0])->reg_div.size)); } /* sdhci_cmu_set_clock - callback on clock change.*/ static void sdhci_cmu_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); /* don't bother if the clock is going off */ if (clock == 0) return; // sdhci_s3c_set_clock(host, clock); sdhci_s3c_set_clock_src(host, clock); // clk_set_rate(ourhost->clk_bus[ourhost->cur_clk], clock); s3c_setrate_clksrc_two_div(ourhost->clk_bus[0],clock); host->clock = clock; } /** * sdhci_s3c_platform_8bit_width - support 8bit buswidth * @host: The SDHCI host being queried * @width: MMC_BUS_WIDTH_ macro for the bus width being requested * * We have 8-bit width support but is not a v3 controller. * So we add platform_8bit_width() and support 8bit width. */ static int sdhci_s3c_platform_8bit_width(struct sdhci_host *host, int width) { u8 ctrl; ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL); switch (width) { case MMC_BUS_WIDTH_8: ctrl |= SDHCI_CTRL_8BITBUS; ctrl &= ~SDHCI_CTRL_4BITBUS; break; case MMC_BUS_WIDTH_4: ctrl |= SDHCI_CTRL_4BITBUS; ctrl &= ~SDHCI_CTRL_8BITBUS; break; default: break; } sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL); return 0; } //ly 20111123 int sdhci_s3c_get_cd(struct sdhci_host *mmc)//lisw sd hotplug { int detect; struct sdhci_s3c* sc = sdhci_priv(mmc); if(mmc->mmc->index== 1){ //ch0+1 is emmc ch2 is TF int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if (status){ detect = true; }else{ detect = false; } }else{ detect = true; } return detect; } static struct sdhci_ops sdhci_s3c_ops = { .get_max_clock = sdhci_s3c_get_max_clk, .set_clock = sdhci_s3c_set_clock, .get_min_clock = sdhci_s3c_get_min_clock, .platform_8bit_width = sdhci_s3c_platform_8bit_width, .get_cd = sdhci_s3c_get_cd,//ly }; void sdhci_init(struct sdhci_host *host, int soft); static void sdhci_s3c_notify_change(struct platform_device *dev, int state) { struct sdhci_host *host = platform_get_drvdata(dev); unsigned long flags; if (host) { spin_lock_irqsave(&host->lock, flags); if (state) { dev_dbg(&dev->dev, "card inserted.\n"); host->flags &= ~SDHCI_DEVICE_DEAD; host->quirks |= SDHCI_QUIRK_BROKEN_CARD_DETECTION; sdhci_init(host,0);//lisw sd hotplug : for reinitialize host controller each time plugin } else { dev_dbg(&dev->dev, "card removed.\n"); host->flags |= SDHCI_DEVICE_DEAD; host->quirks &= ~SDHCI_QUIRK_BROKEN_CARD_DETECTION; } tasklet_schedule(&host->card_tasklet); spin_unlock_irqrestore(&host->lock, flags); } } static irqreturn_t sdhci_s3c_gpio_card_detect_thread(int irq, void *dev_id) { struct sdhci_s3c *sc = dev_id; int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if(status){//card present mmc_valid(1,sc->host->mmc);//lisw sd hotplug } else{//card absent mmc_valid(0,sc->host->mmc); } sdhci_s3c_notify_change(sc->pdev, status); return IRQ_HANDLED; } void sdhci_s3c_sdio_card_detect(struct platform_device *pdev) { struct sdhci_host *host = platform_get_drvdata(pdev); //printk(KERN_DEBUG "+%s", __FUNCTION__); printk("+%s\n", __FUNCTION__); // mmc_detect_change(host->mmc, msecs_to_jiffies(60)); mmc_detect_change(host->mmc, msecs_to_jiffies(500)); //printk(KERN_DEBUG "-%s", __FUNCTION__); printk("-%s\n", __FUNCTION__); } EXPORT_SYMBOL(sdhci_s3c_sdio_card_detect); static void sdhci_s3c_setup_card_detect_gpio(struct sdhci_s3c *sc) { struct s3c_sdhci_platdata *pdata = sc->pdata; struct device *dev = &sc->pdev->dev; if (gpio_request(pdata->ext_cd_gpio, "SDHCI EXT CD") == 0) { sc->ext_cd_gpio = pdata->ext_cd_gpio; sc->ext_cd_irq = gpio_to_irq(pdata->ext_cd_gpio); enable_irq_wake(sc->ext_cd_irq);//lisw hotplug during suspend if (sc->ext_cd_irq && request_threaded_irq(sc->ext_cd_irq, NULL, sdhci_s3c_gpio_card_detect_thread, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, dev_name(dev), sc) == 0) { int status = gpio_get_value(sc->ext_cd_gpio); if (pdata->ext_cd_gpio_invert) status = !status; sdhci_s3c_notify_change(sc->pdev, status); } else { dev_warn(dev, "cannot request irq for card detect\n"); sc->ext_cd_irq = 0; } } else { dev_err(dev, "cannot request gpio for card detect\n"); } } static int __devinit sdhci_s3c_probe(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct device *dev = &pdev->dev; struct sdhci_host *host; struct sdhci_s3c *sc; struct resource *res; int ret, irq, ptr, clks; if (!pdata) { dev_err(dev, "no device data specified\n"); return -ENOENT; } irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(dev, "no irq specified\n"); return irq; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(dev, "no memory specified\n"); return -ENOENT; } host = sdhci_alloc_host(dev, sizeof(struct sdhci_s3c)); if (IS_ERR(host)) { dev_err(dev, "sdhci_alloc_host() failed\n"); return PTR_ERR(host); } sc = sdhci_priv(host); sc->host = host; sc->pdev = pdev; sc->pdata = pdata; sc->ext_cd_gpio = -1; /* invalid gpio number */ platform_set_drvdata(pdev, host); sc->clk_io = clk_get(dev, "hsmmc"); if (IS_ERR(sc->clk_io)) { dev_err(dev, "failed to get io clock\n"); ret = PTR_ERR(sc->clk_io); goto err_io_clk; } /* enable the local io clock and keep it running for the moment. */ clk_enable(sc->clk_io); for (clks = 0, ptr = 0; ptr < MAX_BUS_CLK; ptr++) { struct clk *clk; char *name = pdata->clocks[ptr]; if (name == NULL) continue; clk = clk_get(dev, name); if (IS_ERR(clk)) { dev_err(dev, "failed to get clock %s\n", name); continue; } clks++; sc->clk_bus[ptr] = clk; /* * save current clock index to know which clock bus * is used later in overriding functions. */ sc->cur_clk = 7;// clock sources select number clk_set_parent(clk->parent,to_clksrc(clk->parent)->sources->sources[7]); clk_enable(clk); dev_info(dev, "clock source %d: %s (%ld Hz)\n", ptr, name, clk_get_rate(clk)); } if (clks == 0) { dev_err(dev, "failed to find any bus clocks\n"); ret = -ENOENT; goto err_no_busclks; } sc->ioarea = request_mem_region(res->start, resource_size(res), mmc_hostname(host->mmc)); if (!sc->ioarea) { dev_err(dev, "failed to reserve register area\n"); ret = -ENXIO; goto err_req_regs; } host->ioaddr = ioremap_nocache(res->start, resource_size(res)); if (!host->ioaddr) { dev_err(dev, "failed to map registers\n"); ret = -ENXIO; goto err_req_regs; } /* Ensure we have minimal gpio selected CMD/CLK/Detect */ if (pdata->cfg_gpio) pdata->cfg_gpio(pdev, pdata->max_width); host->hw_name = "samsung-hsmmc"; host->ops = &sdhci_s3c_ops; host->quirks = 0; host->irq = irq; /* Setup quirks for the controller */ host->quirks |= SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC; host->quirks |= SDHCI_QUIRK_NO_HISPD_BIT; #ifndef CONFIG_MMC_SDHCI_S3C_DMA /* we currently see overruns on errors, so disable the SDMA * support as well. */ host->quirks |= SDHCI_QUIRK_BROKEN_DMA; #endif /* CONFIG_MMC_SDHCI_S3C_DMA */ /* It seems we do not get an DATA transfer complete on non-busy * transfers, not sure if this is a problem with this specific * SDHCI block, or a missing configuration that needs to be set. */ host->quirks |= SDHCI_QUIRK_NO_BUSY_IRQ; /* This host supports the Auto CMD12 */ host->quirks |= SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12; if (pdata->cd_type == S3C_SDHCI_CD_NONE || pdata->cd_type == S3C_SDHCI_CD_PERMANENT) host->quirks |= SDHCI_QUIRK_BROKEN_CARD_DETECTION; if (pdata->cd_type == S3C_SDHCI_CD_PERMANENT) host->mmc->caps = MMC_CAP_NONREMOVABLE; if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; host->quirks |= (SDHCI_QUIRK_32BIT_DMA_ADDR | SDHCI_QUIRK_32BIT_DMA_SIZE); /* HSMMC on Samsung SoCs uses SDCLK as timeout clock */ host->quirks |= SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK; /* * If controller does not have internal clock divider, * we can use overriding functions instead of default. */ if (pdata->clk_type) { sdhci_s3c_ops.set_clock = sdhci_cmu_set_clock; sdhci_s3c_ops.get_min_clock = sdhci_cmu_get_min_clock; sdhci_s3c_ops.get_max_clock = sdhci_cmu_get_max_clock; } /* It supports additional host capabilities if needed */ if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set MMC_PM_IGNORE_PM_NOTIFY for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY; } #elif MMC2_DO_SUSPEND_KEEP_PWR if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set MMC_PM_IGNORE_PM_NOTIFY for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY; printk(KERN_INFO "%s: set MMC_PM_KEEP_POWER | MMC_PM_WAKE_SDIO_IRQ for %s pm_caps\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_caps |= MMC_PM_KEEP_POWER | MMC_PM_WAKE_SDIO_IRQ; } #endif /* end add */ ret = sdhci_add_host(host); if (ret) { dev_err(dev, "sdhci_add_host() failed\n"); goto err_add_host; } /* The following two methods of card detection might call sdhci_s3c_notify_change() immediately, so they can be called only after sdhci_add_host(). Setup errors are ignored. */ if (pdata->cd_type == S3C_SDHCI_CD_EXTERNAL && pdata->ext_cd_init) pdata->ext_cd_init(&sdhci_s3c_notify_change); if (pdata->cd_type == S3C_SDHCI_CD_GPIO && gpio_is_valid(pdata->ext_cd_gpio)) sdhci_s3c_setup_card_detect_gpio(sc); return 0; err_add_host: release_resource(sc->ioarea); kfree(sc->ioarea); err_req_regs: for (ptr = 0; ptr < MAX_BUS_CLK; ptr++) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } err_no_busclks: clk_disable(sc->clk_io); clk_put(sc->clk_io); err_io_clk: sdhci_free_host(host); return ret; } static int __devexit sdhci_s3c_remove(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct sdhci_host *host = platform_get_drvdata(pdev); struct sdhci_s3c *sc = sdhci_priv(host); int ptr; if (pdata->cd_type == S3C_SDHCI_CD_EXTERNAL && pdata->ext_cd_cleanup) pdata->ext_cd_cleanup(&sdhci_s3c_notify_change); if (sc->ext_cd_irq) free_irq(sc->ext_cd_irq, sc); if (gpio_is_valid(sc->ext_cd_gpio)) gpio_free(sc->ext_cd_gpio); sdhci_remove_host(host, 1); for (ptr = 0; ptr < 3; ptr++) { if (sc->clk_bus[ptr]) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } } clk_disable(sc->clk_io); clk_put(sc->clk_io); iounmap(host->ioaddr); release_resource(sc->ioarea); kfree(sc->ioarea); sdhci_free_host(host); platform_set_drvdata(pdev, NULL); return 0; } #ifdef CONFIG_PM static int sdhci_s3c_suspend(struct platform_device *dev, pm_message_t pm) { struct sdhci_host *host = platform_get_drvdata(dev); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_suspend_host(host, pm); return 0; } static int sdhci_s3c_resume(struct platform_device *dev) { struct sdhci_host *host = platform_get_drvdata(dev); struct sdhci_s3c *sc = sdhci_priv(host); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_resume_host(host); /* add by cym 20130328 */ #ifndef MMC2_SKIP_SUSPEND /* end add */ if(!(host->mmc->caps & MMC_CAP_NONREMOVABLE)){//lisw hotplug during suspend int status = gpio_get_value(sc->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; sdhci_s3c_notify_change(sc->pdev, status); } /* add by cym 20130328 */ #endif /* end add */ return 0; } #else #define sdhci_s3c_suspend NULL #define sdhci_s3c_resume NULL #endif static struct platform_driver sdhci_s3c_driver = { .probe = sdhci_s3c_probe, .remove = __devexit_p(sdhci_s3c_remove), .suspend = sdhci_s3c_suspend, .resume = sdhci_s3c_resume, .driver = { .owner = THIS_MODULE, .name = "s3c-sdhci", }, }; static int __init sdhci_s3c_init(void) { return platform_driver_register(&sdhci_s3c_driver); } static void __exit sdhci_s3c_exit(void) { platform_driver_unregister(&sdhci_s3c_driver); } module_init(sdhci_s3c_init); module_exit(sdhci_s3c_exit); MODULE_DESCRIPTION("Samsung SDHCI (HSMMC) glue"); MODULE_AUTHOR("Ben Dooks, <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:s3c-sdhci");
Android-Dongyf/itop-kernel
drivers/mmc/host/sdhci-s3c-ori.c
C
gpl-2.0
23,555
/* Copyright (c) 2009-2011, Code Aurora Forum. 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 version 2 and * only version 2 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. * */ /*----------------------------------------------------------------------------*/ // COPYRIGHT(C) FUJITSU LIMITED 2011-2012 /*----------------------------------------------------------------------------*/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/hrtimer.h> #include <linux/delay.h> #include <mach/hardware.h> #include <linux/io.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/spinlock.h> #include <linux/fb.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ extern struct mutex msm_fb_ioctl_lut_sem; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ static struct mdp4_overlay_pipe *mddi_pipe; static struct msm_fb_data_type *mddi_mfd; static int busy_wait_cnt; static int vsync_start_y_adjust = 4; static int dmap_vsync_enable; /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) extern void mddi_panel_fullscrn_update_notify(void); #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ void mdp_dmap_vsync_set(int enable) { dmap_vsync_enable = enable; } int mdp_dmap_vsync_get(void) { return dmap_vsync_enable; } void mdp4_mddi_vsync_enable(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe, int which) { uint32 start_y, data, tear_en; tear_en = (1 << which); if ((mfd->use_mdp_vsync) && (mfd->ibuf.vsync_enable) && (mfd->panel_info.lcd.vsync_enable)) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (which == 0 && dmap_vsync_enable == 0 && mfd->panel_info.lcd.rev < 2) /* dma_p */ return; } if (vsync_start_y_adjust <= pipe->dst_y) start_y = pipe->dst_y - vsync_start_y_adjust; else start_y = (mfd->total_lcd_lines - 1) - (vsync_start_y_adjust - pipe->dst_y); if (which == 0) MDP_OUTP(MDP_BASE + 0x210, start_y); /* primary */ else MDP_OUTP(MDP_BASE + 0x214, start_y); /* secondary */ data = inpdw(MDP_BASE + 0x20c); data |= tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } else { data = inpdw(MDP_BASE + 0x20c); data &= ~tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } } #define WHOLESCREEN void mdp4_overlay_update_lcd(struct msm_fb_data_type *mfd) { MDPIBUF *iBuf = &mfd->ibuf; uint8 *src; int ptype; uint32 mddi_ld_param; uint16 mddi_vdo_packet_reg; struct mdp4_overlay_pipe *pipe; int ret; if (mfd->key != MFD_KEY) return; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_lock(&msm_fb_ioctl_lut_sem); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ mddi_mfd = mfd; /* keep it */ /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) /* if update RAM image size is full screen size */ if (iBuf->dma_h == mfd->panel_info.yres) { mddi_panel_fullscrn_update_notify(); } #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (mddi_pipe == NULL) { ptype = mdp4_overlay_format2type(mfd->fb_imgType); if (ptype < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); pipe = mdp4_overlay_pipe_alloc(ptype, MDP4_MIXER0); if (pipe == NULL) printk(KERN_INFO "%s: pipe_alloc failed\n", __func__); pipe->pipe_used++; pipe->mixer_num = MDP4_MIXER0; pipe->src_format = mfd->fb_imgType; mdp4_overlay_panel_mode(pipe->mixer_num, MDP4_PANEL_MDDI); ret = mdp4_overlay_format2pipe(pipe); if (ret < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); mddi_pipe = pipe; /* keep it */ mddi_pipe->blt_end = 1; /* mark as end */ mddi_ld_param = 0; mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mdp_hw_revision == MDP4_REVISION_V2_1) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); } if (mfd->panel_info.type == MDDI_PANEL) { if (mfd->panel_info.pdest == DISPLAY_1) mddi_ld_param = 0; else mddi_ld_param = 1; } else { mddi_ld_param = 2; } MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param); if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); } else { pipe = mddi_pipe; } /* 0 for dma_p, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 0); src = (uint8 *) iBuf->buf; #ifdef WHOLESCREEN { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32)src; pipe->srcp0_ystride = fbi->fix.line_length; } #else if (mdp4_overlay_active(MDP4_MIXER0)) { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = fbi->fix.line_length; } else { /* starting input address */ src += (iBuf->dma_x + iBuf->dma_y * iBuf->ibuf_width) * iBuf->bpp; pipe->src_height = iBuf->dma_h; pipe->src_width = iBuf->dma_w; pipe->src_h = iBuf->dma_h; pipe->src_w = iBuf->dma_w; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = iBuf->dma_h; pipe->dst_w = iBuf->dma_w; pipe->dst_y = iBuf->dma_y; pipe->dst_x = iBuf->dma_x; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = iBuf->ibuf_width * iBuf->bpp; } #endif pipe->mixer_stage = MDP4_MIXER_STAGE_BASE; mdp4_overlay_rgb_setup(pipe); mdp4_mixer_stage_up(pipe); mdp4_overlayproc_cfg(pipe); mdp4_overlay_dmap_xy(pipe); mdp4_overlay_dmap_cfg(mfd, 0); mdp4_mddi_vsync_enable(mfd, pipe, 0); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int mdp4_mddi_overlay_blt_offset(int *off) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (mddi_pipe->blt_end || (mdp4_overlay_mixer_play(mddi_pipe->mixer_num) == 0)) { *off = -1; return -EINVAL; } } else { /* no dmas dmap switch */ if (mddi_pipe->blt_end) { *off = -1; return -EINVAL; } } if (mddi_pipe->blt_cnt & 0x01) *off = mddi_pipe->src_height * mddi_pipe->src_width * 3; else *off = 0; return 0; } void mdp4_mddi_overlay_blt(ulong addr) { unsigned long flag; spin_lock_irqsave(&mdp_spin_lock, flag); if (addr) { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_intr_mask |= INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mddi_pipe->blt_cnt = 0; mddi_pipe->blt_end = 0; mddi_pipe->blt_addr = addr; } else { mddi_pipe->blt_end = 1; /* mark as end */ } spin_unlock_irqrestore(&mdp_spin_lock, flag); } void mdp4_blt_xy_update(struct mdp4_overlay_pipe *pipe) { uint32 off, addr; int bpp; char *overlay_base; if (pipe->blt_addr == 0) return; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; addr = pipe->blt_addr + off; /* dmap */ MDP_OUTP(MDP_BASE + 0x90008, addr); /* overlay 0 */ overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ outpdw(overlay_base + 0x000c, addr); outpdw(overlay_base + 0x001c, addr); } /* * mdp4_dmap_done_mddi: called from isr */ void mdp4_dma_p_done_mddi(void) { if (mddi_pipe->blt_end) { mddi_pipe->blt_addr = 0; mdp_intr_mask &= ~INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); mdp4_overlayproc_cfg(mddi_pipe); mdp4_overlay_dmap_xy(mddi_pipe); } /* * single buffer, no need to increase * mdd_pipe->dmap_cnt here */ } /* * mdp4_overlay0_done_mddi: called from isr */ void mdp4_overlay0_done_mddi(struct mdp_dma_data *dma) { mdp_disable_irq_nosync(MDP_OVERLAY0_TERM); dma->busy = FALSE; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_unlock(&msm_fb_ioctl_lut_sem); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ complete(&dma->comp); mdp_pipe_ctrl(MDP_OVERLAY0_BLOCK, MDP_BLOCK_POWER_OFF, TRUE); if (busy_wait_cnt) busy_wait_cnt--; pr_debug("%s: ISR-done\n", __func__); if (mddi_pipe->blt_addr) { if (mddi_pipe->blt_cnt == 0) { mdp4_overlayproc_cfg(mddi_pipe); mdp4_overlay_dmap_xy(mddi_pipe); mddi_pipe->ov_cnt = 0; mddi_pipe->dmap_cnt = 0; /* BLT start from next frame */ } else { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp4_blt_xy_update(mddi_pipe); outpdw(MDP_BASE + 0x000c, 0x0); /* start DMAP */ } mddi_pipe->blt_cnt++; mddi_pipe->ov_cnt++; } } void mdp4_mddi_overlay_restore(void) { if (mddi_mfd == NULL) return; pr_debug("%s: resotre, pid=%d\n", __func__, current->pid); if (mddi_mfd->panel_power_on == 0) return; if (mddi_mfd && mddi_pipe) { mdp4_mddi_dma_busy_wait(mddi_mfd); mdp4_overlay_update_lcd(mddi_mfd); mdp4_mddi_overlay_kickoff(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } if (mdp_hw_revision < MDP4_REVISION_V2_1) /* need dmas dmap switch */ mdp4_mddi_overlay_dmas_restore(); } /* * mdp4_mddi_cmd_dma_busy_wait: check mddi link activity * dsi link is a shared resource and it can only be used * while it is in idle state. * ov_mutex need to be acquired before call this function. */ void mdp4_mddi_dma_busy_wait(struct msm_fb_data_type *mfd) { unsigned long flag; int need_wait = 0; pr_debug("%s: START, pid=%d\n", __func__, current->pid); spin_lock_irqsave(&mdp_spin_lock, flag); if (mfd->dma->busy == TRUE) { if (busy_wait_cnt == 0) INIT_COMPLETION(mfd->dma->comp); busy_wait_cnt++; need_wait++; } spin_unlock_irqrestore(&mdp_spin_lock, flag); if (need_wait) { /* wait until DMA finishes the current job */ pr_debug("%s: PENDING, pid=%d\n", __func__, current->pid); wait_for_completion(&mfd->dma->comp); } pr_debug("%s: DONE, pid=%d\n", __func__, current->pid); } void mdp4_mddi_kickoff_video(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); mdp4_mddi_overlay_kickoff(mfd, pipe); } void mdp4_mddi_kickoff_ui(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); mdp4_mddi_overlay_kickoff(mfd, pipe); } void mdp4_mddi_overlay_kickoff(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); if (mdp_hw_revision == MDP4_REVISION_V2_1) { if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_UNSET)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_UNSET, false); } if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_SET)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ MDP_OUTP(MDP_BASE + 0x00028, data); mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_SET, false); } } mdp_enable_irq(MDP_OVERLAY0_TERM); mfd->dma->busy = TRUE; /* start OVERLAY pipe */ mdp_pipe_kickoff(MDP_OVERLAY0_TERM, mfd); mdp4_stat.kickoff_ov0++; } void mdp4_dma_s_update_lcd(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { MDPIBUF *iBuf = &mfd->ibuf; uint32 outBpp = iBuf->bpp; uint16 mddi_vdo_packet_reg; uint32 dma_s_cfg_reg; dma_s_cfg_reg = 0; if (mfd->fb_imgType == MDP_RGBA_8888) dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR; /* on purpose */ else if (mfd->fb_imgType == MDP_BGR_565) dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR; else dma_s_cfg_reg |= DMA_PACK_PATTERN_RGB; if (outBpp == 4) dma_s_cfg_reg |= (1 << 26); /* xRGB8888 */ else if (outBpp == 2) dma_s_cfg_reg |= DMA_IBUF_FORMAT_RGB565; dma_s_cfg_reg |= DMA_DITHER_EN; /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* PIXELSIZE */ MDP_OUTP(MDP_BASE + 0xa0004, (pipe->dst_h << 16 | pipe->dst_w)); MDP_OUTP(MDP_BASE + 0xa0008, pipe->srcp0_addr); /* ibuf address */ MDP_OUTP(MDP_BASE + 0xa000c, pipe->srcp0_ystride);/* ystride */ if (mfd->panel_info.bpp == 24) { dma_s_cfg_reg |= DMA_DSTC0G_8BITS | /* 666 18BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } MDP_OUTP(MDP_BASE + 0xa0010, (pipe->dst_y << 16) | pipe->dst_x); /* 1 for dma_s, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 1); mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); MDP_OUTP(MDP_BASE + 0xa0000, dma_s_cfg_reg); mdp4_mddi_vsync_enable(mfd, pipe, 1); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_mddi_dma_s_kickoff(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); mdp_enable_irq(MDP_DMA_S_TERM); mfd->dma->busy = TRUE; mfd->ibuf_flushed = TRUE; /* start dma_s pipe */ mdp_pipe_kickoff(MDP_DMA_S_TERM, mfd); mdp4_stat.kickoff_dmas++; /* wait until DMA finishes the current job */ wait_for_completion(&mfd->dma->comp); mdp_disable_irq(MDP_DMA_S_TERM); } void mdp4_mddi_overlay_dmas_restore(void) { /* mutex held by caller */ if (mddi_mfd && mddi_pipe) { mdp4_mddi_dma_busy_wait(mddi_mfd); mdp4_dma_s_update_lcd(mddi_mfd, mddi_pipe); mdp4_mddi_dma_s_kickoff(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } } void mdp4_mddi_overlay(struct msm_fb_data_type *mfd) { mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { mdp4_mddi_dma_busy_wait(mfd); mdp4_overlay_update_lcd(mfd); if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* dmas dmap switch */ if (mdp4_overlay_mixer_play(mddi_pipe->mixer_num) == 0) { mdp4_dma_s_update_lcd(mfd, mddi_pipe); mdp4_mddi_dma_s_kickoff(mfd, mddi_pipe); } else mdp4_mddi_kickoff_ui(mfd, mddi_pipe); } else /* no dams dmap switch */ mdp4_mddi_kickoff_ui(mfd, mddi_pipe); /* signal if pan function is waiting for the update completion */ if (mfd->pan_waiting) { mfd->pan_waiting = FALSE; complete(&mfd->pan_comp); } } mutex_unlock(&mfd->dma->ov_mutex); } int mdp4_mddi_overlay_cursor(struct fb_info *info, struct fb_cursor *cursor) { struct msm_fb_data_type *mfd = info->par; mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { mdp4_mddi_dma_busy_wait(mfd); mdp_hw_cursor_update(info, cursor); } mutex_unlock(&mfd->dma->ov_mutex); return 0; }
hiikezoe/android_kernel_fujitsu_f12nad
drivers/video/msm/mdp4_overlay_mddi.c
C
gpl-2.0
16,555
<?php /** * Template Name: Two Column, Right-Sidebar * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package joe_neat */ get_header(); ?> <div id="primary" class="content-area"> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'page-templates/partials/content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'partials/content', 'none' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endif; ?> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
joseph-jalbert/joe_neat
page-templates/template-right-col.php
PHP
gpl-2.0
1,499
package org.nla.tarotdroid.lib.helpers; import static com.google.common.base.Preconditions.checkArgument; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Network and internet connexion helper class. */ public class ConnexionHelper { /** * Checking for all possible internet providers * **/ public static boolean isConnectedToInternet(Context context) { checkArgument(context != null, "context is null"); boolean toReturn = false; ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { toReturn = true; break; } } return toReturn; } }
daffycricket/tarotdroid
tarotDroidUiLib/src/main/java/org/nla/tarotdroid/lib/helpers/ConnexionHelper.java
Java
gpl-2.0
1,094
<!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_18) on Tue Nov 02 13:16:53 CET 2010 --> <TITLE> com.redhat.rhn.common.filediff Class Hierarchy </TITLE> <META NAME="date" CONTENT="2010-11-02"> <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="com.redhat.rhn.common.filediff 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> </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="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/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 com.redhat.rhn.common.filediff </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">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Diff.html" title="class in com.redhat.rhn.common.filediff"><B>Diff</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Differ.html" title="class in com.redhat.rhn.common.filediff"><B>Differ</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Edit.html" title="class in com.redhat.rhn.common.filediff"><B>Edit</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/FileLines.html" title="class in com.redhat.rhn.common.filediff"><B>FileLines</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Hunk.html" title="class in com.redhat.rhn.common.filediff"><B>Hunk</B></A><UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/ChangeHunk.html" title="class in com.redhat.rhn.common.filediff"><B>ChangeHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DeleteHunk.html" title="class in com.redhat.rhn.common.filediff"><B>DeleteHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/InsertHunk.html" title="class in com.redhat.rhn.common.filediff"><B>InsertHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/MatchHunk.html" title="class in com.redhat.rhn.common.filediff"><B>MatchHunk</B></A></UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnHtmlDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnHtmlDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnPatchDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnPatchDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Trace.html" title="class in com.redhat.rhn.common.filediff"><B>Trace</B></A></UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffVisitor</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffWriter</B></A></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> </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="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/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>
colloquium/spacewalk
documentation/javadoc/com/redhat/rhn/common/filediff/package-tree.html
HTML
gpl-2.0
9,249
<?php class SatellitePlugin { var $plugin_name; var $plugin_base; var $pre = 'Satellite'; var $debugging = false; var $menus = array(); var $latestorbit = 'jquery.orbit-1.3.1.js'; //var $latestorbit = 'orbit-min.js'; var $cssfile = 'orbit-css.php'; var $cssadmin = 'admin-styles.css'; var $sections = array( 'satellite' => 'satellite-slides', 'settings' => 'satellite', 'newgallery' => 'satellite-galleries', ); var $helpers = array('Ajax', 'Config', 'Db', 'Html', 'Form', 'Metabox', 'Version'); var $models = array('Slide','Gallery'); function register_plugin($name, $base) { $this->plugin_base = rtrim(dirname($base), DS); $this->initialize_classes(); $this->initialize_options(); if (function_exists('load_plugin_textdomain')) { $currentlocale = get_locale(); if (!empty($currentlocale)) { $moFile = dirname(__FILE__) . DS . "languages" . DS . SATL_PLUGIN_NAME . "-" . $currentlocale . ".mo"; if (@file_exists($moFile) && is_readable($moFile)) { load_textdomain(SATL_PLUGIN_NAME, $moFile); } } } if ($this->debugging == true) { global $wpdb; $wpdb->show_errors(); error_reporting(E_ALL); @ini_set('display_errors', 1); } $this->add_action('wp_head', 'enqueue_scripts', 1); $this->add_action('admin_head', 'add_admin_styles'); $this->add_action("admin_head", 'plupload_admin_head'); $this->add_action('admin_init', 'admin_scripts'); $this->add_filter('the_posts', 'conditionally_add_scripts_and_styles'); // the_posts gets triggered before wp_head $this->add_action('wp_ajax_plupload_action', "g_plupload_action"); return true; } function add_admin_styles() { $adminStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssadmin . '?v=' . SATL_VERSION; wp_register_style(SATL_PLUGIN_NAME . "_adstyle", $adminStyleUrl); wp_enqueue_style(SATL_PLUGIN_NAME . "_adstyle"); } function conditionally_add_scripts_and_styles($posts){ if (empty($posts)) return $posts; $shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued if ($this->get_option('shortreq') == 'N') { $shortcode_found = true; } else { foreach ($posts as $post) { if ( ( stripos($post->post_content, '[gpslideshow') !== false ) || ( stripos($post->post_content, '[satellite') !== false) || ( stripos($post->post_content, '[slideshow') !== false && $this->get_option('embedss') == "Y" ) ) { $shortcode_found = true; // bingo! $pID = $post->ID; break; } } } if ($shortcode_found) { $satlStyleFile = SATL_PLUGIN_DIR . '/css/' . $this -> cssfile; $satlStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssfile . '?v=' . SATL_VERSION . '&amp;pID=' . $pID; if ($_SERVER['HTTPS']) { $satlStyleUrl = str_replace("http:", "https:", $satlStyleUrl); } //$infogal = $this; if (file_exists($satlStyleFile)) { if ($styles = $this->get_option('styles')) { foreach ($styles as $skey => $sval) { $satlStyleUrl .= "&amp;" . $skey . "=" . urlencode($sval); } } $width_temp = $this->get_option('width_temp'); $height_temp = $this->get_option('height_temp'); $align_temp = $this->get_option('align_temp'); $nav_temp = $this->get_option('nav_temp'); //print_r($wp_query->current_post); if (is_array($width_temp)) { foreach ($width_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;width_temp=" . urlencode($sval); } } if (is_array($height_temp)) { foreach ($height_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;height_temp=" . urlencode($sval); } } if (is_array($align_temp)) { foreach ($align_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;align=" . urlencode($sval); } } if (is_array($nav_temp)) { foreach ($nav_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;nav=" . urlencode($sval); } } wp_register_style(SATL_PLUGIN_NAME . "_style", $satlStyleUrl); } // enqueue here wp_enqueue_style(SATL_PLUGIN_NAME . "_style"); wp_enqueue_script(SATL_PLUGIN_NAME . "_script", '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/' . $this->latestorbit, array('jquery'), SATL_VERSION); //wp_enqueue_script(SATL_PLUGIN_NAME . "_script"); } return $posts; } function init_class($name = null, $params = array()) { if (!empty($name)) { $name = $this->pre . $name; if (class_exists($name)) { if ($class = new $name($params)) { return $class; } } } $this->init_class('Country'); return false; } function initialize_classes() { if (!empty($this->helpers)) { foreach ($this->helpers as $helper) { $hfile = dirname(__FILE__) . DS . 'helpers' . DS . strtolower($helper) . '.php'; if (file_exists($hfile)) { require_once($hfile); if (empty($this->{$helper}) || !is_object($this->{$helper})) { $classname = $this->pre . $helper . 'Helper'; if (class_exists($classname)) { $this->{$helper} = new $classname; } } } } } if (!empty($this->models)) { foreach ($this->models as $model) { $mfile = dirname(__FILE__) . DS . 'models' . DS . strtolower($model) . '.php'; if (file_exists($mfile)) { require_once($mfile); if (empty($this->{$model}) || !is_object($this->{$model})) { $classname = $this->pre . $model; if (class_exists($classname)) { $this->{$model} = new $classname; } } } } } } function initialize_options() { $styles = array( 'width' => "450", 'height' => "300", 'thumbheight' => "75", 'thumbarea' => "275", 'thumbareamargin' => "30", 'thumbmargin' => "2", 'thumbspacing' => "5", 'thumbactive' => "#FFFFFF", 'thumbopacity' => "70", 'align' => "none", 'border' => "1px solid #CCCCCC", 'background' => "#000000", 'infotitle' => "2", 'infobackground' => "#000000", 'infocolor' => "#FFFFFF", 'playshow' => "A", 'navpush' => "0", 'infomin' => "Y" ); $this->add_option('styles', $styles); //General Settings $this->add_option('fadespeed', 10); $this->add_option('nav_opacity', 30); $this->add_option('navhover', 70); $this->add_option('nolinker', "N"); $this->add_option('nolinkpage', 0); $this->add_option('pagelink', "S"); $this->add_option('wpattach', "N"); $this->add_option('captionlink', "N"); $this->add_option('transition', "FB"); $this->add_option('information', "Y"); $this->add_option('infospeed', 10); $this->add_option('showhover', "P"); $this->add_option('thumbnails', "N"); $this->add_option('thumbposition', "bottom"); $this->add_option('thumbscrollspeed', 5); $this->add_option('autoslide', "Y"); $this->add_option('autoslide_temp', "Y"); $this->add_option('imagesbox', "T"); $this->add_option('autospeed', 10); $this->add_option('abscenter', "Y"); $this->add_option('embedss', "Y"); $this->add_option('satwiz', "Y"); $this->add_option('shortreq', "Y"); $this->add_option('ggljquery', "Y"); $this->add_option('splash', "N"); $this->add_option('stldb_version', "1.0"); // Orbit Only $this->add_option('autospeed2', 5000); $this->add_option('duration', 700); $this->add_option('othumbs', "B"); $this->add_option('bullcenter', "true"); //Multi-ImageSlide $this->add_option('multicols', 3); $this->add_option('dropshadow', 'N'); //Full Right / Left $this->add_option('thumbarea', 250); //Premium $this->add_option('custslide', 10); $this->add_option('preload', 'N'); $this->add_option('keyboard', 'N'); $this->add_option('manager', 'manage_options'); $this->add_option('nav', "on"); //$this->add_option('orbitinfo', 'Y'); //$this->add_option('orbitinfo_temp', 'Y'); } function render_msg($message = '') { $this->render('msg-top', array('message' => $message), true, 'admin'); } function render_err($message = '') { $this->render('err-top', array('message' => $message), true, 'admin'); } function redirect($location = '', $msgtype = '', $message = '') { $url = $location; if ($msgtype == "message") { $url .= '&' . $this->pre . 'updated=true'; } elseif ($msgtype == "error") { $url .= '&' . $this->pre . 'error=true'; } if (!empty($message)) { $url .= '&' . $this->pre . 'message=' . urlencode($message); } ?> <script type="text/javascript"> window.location = '<?php echo (empty($url)) ? get_option('home') : $url; ?>'; </script> <?php flush(); } function paginate($model = null, $fields = '*', $sub = null, $conditions = null, $searchterm = null, $per_page = 10, $order = array('modified', "DESC")) { global $wpdb; if (!empty($model)) { global $paginate; $paginate = $this->vendor('Paginate'); $paginate->table = $this->{$model}->table; $paginate->sub = (empty($sub)) ? $this->{$model}->controller : $sub; $paginate->fields = (empty($fields)) ? '*' : $fields; $paginate->where = (empty($conditions)) ? false : $conditions; $paginate->searchterm = (empty($searchterm)) ? false : $searchterm; $paginate->per_page = $per_page; $paginate->order = $order; $data = $paginate->start_paging($_GET[$this->pre . 'page']); if (!empty($data)) { $newdata = array(); foreach ($data as $record) { $newdata[] = $this->init_class($model, $record); } $data = array(); $data[$model] = $newdata; $data['Paginate'] = $paginate; } return $data; } return false; } function vendor($name = '', $folder = '') { if (!empty($name)) { $filename = 'class.' . strtolower($name) . '.php'; $filepath = rtrim(dirname(__FILE__), DS) . DS . 'vendors' . DS . $folder . ''; $filefull = $filepath . $filename; if (file_exists($filefull)) { require_once($filefull); $class = 'Satellite' . $name; if (${$name} = new $class) { return ${$name}; } } } return false; } function check_uploaddir() { if (!file_exists(SATL_UPLOAD_DIR)) { if (@mkdir(SATL_UPLOAD_DIR, 0777)) { @chmod(SATL_UPLOAD_DIR, 0755); return true; } else { $message = __('Uploads folder named "' . SATL_PLUGIN_NAME . '" cannot be created inside "' . SATL_UPLOAD_DIR, SATL_PLUGIN_NAME); $this->render_msg($message); } } return false; } function check_sgprodir() { $sgprodir = SATL_UPLOAD_DIR.'/../slideshow-gallery-pro/'; if (file_exists($sgprodir) && $this->is_empty_folder(SATL_UPLOAD_DIR)) { if ($this->is_empty_folder($sgprodir)) { return false; } $message = __('Transitioning from <strong>Slideshow Gallery Pro</strong>? <a href="admin.php?page=satellite-slides&method=copysgpro">Copy Files</a> from your previous custom galleries', SATL_PLUGIN_NAME); $this->render_msg($message); } return false; } function is_empty_folder($folder){ $c=0; if(is_dir($folder) ){ $files = opendir($folder); while ($file=readdir($files)){$c++;} if ($c>2){ return false; }else{ return true; } } } function add_action($action, $function = null, $priority = 10, $params = 1) { if (add_action($action, array($this, (empty($function)) ? $action : $function), $priority, $params)) { return true; } return false; } function add_filter($filter, $function = null, $priority = 10, $params = 1) { if (add_filter($filter, array($this, (empty($function)) ? $filter : $function), $priority, $params)) { return true; } return false; } function admin_scripts() { if (!empty($_GET['page']) && in_array($_GET['page'], (array) $this->sections)) { wp_enqueue_script('autosave'); if ($_GET['page'] == 'satellite') { wp_enqueue_script('common'); wp_enqueue_script('wp-lists'); wp_enqueue_script('postbox'); wp_enqueue_script('settings-editor', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/settings-editor.js', array('jquery'), SATL_VERSION); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } if ($_GET['page'] == "satellite-slides" && $_GET['method'] == "order") { wp_enqueue_script('jquery-ui-sortable'); } if ($_GET['page'] == "satellite-galleries") { wp_enqueue_script('plupload-all'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } wp_enqueue_scripts(); //wp_enqueue_script('jquery-ui-sortable'); add_thickbox(); } } function enqueue_scripts() { if ($this->get_option('ggljquery') == "Y") { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); } wp_enqueue_script('jquery'); if (SATL_PRO && ($this->get_option('preload') == 'Y')) { wp_register_script('satellite_preloader', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/pro/preloader.js'); wp_enqueue_script('satellite_preloader'); } if ($this->get_option('imagesbox') == "T") add_thickbox(); return true; } function plupload_admin_head() { //Thank you Krishna!! http://www.krishnakantsharma.com/ // place js config array for plupload $plupload_init = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'plupload-browse-button', // will be adjusted per uploader 'container' => 'plupload-upload-ui', // will be adjusted per uploader 'drop_element' => 'drag-drop-area', // will be adjusted per uploader 'file_data_name' => 'async-upload', // will be adjusted per uploader 'multiple_queues' => true, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url('admin-ajax.php'), 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), 'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')), 'multipart' => true, 'urlstream_upload' => true, 'multi_selection' => false, // will be added per uploader // additional post data to send to our ajax hook 'multipart_params' => array( '_ajax_nonce' => "", // will be added per uploader 'action' => 'plupload_action', // the ajax action name 'imgid' => 0 // will be added per uploader ) ); ?> <script type="text/javascript"> var base_plupload_config=<?php echo json_encode($plupload_init); ?>; </script> <?php } function g_plupload_action() { // check ajax noonce $imgid = $_POST["imgid"]; check_ajax_referer($imgid . 'pluploadan'); // handle file upload $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action')); // send the uploaded file url in response echo $status['url']; exit; } function plugin_base() { return rtrim(dirname(__FILE__), '/'); } function url() { return rtrim(WP_PLUGIN_URL, '/') . '/' . substr(preg_replace("/\\" . DS . "/si", "/", $this->plugin_base()), strlen(ABSPATH)); } function add_option($name = '', $value = '') { if (add_option($this->pre . $name, $value)) { return true; } return false; } function update_option($name = '', $value = '') { if (update_option($this->pre . $name, $value)) { return true; } return false; } function get_option($name = '', $stripslashes = true) { if ($option = get_option($this->pre . $name)) { if (@unserialize($option) !== false) { return unserialize($option); } if ($stripslashes == true) { $option = stripslashes_deep($option); } return $option; } return false; } function debug($var = array()) { if ($this->debugging) { echo '<pre>' . print_r($var, true) . '</pre>'; return true; } return false; } function check_table( $model = null ) { global $wpdb; if ( !empty($model) ) { if ( !empty($this->fields) && is_array($this->fields ) ) { if ( /* !$wpdb->get_var("SHOW TABLES LIKE '" . $this->table . "'") ||*/ $this->get_option($model.'db_version') != SATL_VERSION ) { $query = "CREATE TABLE " . $this->table . " (\n"; $c = 1; foreach ( $this->fields as $field => $attributes ) { if ( $field != "key" ) { $query .= "`" . $field . "` " . $attributes . ""; //$query .= "`".$field . "` " . $attributes ; } else { $query .= "" . $attributes . ""; } if ($c < count($this->fields)) { $query .= ",\n"; } $c++; } $query .= ");"; if (!empty($query)) { $this->table_query[] = $query; } if (SATL_PRO) { if ( class_exists( 'SatellitePremium' ) ) { $satlprem = new SatellitePremium; $satlprem->check_pro_dirs(); } } if (!empty($this->table_query)) { require_once(ABSPATH . 'wp-admin'.DS.'includes'.DS.'upgrade.php'); dbDelta($this->table_query, true); $this -> update_option($model.'db_version', SATL_VERSION); $this -> update_option('stldb_version', SATL_VERSION); error_log("Updated slideshow satellite databases"); } } else { //echo "this model db version: ".$this->get_option($model.'db_version'); $field_array = $this->get_fields($this->table); foreach ($this->fields as $field => $attributes) { if ($field != "key") { $this->add_field($this->table, $field, $attributes); } } } } } return false; } function get_fields($table = null) { global $wpdb; if (!empty($table)) { $fullname = $table; if (($tablefields = mysql_list_fields(DB_NAME, $fullname, $wpdb->dbh)) !== false) { $columns = mysql_num_fields($tablefields); $field_array = array(); for ($i = 0; $i < $columns; $i++) { $fieldname = mysql_field_name($tablefields, $i); $field_array[] = $fieldname; } return $field_array; } } return false; } function delete_field($table = '', $field = '') { global $wpdb; if (!empty($table)) { if (!empty($field)) { $query = "ALTER TABLE `" . $wpdb->prefix . "" . $table . "` DROP `" . $field . "`"; if ($wpdb->query($query)) { return false; } } } return false; } function change_field($table = '', $field = '', $newfield = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { if (!empty($newfield)) { $field_array = $this->get_fields($table); if (!in_array($field, $field_array)) { if ($this->add_field($table, $newfield)) { return true; } } else { $query = "ALTER TABLE `" . $table . "` CHANGE `" . $field . "` `" . $newfield . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function add_field($table = '', $field = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { $field_array = $this->get_fields($table); if (!empty($field_array)) { if (!in_array($field, $field_array)) { $query = "ALTER TABLE `" . $table . "` ADD `" . $field . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function render($file = '', $params = array(), $output = true, $folder = 'admin') { if (!empty($file)) { $filename = $file . '.php'; $filepath = $this->plugin_base() . DS . 'views' . DS . $folder . DS; $filefull = $filepath . $filename; if (file_exists($filefull)) { if (!empty($params)) { foreach ($params as $pkey => $pval) { ${$pkey} = $pval; } } if ($output == false) { ob_start(); } include($filefull); if ($output == false) { $data = ob_get_clean(); return $data; } else { flush(); return true; } } } return false; } /** * Add Settings link to plugins - code from GD Star Ratings */ function add_satl_settings_link($links, $file) { static $this_plugin; if (!$this_plugin) $this_plugin = plugin_basename(__FILE__); if ($file == $this_plugin) { $settings_link = '<a href="admin.php?page=satellite">' . __("Settings", SATL_PLUGIN_NAME) . '</a>'; array_unshift($links, $settings_link); } return $links; } } ?>
diegorojas/encontros.maracatu.org.br
wp-content/plugins/slideshow-satellite/slideshow-satellite-plugin.php
PHP
gpl-2.0
26,130
# -*- coding: UTF-8 -*- #/* # * Copyright (C) 2011 Ivo Brhel # * # * # * 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, 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; see the file COPYING. If not, write to # * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # * http://www.gnu.org/copyleft/gpl.html # * # */ import re,os,urllib,urllib2,cookielib import util,resolver from provider import ContentProvider class HejbejseContentProvider(ContentProvider): def __init__(self,username=None,password=None,filter=None): ContentProvider.__init__(self,'hejbejse.tv','http://www.kynychova-tv.cz/',username,password,filter) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())) urllib2.install_opener(opener) def capabilities(self): return ['resolve','categories','list'] def categories(self): page = util.parse_html('http://www.kynychova-tv.cz/index.php?id=5') result = [] for title,uri in [(x.h3.text,x.h3.a['href']) for x in page.select('div.entry5') if x.h3]: item = self.dir_item() item['title'] = title item['url'] = uri result.append(item) return result def list(self, url): url = self._url(url) page = util.parse_html(url) result = [] for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]: item = self.video_item() item['title'] = title item['url'] = uri result.append(item) return result def resolve(self,item,captcha_cb=None,select_cb=None): item = item.copy() url = self._url(item['url']) page = util.parse_html(url) result = [] data=str(page.select('div.entry3 > center')[0]) resolved = resolver.findstreams(data,['<iframe(.+?)src=[\"\'](?P<url>.+?)[\'\"]']) try: for i in resolved: item = self.video_item() item['title'] = i['name'] item['url'] = i['url'] item['quality'] = i['quality'] item['surl'] = i['surl'] result.append(item) except: print '===Unknown resolver===' if len(result)==1: return result[0] elif len(result) > 1 and select_cb: return select_cb(result)
kodi-czsk/plugin.video.hejbejse.tv
resources/lib/hejbejse.py
Python
gpl-2.0
2,611
# Wider Gravity Forms Stop Entries ## Download the latest release of this plugin from: https://wordpress.org/plugins/wider-gravity-forms-stop-entries/ or install from your WordPress Dashboard by searching for 'Wider Gravity Forms Stop Entires'. ### Selectively stop Gravity Forms entries being stored on your web server to comply with privacy and the GDPR. Gravity Forms is a wonderful plugin and each form submission is stored on your web server and is accessible through the admin area - which can be great if you have problems with the email address you have setup to receive form submissions. However, there is no easy way in the admin area to selectively stop entries being stored on your web server, it has to be done in code and is a bit of hassle - this plugin makes it easy to stop this potentially sensitive data being stored. Improve the privacy of your visitors form submissions and make your website comply with the GDPR - this plugin allows you to select individual Gravity Forms you have setup and stop these entries being stored through easy to use admin options. You will find the options under `Settings > Gravity Forms Stop Entries`. NOTE: Requires Gravity Forms v1.8 or newer!
We-Are-Wider/wider-gravity-forms-stop-entries
readme.md
Markdown
gpl-2.0
1,203
<?php /** * Template Name: Full Width Blog * * The template for displaying content in full width with no sidebars. * * * @package blogBox WordPress Theme * @copyright Copyright (c) 2012, Kevin Archibald * @license http://www.gnu.org/licenses/quick-guide-gplv3.html GNU Public License * @author Kevin Archibald <www.kevinsspace.ca/contact/> */ ?> <?php get_header(); ?> <div id="fullwidth"> <h2 class="fullwidth_blog_title"><?php the_title(); ?></h2> <div id="home1post"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post"> <div class="entry"> <?php the_content('Read more'); ?> </div> </div> <?php endwhile; else : endif; ?> </div> <div id="fullwidth_blog"> <?php $exclude_categories = blogBox_exclude_categories(); $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query(); $wp_query->query('cat='.$exclude_categories.'&paged='.$paged); if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php global $more; $more = 0; blogBox_post_format(); ?> </div> <?php endwhile; ?> <?php if(function_exists('wp_pagenavi')) { echo '<div class="postpagenav">'; wp_pagenavi(); echo '</div>'; } else { ?> <div class="postpagenav"> <div class="left"><?php next_posts_link(__('&lt;&lt; older entries','blogBox') ); ?></div> <div class="right"><?php previous_posts_link(__(' newer entries &gt;&gt;','blogBox') ); ?></div> <br/> </div> <?php } ?> <?php $wp_query = null; $wp_query = $temp;?> <?php else : ?> <?php endif; ?> <br/> </div> </div> <?php get_footer(); ?>
aliuwahab/saveghana
wp-content/themes/blogbox/page-full_width_blog.php
PHP
gpl-2.0
1,734
<?php /** * The template for displaying 404 pages (not found) * * @link https://codex.wordpress.org/Creating_an_Error_404_Page * * @package wapp */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <section class="error-404 not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'wapp' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'wapp' ); ?></p> <?php get_search_form(); the_widget( 'WP_Widget_Recent_Posts' ); // Only show the widget if site has multiple categories. if ( wapp_categorized_blog() ) : ?> <div class="widget widget_categories"> <h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'wapp' ); ?></h2> <ul> <?php wp_list_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'show_count' => 1, 'title_li' => '', 'number' => 10, ) ); ?> </ul> </div><!-- .widget --> <?php endif; /* translators: %1$s: smiley */ $archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'wapp' ), convert_smilies( ':)' ) ) . '</p>'; the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" ); the_widget( 'WP_Widget_Tag_Cloud' ); ?> </div><!-- .page-content --> </section><!-- .error-404 --> </main><!-- #main --> </div><!-- #primary --> <?php get_footer();
Headlab/wapp
404.php
PHP
gpl-2.0
1,741
-- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 16, 2011 at 10:05 AM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `sqlparser` -- -- -------------------------------------------------------- -- -- Table structure for table `articles` -- CREATE TABLE IF NOT EXISTS `articles` ( `article_id` int(10) NOT NULL AUTO_INCREMENT, `article_format_id` int(10) NOT NULL, `article_title` varchar(150) NOT NULL, `article_body` text NOT NULL, `article_date` date NOT NULL, `article_cat_id` int(10) NOT NULL, `article_active` tinyint(1) NOT NULL, `article_user_id` int(10) NOT NULL, PRIMARY KEY (`article_id`), KEY `article_format_id` (`article_format_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Dumping data for table `articles` -- INSERT INTO `articles` (`article_id`, `article_format_id`, `article_title`, `article_body`, `article_date`, `article_cat_id`, `article_active`, `article_user_id`) VALUES (1, 2, 'Tinie Tempah, Arcade Fire score Brits doubles', 'Tinie Tempah and Arcade Fire were the major winners at tonight''s Brit Awards, taking home two trophies apiece.', '2011-02-15', 3, 1, 1), (2, 1, 'Kelly Osbourne ''defends Leona Lewis''', 'Kelly Osbourne has revealed that she doesn''t understand why Leona Lewis is being judged because of her new style.', '2011-02-16', 2, 1, 0), (3, 2, 'Adele Storms download chart', 'Adele has stormed the singles chart following her performance at the Brit Awards. The singer, who sang a moving rendition of ''Someone Like You'', saw the track rocket up the download chart immediately after the gig.', '2011-01-16', 2, 1, 2); -- -------------------------------------------------------- -- -- Table structure for table `article_categories` -- CREATE TABLE IF NOT EXISTS `article_categories` ( `article_id` int(10) NOT NULL, `category_id` int(10) NOT NULL, KEY `article_id` (`article_id`,`category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `article_categories` -- INSERT INTO `article_categories` (`article_id`, `category_id`) VALUES (1, 2), (2, 1), (2, 2), (3, 2); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `category_id` int(10) NOT NULL AUTO_INCREMENT, `category_title` varchar(150) NOT NULL, PRIMARY KEY (`category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`category_id`, `category_title`) VALUES (1, 'Showbiz'), (2, 'Music'), (3, 'Hotels'); -- -------------------------------------------------------- -- -- Table structure for table `formats` -- CREATE TABLE IF NOT EXISTS `formats` ( `format_id` int(10) NOT NULL AUTO_INCREMENT, `format_title` varchar(150) NOT NULL, PRIMARY KEY (`format_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `formats` -- INSERT INTO `formats` (`format_id`, `format_title`) VALUES (1, 'Video'), (2, 'TV Show'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(10) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `user_name`) VALUES (1, 'Jason'), (2, 'Paul');
digitalspy/SQL-Parser
tests/database.sql
SQL
gpl-2.0
3,809
# # bzr support for dpkg-source # # Copyright © 2007 Colin Watson <[email protected]>. # Based on Dpkg::Source::Package::V3_0::git, which is: # Copyright © 2007 Joey Hess <[email protected]>. # Copyright © 2008 Frank Lichtenheld <[email protected]> # # 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 <https://www.gnu.org/licenses/>. package Dpkg::Source::Package::V3::Bzr; use strict; use warnings; our $VERSION = '0.01'; use Cwd; use File::Basename; use File::Find; use File::Temp qw(tempdir); use Dpkg::Gettext; use Dpkg::Compression; use Dpkg::ErrorHandling; use Dpkg::Source::Archive; use Dpkg::Exit qw(push_exit_handler pop_exit_handler); use Dpkg::Source::Functions qw(erasedir); use parent qw(Dpkg::Source::Package); our $CURRENT_MINOR_VERSION = '0'; sub import { foreach my $dir (split(/:/, $ENV{PATH})) { if (-x "$dir/bzr") { return 1; } } error(g_('cannot unpack bzr-format source package because ' . 'bzr is not in the PATH')); } sub sanity_check { my $srcdir = shift; if (! -d "$srcdir/.bzr") { error(g_('source directory is not the top directory of a bzr repository (%s/.bzr not present), but Format bzr was specified'), $srcdir); } # Symlinks from .bzr to outside could cause unpack failures, or # point to files they shouldn't, so check for and don't allow. if (-l "$srcdir/.bzr") { error(g_('%s is a symlink'), "$srcdir/.bzr"); } my $abs_srcdir = Cwd::abs_path($srcdir); find(sub { if (-l) { if (Cwd::abs_path(readlink) !~ /^\Q$abs_srcdir\E(?:\/|$)/) { error(g_('%s is a symlink to outside %s'), $File::Find::name, $srcdir); } } }, "$srcdir/.bzr"); return 1; } sub can_build { my ($self, $dir) = @_; return (0, g_("doesn't contain a bzr repository")) unless -d "$dir/.bzr"; return 1; } sub do_build { my ($self, $dir) = @_; my @argv = @{$self->{options}{ARGV}}; # TODO: warn here? #my @tar_ignore = map { "--exclude=$_" } @{$self->{options}{tar_ignore}}; my $diff_ignore_regex = $self->{options}{diff_ignore_regex}; $dir =~ s{/+$}{}; # Strip trailing / my ($dirname, $updir) = fileparse($dir); if (scalar(@argv)) { usageerr(g_("-b takes only one parameter with format '%s'"), $self->{fields}{'Format'}); } my $sourcepackage = $self->{fields}{'Source'}; my $basenamerev = $self->get_basename(1); my $basename = $self->get_basename(); my $basedirname = $basename; $basedirname =~ s/_/-/; sanity_check($dir); my $old_cwd = getcwd(); chdir $dir or syserr(g_("unable to chdir to '%s'"), $dir); local $_; # Check for uncommitted files. # To support dpkg-source -i, remove any ignored files from the # output of bzr status. open(my $bzr_status_fh, '-|', 'bzr', 'status') or subprocerr('bzr status'); my @files; while (<$bzr_status_fh>) { chomp; next unless s/^ +//; if (! length $diff_ignore_regex || ! m/$diff_ignore_regex/o) { push @files, $_; } } close($bzr_status_fh) or syserr(g_('bzr status exited nonzero')); if (@files) { error(g_('uncommitted, not-ignored changes in working directory: %s'), join(' ', @files)); } chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); my $tmp = tempdir("$dirname.bzr.XXXXXX", DIR => $updir); push_exit_handler(sub { erasedir($tmp) }); my $tardir = "$tmp/$dirname"; system('bzr', 'branch', $dir, $tardir); subprocerr("bzr branch $dir $tardir") if $?; # Remove the working tree. system('bzr', 'remove-tree', $tardir); subprocerr("bzr remove-tree $tardir") if $?; # Some branch metadata files are unhelpful. unlink("$tardir/.bzr/branch/branch-name", "$tardir/.bzr/branch/parent"); # Create the tar file my $debianfile = "$basenamerev.bzr.tar." . $self->{options}{comp_ext}; info(g_('building %s in %s'), $sourcepackage, $debianfile); my $tar = Dpkg::Source::Archive->new(filename => $debianfile, compression => $self->{options}{compression}, compression_level => $self->{options}{comp_level}); $tar->create(chdir => $tmp); $tar->add_directory($dirname); $tar->finish(); erasedir($tmp); pop_exit_handler(); $self->add_file($debianfile); } # Called after a tarball is unpacked, to check out the working copy. sub do_extract { my ($self, $newdirectory) = @_; my $fields = $self->{fields}; my $dscdir = $self->{basedir}; my $basename = $self->get_basename(); my $basenamerev = $self->get_basename(1); my @files = $self->get_files(); if (@files > 1) { error(g_('format v3.0 uses only one source file')); } my $tarfile = $files[0]; my $comp_ext_regex = compression_get_file_extension_regex(); if ($tarfile !~ /^\Q$basenamerev\E\.bzr\.tar\.$comp_ext_regex$/) { error(g_('expected %s, got %s'), "$basenamerev.bzr.tar.$comp_ext_regex", $tarfile); } if ($self->{options}{no_overwrite_dir} and -e $newdirectory) { error(g_('unpack target exists: %s'), $newdirectory); } else { erasedir($newdirectory); } # Extract main tarball info(g_('unpacking %s'), $tarfile); my $tar = Dpkg::Source::Archive->new(filename => "$dscdir$tarfile"); $tar->extract($newdirectory); sanity_check($newdirectory); my $old_cwd = getcwd(); chdir($newdirectory) or syserr(g_("unable to chdir to '%s'"), $newdirectory); # Reconstitute the working tree. system('bzr', 'checkout'); subprocerr('bzr checkout') if $?; chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); } 1;
CharizTeam/dpkg
scripts/Dpkg/Source/Package/V3/Bzr.pm
Perl
gpl-2.0
6,490
/**************************************************************************** * * $Id: vpHinkley.cpp 4056 2013-01-05 13:04:42Z fspindle $ * * This file is part of the ViSP software. * Copyright (C) 2005 - 2013 by INRIA. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact INRIA about acquiring a ViSP Professional * Edition License. * * See http://www.irisa.fr/lagadic/visp/visp.html for more information. * * This software was developed at: * INRIA Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * http://www.irisa.fr/lagadic * * If you have questions regarding the use of this file, please contact * INRIA at [email protected] * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * Description: * Hinkley's cumulative sum test implementation. * * Authors: * Fabien Spindler * *****************************************************************************/ /*! \file vpHinkley.cpp \brief Definition of the vpHinkley class corresponding to the Hinkley's cumulative sum test. */ #include <visp/vpHinkley.h> #include <visp/vpDebug.h> #include <visp/vpIoTools.h> #include <visp/vpMath.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <cmath> // std::fabs #include <limits> // numeric_limits /* VP_DEBUG_MODE fixed by configure: 1: 2: 3: Print data */ /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ to default values. By default \f$ \delta = 0.2 \f$ and \f$ \alpha = 0.2\f$. Use setDelta() and setAlpha() to modify these values. */ vpHinkley::vpHinkley() { init(); setAlpha(0.2); setDelta(0.2); } /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ vpHinkley::vpHinkley(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ void vpHinkley::init(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Destructor. */ vpHinkley::~vpHinkley() { } /*! Initialise the Hinkley's test by setting the mean signal value \f$m_0\f$ to zero as well as \f$S_k, M_k, T_k, N_k\f$. */ void vpHinkley::init() { nsignal = 0; mean = 0.0; Sk = 0; Mk = 0; Tk = 0; Nk = 0; } /*! Set the value of \f$\delta\f$, the jump minimal magnetude that we want to detect. \sa setAlpha() */ void vpHinkley::setDelta(double delta) { dmin2 = delta / 2; } /*! Set the value of \f$\alpha\f$, a predefined threshold. \sa setDelta() */ void vpHinkley::setAlpha(double alpha) { this->alpha = alpha; } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeMk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >=2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == downwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeTk(signal); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Tk: " << Tk << " Nk: " << Nk; // teste si les variables cumulées excèdent le seuil if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upWardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == upwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Tk = 0; Nk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeTk(signal); computeMk(); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk << " Tk: " << Tk << " Nk: " << Nk << std::endl; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; else if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if ((jump == upwardJump) || (jump == downwardJump)) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; Tk = 0; Nk = 0; nsignal = 0; // Debut modif FS le 03/09/2003 mean = signal; // Fin modif FS le 03/09/2003 } return (jump); } /*! Compute the mean value \f$m_0\f$ of the signal. The mean value must be computed before the jump is estimated on-line. \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeMean(double signal) { // Debut modif FS le 03/09/2003 // Lors d'une chute ou d'une remontée lente du signal, pariculièrement // après un saut, la moyenne a tendance à "dériver". Pour réduire ces // dérives de la moyenne, elle n'est remise à jour avec la valeur // courante du signal que si un début de saut potentiel n'est pas détecté. //if ( ((Mk-Sk) == 0) && ((Tk-Nk) == 0) ) if ( ( std::fabs(Mk-Sk) <= std::fabs(vpMath::maximum(Mk,Sk))*std::numeric_limits<double>::epsilon() ) && ( std::fabs(Tk-Nk) <= std::fabs(vpMath::maximum(Tk,Nk))*std::numeric_limits<double>::epsilon() ) ) // Fin modif FS le 03/09/2003 // Mise a jour de la moyenne. mean = (mean * (nsignal - 1) + signal) / (nsignal); } /*! Compute \f$S_k = \sum_{t=0}^{k} (s(t) - m_0 + \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeSk(double signal) { // Calcul des variables cumulées Sk += signal - mean + dmin2; } /*! Compute \f$M_k\f$, the maximum value of \f$S_k\f$. */ void vpHinkley::computeMk() { if (Sk > Mk) Mk = Sk; } /*! Compute \f$T_k = \sum_{t=0}^{k} (s(t) - m_0 - \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeTk(double signal) { // Calcul des variables cumulées Tk += signal - mean - dmin2; } /*! Compute \f$N_k\f$, the minimum value of \f$T_k\f$. */ void vpHinkley::computeNk() { if (Tk < Nk) Nk = Tk; } void vpHinkley::print(vpHinkley::vpHinkleyJumpType jump) { switch(jump) { case noJump : std::cout << " No jump detected " << std::endl ; break ; case downwardJump : std::cout << " Jump downward detected " << std::endl ; break ; case upwardJump : std::cout << " Jump upward detected " << std::endl ; break ; default: std::cout << " Jump detected " << std::endl ; break ; } }
thomas-moulard/visp-deb
src/math/misc/vpHinkley.cpp
C++
gpl-2.0
9,567
<?php /** * The template for displaying all single posts. * * @package srh_framework */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php the_post_navigation(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
jamiebrwr/srh-theme-framework
single.php
PHP
gpl-2.0
678
//: containers/MapDataTest.java package course.containers; /* Added by Eclipse.py */ import java.util.*; import net.mindview.util.*; import static net.mindview.util.Print.*; class Letters implements Generator<Pair<Integer,String>>, Iterable<Integer> { private int size = 9; private int number = 1; private char letter = 'A'; public Pair<Integer,String> next() { return new Pair<Integer,String>( number++, "" + letter++); } public Iterator<Integer> iterator() { return new Iterator<Integer>() { public Integer next() { return number++; } public boolean hasNext() { return number < size; } public void remove() { throw new UnsupportedOperationException(); } }; } } public class MapDataTest { public static void main(String[] args) { // Pair Generator: print(MapData.map(new Letters(), 11)); // Two separate generators: print(MapData.map(new CountingGenerator.Character(), new RandomGenerator.String(3), 8)); // A key Generator and a single value: print(MapData.map(new CountingGenerator.Character(), "Value", 6)); // An Iterable and a value Generator: print(MapData.map(new Letters(), new RandomGenerator.String(3))); // An Iterable and a single value: print(MapData.map(new Letters(), "Pop")); } } /* Output: {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K} {a=YNz, b=brn, c=yGc, d=FOW, e=ZnT, f=cQr, g=Gse, h=GZM} {a=Value, b=Value, c=Value, d=Value, e=Value, f=Value} {1=mJM, 2=RoE, 3=suE, 4=cUO, 5=neO, 6=EdL, 7=smw, 8=HLG} {1=Pop, 2=Pop, 3=Pop, 4=Pop, 5=Pop, 6=Pop, 7=Pop, 8=Pop} *///:~
fengzhongdege/TIJ4
src/main/java/course/containers/MapDataTest.java
Java
gpl-2.0
1,677
/**************************************************************************** * * Copyright (c) 2006 Dave Hylands <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. * ****************************************************************************/ /** * * @file Hardware.h * * @brief Defines all of the hardware definitions for the chip. * ****************************************************************************/ #if !defined( HARDWARE_H ) #define HARDWARE_H /**< Include Guard */ /* ---- Include Files ---------------------------------------------------- */ #include "Config.h" #include <avr/io.h> //-------------------------------------------------------------------------- // LED Constants #define RED_LED_PIN 4 #define RED_LED_MASK ( 1 << RED_LED_PIN ) #define RED_LED_DDR DDRG #define RED_LED_PORT PORTG #define BLUE_LED_PIN 3 #define BLUE_LED_MASK ( 1 << BLUE_LED_PIN ) #define BLUE_LED_DDR DDRG #define BLUE_LED_PORT PORTG #define YELLOW_LED_PIN 4 #define YELLOW_LED_MASK ( 1 << YELLOW_LED_PIN ) #define YELLOW_LED_DDR DDRB #define YELLOW_LED_PORT PORTB //-------------------------------------------------------------------------- // Some convenience macros to turn the LEDs on/off. // // Usage: LED_ON( BLUE ); // // to turn on the blue LED. // // Note: Setting the pin to 0 turns the LED on. #define LED_ON( color ) do { color ## _LED_PORT &= ~color ## _LED_MASK; } while (0) #define LED_OFF( color ) do { color ## _LED_PORT |= color ## _LED_MASK; } while (0) //-------------------------------------------------------------------------- // Port registers. // // Note: For input ports, writing a 1 to the PORT register casues an internal // pullup resistor to be activated. This feature also requires the // PUD bit to be set in the SFIOR register. // // For the DDR pins, 0 = input, 1 = output // Port A if the one that's just pads on the bottom of the board #define PORTA_INIT 0xFF #define DDRA_INIT 0x00 // Port B has 3 PWM lines, and SPI. Pin 4 is connected to the Yellow LED // // 7 - OC2 ATM_PWM1C // 6 - OC1B ATM_PWM1B // 5 - OC1A ATM_PWM1A // 4 - OC0 PB4 (Yellow LED) // 3 - MISO ATM_MISO // 2 - MOSI ATM_MOSI // 1 - SCK ATM_SCK // 0 - SS ATM_SS #define PORTB_INIT 0xFF // Enable pullups for inputs, Yellow LED off #define DDRB_INIT YELLOW_LED_MASK // Port C is available on the headers as 8 I/O lines. We'll assume all inputs // for now. #define PORTC_INIT 0xFF // enable pullups for all inputs #define DDRC_INIT 0x00 // Port D // // 7 - T2 ATM_T2 // 6 - T1 ATM_T1 // 5 - PD5 ATM_PD5 // 4 - IC1 ATM_IC1 // 3 - INT3 ATM_TX1 // 2 - INT2 ATM_RX1 // 1 - INT1 ATM_SDA // 0 - INT0 ATM_SCL #define PORTD_INIT 0xFF // enable pullups for all inputs #define DDRD_INIT 0x00 // Port E // // 7 - INT7 ATM_INT7 // 6 - INT6 ATM_INT6 // 5 - OC3C ATM_PWM3C // 4 - OC3B ATM_PWM3B // 3 - OC3A ATM_PWM3A // 2 - PE2 ATM_IRQ Used to interrupt gumstix // 1 - TXD ATM_TX0 // 0 - RXD ATM_RX0 #define PORTE_INIT 0xFF // enable pullups for all inputs #define DDRE_INIT 0x00 // Port F - A/D lines - could be used as GPIO // // We disable all pullups by default so they don't mess with the A/D #define PORTF_INIT 0x00 // disable pullups for A/D channels #define DDRF_INIT 0x00 // Port G // // 7 - N/A // 6 - N/A // 5 - N/A // 4 - TOSC1 ATM_PG4 - Red LED // 3 - TOSC2 ATM_PG3 - Blue LED // 2 - ALE ATM_PG2 // 1 - /RD ATM_PG1 // 0 - /WR ATM_PG0 #define PORTG_INIT 0xFF // Enable pullups for inputs, LEDs off #define DDRG_INIT ( RED_LED_MASK | BLUE_LED_MASK ) // Make LEDs outputs //-------------------------------------------------------------------------- // ASSR - Asynchronous Status Register // // TOSC1 & TOSC2 are connected to the Red/Blue LEDs so we need to set // AS0 to 0. AS0 is the only writable bit. #define ASSR_INIT 0x00 //-------------------------------------------------------------------------- // ADC Settings #define ADC_PRESCALAR_2 (( 0 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_4 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_8 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_16 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_32 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_64 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_128 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADCSR_INIT (( 1 << ADEN ) | ( 1 << ADSC ) | ADC_PRESCALAR_128 ) #define ADMUX_REF_AREF (( 0 << REFS1 ) | ( 0 << REFS0 )) #define ADMUX_REF_AVCC (( 0 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_REF_INTERNAL (( 1 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_INIT ADMUX_REF_AVCC //-------------------------------------------------------------------------- // UART settings #define UART0_BAUD_RATE 38400 #define UART1_BAUD_RATE 38400 #define UART_DATA_BIT_8 (( 1 << UCSZ1 ) | ( 1 << UCSZ0 )) #define UART_PARITY_NONE (( 0 << UPM1 ) | ( 0 << UPM0 )) #define UART_STOP_BIT_1 ( 0 << USBS ) #define UBRR0_INIT (( CFG_CPU_CLOCK / 16 / UART0_BAUD_RATE ) - 1 ) #define UBRR1_INIT (( CFG_CPU_CLOCK / 16 / UART1_BAUD_RATE ) - 1 ) #define UCSR0A_INIT 0 #define UCSR0B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR0C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) #define UCSR1A_INIT 0 #define UCSR1B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR1C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) /* ---- Variable Externs ------------------------------------------------- */ /** * Description of variable. */ /* ---- Function Prototypes ---------------------------------------------- */ void InitHardware( void ); /** @} */ #endif // HARDWARE_H
ptLong/linux-code-collections
avr/Flash-LED-robostix/Hardware.h
C
gpl-2.0
6,386
<?php class Listify_Template_Page_Templates { public function __construct() { add_filter( 'theme_page_templates', array( $this, 'visual_composer' ) ); } public function visual_composer( $page_templates ) { if ( listify_has_integration( 'visual-composer' ) ) { return $page_templates; } unset( $page_templates[ 'page-templates/template-home-vc.php' ] ); return $page_templates; } }
jfrankel-13/findlancer
wp-content/themes/listify/inc/template/class-template-page-templates.php
PHP
gpl-2.0
404
import socket import threading import time def tcplink(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start()
lovekun/Notebook
python/chatroomServer.py
Python
gpl-2.0
654
import os import sys import shutil import binascii import traceback import subprocess from win32com.client import Dispatch LAUNCHER_PATH = "C:\\Program Files\\Augur" DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur") PASSFILE = os.path.join(DATA_PATH, "password.txt") if getattr(sys, 'frozen', False): # we are running in a |PyInstaller| bundle BASEDIR = sys._MEIPASS else: # we are running in a normal Python environment BASEDIR = os.path.dirname(os.path.abspath(__file__)) GETH_EXE = os.path.join(BASEDIR, 'geth.exe') LAUNCHER_EXE = os.path.join(BASEDIR, 'augurlauncher.exe') def main(): # first make all the appropriate directories print("Making directories...") for d in LAUNCHER_PATH, DATA_PATH: print("Creating", d, end=" ", flush=True) os.mkdir(d) print("Success!") print("Generating random password file...", end=" ", flush=True) # then generate the password password = binascii.b2a_hex(os.urandom(32)) passfile = open(PASSFILE, "w") passfile.write(password.decode('ascii')) passfile.close() print("Success!") # Then copy ".exe"s to the launcher path exes = GETH_EXE, LAUNCHER_EXE results = [] for exe in exes: print("Copying", os.path.basename(exe), "to", LAUNCHER_PATH, "...", end=" ", flush=True) results.append(shutil.copy(exe, LAUNCHER_PATH)) print("Sucess!") print("Creating node account...", end=" ", flush=True) # create account on node p = subprocess.Popen([results[0], "--password", PASSFILE, "account", "new"]) p.wait() print("Success!") print("Creating shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") wDir = LAUNCHER_PATH shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(shortcut_path) shortcut.Targetpath = results[1] shortcut.WorkingDirectory = wDir shortcut.IconLocation = results[1] shortcut.save() print("Success!") def uninstall(): paths = LAUNCHER_PATH, DATA_PATH for p in paths: print("Deleting", p, "...", end=" ", flush=True) shutil.rmtree(p) print("Success!") print("Removing desktop shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") os.remove(shortcut_path) print("Success!") if __name__ == '__main__': try: if len(sys.argv) == 2 and sys.argv[1] == 'uninstall': uninstall() elif len(sys.argv) == 1: main() else: assert len(sys.argv) <= 2, "wrong number of arguements!" except Exception as exc: traceback.print_exc() finally: os.system("pause") sys.exit(0)
AugurProject/augur-launcher
Augur Installer.py
Python
gpl-2.0
2,932
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
ancho85/pylint-playero-plugin
tests/test_funcs.py
Python
gpl-2.0
3,850
<div class="twelve columns alpha"> <h3 class="headline">Descripción del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <p>O Parque Tecnológico Itaipu (conocido como PTI) tiene un sitio web que proporciona mucha información sobre las actividades y los proyectos de PTI. <p>PTI ha identificado algunos problemas en su sitio, y presentado estas demandas a Celtab, para resolver estos problemas, así como mejorar el sitio en general, completamente en Drupal. <p>Por lo tanto, al ser necesario el desarrollo de algunas mejoras en Drupal y crear "plugins" para ayudar a la publicación de noticias y edición.</p> <p><strong>Investigadores:</strong> Cristhian Urunaga; Mario Villagra</p> </div> <!-- Job Description --> <div class="four columns omega"> <h3 class="headline">Detalles del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <ul style="margin: 2px 0 18px 0;" class="list-3"> <li>PHP</li> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>CMS Drupal 7.x</li> </ul> <div class="clearfix"></div> </div>
IngCarlosColman/SiteCeltab
CONTENIDOS/espanol/Proyectos/Mejoras del Sitio PTI.php
PHP
gpl-2.0
1,129
var express = require('express'), formidable = require('formidable'), imgur = require('imgur'), fs = require('fs'), url = require('url'), bodyParser = require('body-parser'), router = express.Router(), uuid = require('node-uuid'), db = require('../lib/database'), tools = require('../lib/functions'); var connection = db.connectdb(); router.post('/upload', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); var id = tools.makeid(); var owner = uuid.v1(); var form = new formidable.IncomingForm(), files = [], fields = []; form.uploadDir = 'tmp/'; form.on('field', function(field, value) { fields.push(value); }); form.on('file', function(field, file) { files.push(file); }); form.on('end', function() { res.end('http://' + req.headers.host + '/' + id); if (fields[0]) { owner = fields[0]; } files.forEach(function(file) { imgur.uploadFile(file.path) .then(function(json) { fs.unlink(file.path); connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')"); }) .catch(function(err) { fs.unlink(file.path); console.log(err); }); }); }); form.parse(req); }); router.get('/image/:id', function(req, res) { var id = req.params.id; connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) { if (!row[0]) { res.json({ status: false }); } else { res.json({ status: true, direct: row[0].direct, timestamp: row[0].timestamp }); } }); }); router.get('/check', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); res.end('Server Online'); }); module.exports = router;
luigiplr/imgSnap-backend
routes/api.js
JavaScript
gpl-2.0
2,487
# -*- coding: utf-8 -*- def outfit(): collection = [] for _ in range(0, 5): collection.append("Item{}".format(_)) return { "data": collection, } api = [ ('/outfit', 'outfit', outfit), ]
Drachenfels/Game-yolo-archer
server/api/outfits.py
Python
gpl-2.0
228
var UniteNivoPro = new function() { var t = this; var containerID = "slider_container"; var container, arrow_left, arrow_right, bullets_container; var caption_back, caption_text; var bulletsRelativeY = ""; /** * show slider view error, hide all the elements */ t.showSliderViewError = function(errorMessage) { jQuery("#config-document").hide(); UniteAdmin.showErrorMessage(errorMessage); } /** * main init of the object */ var init = function() { container = jQuery("#" + containerID); arrow_left = jQuery("#arrow_left"); arrow_right = jQuery("#arrow_right"); bullets_container = jQuery("#bullets_wrapper"); caption_back = jQuery("#caption_back"); caption_text = jQuery("#caption_text"); UniteAdmin.hideSystemMessageDelay(); } /** * init visual form width */ t.initSliderView = function() { init(); //init the object - must call //update menu event jQuery("#visual").click(function() { setTimeout("UniteNivoPro.initAfterDelay()", 300); }); //update visual from fields updateFromFields(); initSliderEvents(); initVisualTabs(); //update arrows fields ) if not set setTimeout("UniteNivoPro.initAfterDelay()", 1000); } /* ===================== Item View Section =================== */ /** * init item view */ t.initItemView = function() { //operate on slide image change var obj = document.getElementById("jform_params_image"); obj.addEvent('change', function() { var urlImage = g_urlRoot + this.value; //trace(urlImage); jQuery("#image_preview_wrapper").show().css("background-image", "url(\"" + urlImage + "\")"); }); } /* ===================== Item View End =================== */ /** * on visual tab display event. update some fields */ t.onVisualDisplay = function() { updateArrowPosFields(); bulletsAlignCenter(); } /** * init elements after delay */ t.initAfterDelay = function() { updateArrowPosFields(); initBullets(); } /** * align the bullets to center */ var bulletsAlignCenter = function() { var align = jQuery("#jform_visual_bullets_align").val(); if (align != "center") return(true); var data = getElementsData(); var bulletsX = Math.round((data.sliderWidth - data.bulletsWidth) / 2); bullets_container.css("left", bulletsX + "px"); updateBulletFields("center"); } /** * set bullets position by relative. */ var bulletsSetRelativeYPos = function() { var data = getElementsData(); if (data.bulletsWidth == 0) return(true); if (bulletsRelativeY == "") return(true); var bulletsPosY = data.sliderHeight + bulletsRelativeY; bullets_container.css("top", bulletsPosY + "px"); updateBulletFields("relative"); } /** * do some actions on bullets align change */ var onBulletsAlignChange = function(align) { switch (align) { case "center": bullets_container.draggable("option", "axis", "y"); bulletsAlignCenter(); UniteAdmin.hideFormField("jform_visual_bullets_xleft"); UniteAdmin.hideFormField("jform_visual_bullets_xright"); break; case "left": bullets_container.draggable("option", "axis", ""); UniteAdmin.showFormField("jform_visual_bullets_xleft"); UniteAdmin.hideFormField("jform_visual_bullets_xright"); jQuery("#jform_visual_bullets_xleft-lbl").css('display', 'inline'); break; case "right": bullets_container.draggable("option", "axis", ""); UniteAdmin.hideFormField("jform_visual_bullets_xleft"); UniteAdmin.showFormField("jform_visual_bullets_xright"); jQuery("#jform_visual_bullets_xright-lbl").css('display', 'inline'); break; } } /** * on bullets drag event, update fields. */ var onBulletsDrag = function() { updateBulletFields("drag"); } /** * update relative y */ var updateBulletsRelativeY = function() { var data = getElementsData(); bulletsRelativeY = data.bulletsY - data.sliderHeight; } /** * init the bullets position */ var initBullets = function() { var selectorBulletsAlign = "#jform_visual_bullets_align"; var selectorBulletReverse = "#jform_visual_reverse_bullets"; var align = jQuery(selectorBulletsAlign).val(); //set bullets draggable var drag_options = {drag: onBulletsDrag}; if (align == "center") { bulletsAlignCenter(); //set draggable only y axis drag_options.axis = "y"; } jQuery(selectorBulletReverse).change(function() { reverse_bullets(); }) //set select event jQuery(selectorBulletsAlign).change(function() { onBulletsAlignChange(this.value); }); //set draggable event bullets_container.draggable(drag_options); //show the bullets (if hidden) bullets_container.removeClass("invisible"); updateBulletsRelativeY(); } /** * show some tab, set it selecetd class, and hide the others. */ var showVisualTab = function(linkID) { var link = jQuery("#" + linkID); if (!link.length) return(false); var tabID = link.data("tab"); //set togler selected jQuery("#tabs_visual li a").removeClass("selected"); link.addClass("selected"); //show panel jQuery(".visual_panel").removeClass("hidden").hide(); jQuery(tabID).show(); } /** * init visual tabs functionality */ var initVisualTabs = function() { var hash = location.hash; if (hash) { var linkID = hash.replace("#tab-", ""); showVisualTab(linkID); } //set event jQuery("#tabs_visual li a").click(function() { showVisualTab(this.id); }); } /** * on slider resize event. update all elements and fields accordingly */ var onSliderResize = function(event, ui) { //update fields widht / height if (event) { //only if came from event jQuery("#jform_visual_width").val(container.width()); jQuery("#jform_visual_height").val(container.height()); } checkArrowsConnection("arrow_left"); bulletsSetRelativeYPos(); bulletsAlignCenter(); } /** * init slider view onchange events */ var initSliderEvents = function() { //set fields onchange events var fields = "#visual_wrapper input"; jQuery(fields).blur(updateFromFields).click(updateFromFields); jQuery(fields).keypress(function(event) { if (event.keyCode == 13) updateFromFields(this); }); jQuery("#visual_wrapper select").change(updateFromFields); //set resizible event: container.resizable({resize: onSliderResize}); //set on color picker move event: UniteAdmin.onColorPickerMove(function() { updateFromFields(); }); //set arrows draggable jQuery("#arrow_left,#arrow_right").draggable({ drag: onArrowsDrag }); jQuery("#arrows_gocenter").click(arrowsToCenter); } /** * get all element sizes and positions. */ var getElementsData = function() { var data = {}; //slider data data.sliderWidth = Number(jQuery("#jform_visual_width").val()); data.sliderHeight = Number(jQuery("#jform_visual_height").val()); //arrows data var arrowLeftPos = arrow_left.position(); var arrowRightPos = arrow_right.position(); data.arrowLeftX = Math.round(arrowLeftPos.left); data.arrowLeftY = Math.round(arrowLeftPos.top); data.arrowRightX = Math.round(arrowRightPos.left); data.arrowRightY = Math.round(arrowRightPos.top); data.arrowLeftWidth = arrow_left.width(); data.arrowLeftHeight = arrow_left.height(); data.arrowRightWidth = arrow_right.width(); data.arrowRightHeight = arrow_right.height(); //bullets data: var bulletsPos = bullets_container.position(); data.bulletsWidth = bullets_container.width(); data.bulletsHeight = bullets_container.height(); data.bulletsX = Math.round(bulletsPos.left); data.bulletsY = Math.round(bulletsPos.top); return(data); } /** * get the arrows to center of the banner (y axes) */ var arrowsToCenter = function() { var data = getElementsData(); var arrowsNewY = Math.round(data.sliderHeight - data.arrowLeftHeight) / 2; arrow_right.css("top", arrowsNewY + "px"); arrow_left.css("top", arrowsNewY + "px"); //update position fields on the panel updateArrowPosFields(); } /** * check arrows connection, and */ var checkArrowsConnection = function(arrowID) { var freeDrag = jQuery("#jform_visual_arrows_free_drag").is(":checked"); if (freeDrag == true) { updateArrowPosFields(); return(false); } var data = getElementsData(); if (arrowID == "arrow_left") { //left arrow is main. var arrowRightNewX = data.sliderWidth - data.arrowLeftX - data.arrowRightWidth; //set right arrow position arrow_right.css({"top": data.arrowLeftY + "px", "left": arrowRightNewX + "px"}); } else if (arrowID == "arrow_right") { //right arrow is main var arrowLeftNewX = data.sliderWidth - data.arrowRightX - data.arrowRightWidth; //set left arrow position arrow_left.css({"top": data.arrowRightY + "px", "left": arrowLeftNewX + "px"}); } updateArrowPosFields(); } /** * on arrows drag event. update form fields, and operate arrow connections. */ var onArrowsDrag = function() { var arrowID = this.id; checkArrowsConnection(arrowID); } /** * * update bullets position from the bullets */ var updateBulletFields = function(fromWhere) { //trace("update fields "+fromWhere);return(false); if (bullets_container.is(":visible") == false) return(true); var data = getElementsData(); //update fields: var bulletsRightX = data.sliderWidth - data.bulletsX - data.bulletsWidth; jQuery("#jform_visual_bullets_y").val(data.bulletsY); jQuery("#jform_visual_bullets_xleft").val(data.bulletsX); jQuery("#jform_visual_bullets_xright").val(bulletsRightX); //update relative option updateBulletsRelativeY(); } /** * update arrows positions from the arrows */ var updateArrowPosFields = function() { //don't update if the container not visible if (container.is(':visible') == false) return(true); if (arrow_left.is(':visible') == false) return(true); var data = getElementsData(); //set values jQuery("#jform_visual_arrow_left_x").val(data.arrowLeftX); jQuery("#jform_visual_arrow_left_y").val(data.arrowLeftY); jQuery("#jform_visual_arrow_right_x").val(data.arrowRightX); jQuery("#jform_visual_arrow_right_y").val(data.arrowRightY); } /** * hide arrows and disable panel elements */ var hideArrows = function() { if (arrow_left.is(':visible') == false) return(true); arrow_left.hide(); arrow_right.hide(); //hide arrow fields jQuery("#section_arrows").hide(); } /** * show arrows and enable panel elements */ var showArrows = function() { if (arrow_left.is(':visible') == true) return(true); arrow_left.show(); arrow_right.show(); //show arrow fields jQuery("#section_arrows").show(); } /** * update the container from fields. */ var updateFromFields = function(element) { if (element == undefined || element.id == undefined) element = this; var elemID = null; if (element.id != undefined) elemID = element.id; //---- update width / height var width = jQuery("#jform_visual_width").val(); var height = jQuery("#jform_visual_height").val(); container.width(width).height(height); //width / heigth event switch (elemID) { case "jform_visual_width": case "jform_visual_height": onSliderResize(); break; } //update border updateFromFields_border(); //update shadow updateFromFields_shadow(); //update arrows updateFromFields_arrows(elemID); //update bullets updateFromFields_bullets(elemID); //set the bullets according the resize bulletsSetRelativeYPos(); //update captions updateFromFields_caption(elemID); //update caption text updateFromFields_captionText(); } /** * update caption text */ var updateFromFields_captionText = function() { var css = {}; if (caption_back.is(":visible") == false) return(true); //set color var textColor = jQuery("#jform_visual_text_color").val(); css["color"] = textColor; //set text align var textAlign = jQuery("#jform_visual_text_align").val(); css["text-align"] = textAlign; //set padding var textPadding = jQuery("#jform_visual_text_padding").val(); css["padding"] = textPadding + "px"; var fontSize = jQuery("#jform_visual_font_size").val(); css["font-size"] = fontSize + "px"; //set the css caption_text.css(css); } /** * show the caption */ var showCaption = function() { if (caption_back.is(":visible") == true) return(false); caption_back.show(); } /** * hide the caption */ var hideCaption = function() { if (caption_back.is(":visible") == false) return(false); caption_back.hide(); } /** * update captions fields */ var updateFromFields_caption = function(elemID) { var css = {}; if (elemID == "jform_visual_has_caption") { var hasCaption = jQuery("#jform_visual_has_caption").is(":checked"); if (hasCaption == true) showCaption(); else hideCaption(); } if (caption_back.is(":visible") == false) return(true); //set back color var backColor = jQuery("#jform_visual_caption_back_color").val(); css["background-color"] = backColor; //set alpha var alpha = jQuery("#jform_visual_caption_back_alpha").val(); var alpha = Number(alpha) / 100; caption_back.fadeTo(0, alpha); //set position: var position = jQuery("#jform_visual_caption_position").val(); if (position == "top") { css["bottom"] = ""; //set to top css["top"] = "0px"; } else { css["bottom"] = "0px"; //set to bottom css["top"] = ""; } //set the css caption_back.css(css); } /** * hide the bullets */ var hideBullets = function() { if (bullets_container.is(":visible") == false) return(true); //hide fields jQuery("#section_bullets").hide(); //hide bullets bullets_container.hide(); } /** * show the bullets */ var showBullets = function() { if (bullets_container.is(":visible") == true) return(true); //show fields jQuery("#section_bullets").show(); //show bullets bullets_container.removeClass("invisible").show(); } /** * update bullets fields */ var reverse_bullets = function() { var reverseChecked = jQuery("#jform_visual_reverse_bullets").is(":checked"); var normal = 'normal'; var active = 'active'; if (reverseChecked) { normal = 'active'; active = 'normal'; } jQuery("#bullets_wrapper img").each(function(index, value) { if (index == 1) { jQuery(this).attr('src', jQuery(this).attr('src').replace(normal, active)); } else { jQuery(this).attr('src', jQuery(this).attr('src').replace(active, normal)); } }); } /** * update bullets fields */ var updateFromFields_bullets = function(elemID) { //trace("update bullets");return(false); switch (elemID) { case "jform_visual_has_bullets": var showBulletsCheck = jQuery("#jform_visual_has_bullets").is(":checked"); if (showBulletsCheck) showBullets(); else hideBullets(); break; } //skip invisible container if (bullets_container.is(':visible') == false) return(true); var bulletsY = jQuery("#jform_visual_bullets_y").val(); switch (elemID) { default: case "jform_visual_bullets_xleft": var bulletsX = jQuery("#jform_visual_bullets_xleft").val(); break; case "jform_visual_bullets_xright": var data = getElementsData(); var bulletsRightX = jQuery("#jform_visual_bullets_xright").val(); var bulletsX = data.sliderWidth - data.bulletsWidth - bulletsRightX; break; case "jform_visual_bullets_spacing": //set spacing var spacing = jQuery("#jform_visual_bullets_spacing").val(); bullets_container.find("ul li:not(:first-child)").css("margin-left", spacing + "px"); bulletsAlignCenter(); break; } bullets_container.css({"top": bulletsY + "px", "left": bulletsX + "px"}); updateBulletFields("fields"); } /** * update border */ var updateFromFields_border = function() { var has_border = jQuery("#jform_visual_has_border").is(':checked'); if (has_border == true) { var border_color = jQuery("#jform_visual_border_color").val(); var border_size = jQuery("#jform_visual_border_size").val(); container.css({"border-style": "solid", "border-width": border_size + "px", "border-color": border_color }); } else container.css({"border-style": "none"}); } /** * update shadow from fields */ var updateFromFields_shadow = function() { //----update shadow: var has_shadow = jQuery("#jform_visual_has_shadow").is(':checked'); if (has_shadow == true) { var shadow_color = jQuery("#jform_visual_shadow_color").val(); var shadowProps = "0px 1px 5px 0px " + shadow_color; container.css({"box-shadow": shadowProps, "-moz-box-shadow": shadowProps, "-webkit-box-shadow": shadowProps}); } else container.css({"box-shadow": "none", "-moz-box-shadow": "none", "-webkit-box-shadow": "none"}); } /** * set arrows in the place of the fields */ var updateFromFields_arrows = function(elemID) { var showArrows_check = jQuery("#jform_visual_has_arrows").is(":checked"); //check arrows hide / show if (elemID == "jform_visual_has_arrows") { if (showArrows_check == false) hideArrows(); else showArrows(); } //position arrows if (arrow_left.is(':visible') == false) return(true); var arrowLeftX = jQuery("#jform_visual_arrow_left_x").val(); var arrowLeftY = jQuery("#jform_visual_arrow_left_y").val(); var arrowRightX = jQuery("#jform_visual_arrow_right_x").val(); var arrowRightY = jQuery("#jform_visual_arrow_right_y").val(); arrow_left.css({"top": arrowLeftY + "px", "left": arrowLeftX + "px"}); arrow_right.css({"top": arrowRightY + "px", "left": arrowRightX + "px"}); //operate errors connection: switch (elemID) { case "jform_visual_has_arrows": case "jform_visual_arrow_left_y": case "jform_visual_arrow_left_x": checkArrowsConnection("arrow_left"); break; case "jform_visual_arrow_right_y": case "jform_visual_arrow_right_x": checkArrowsConnection("arrow_right"); break; } } /** * on arrows select event - update arrow pictures and change arrows set */ t.onArrowsSelect = function(data) { jQuery("#arrow_left").attr("src", data.url_left); jQuery("#arrow_right").attr("src", data.url_right); jQuery("#jform_visual_arrows_set").val(data.arrowName); //align arrows setTimeout("UniteNivoPro.operationDelay('checkArrowsConnection')", 500); } /** * on bullets select - take bullets html by ajax, and change the bullets. */ t.onBulletsSelect = function(setName) { var data = {setName: setName}; UniteAdmin.ajaxRequest("get_bullets_html", data, function(response) { jQuery("#bullets_wrapper").html(response.bullets_html); jQuery("#jform_visual_bullets_set").val(setName); //align center after delay setTimeout("UniteNivoPro.operationDelay('bulletsAlignCenter')", 500); bulletsAlignCenter(); reverse_bullets(); }); } /** * align center after delay function */ t.operationDelay = function(operation) { switch (operation) { case "bulletsAlignCenter": bulletsAlignCenter(); break; case "checkArrowsConnection": checkArrowsConnection("arrow_left"); break; } } }
VS-Studio3/build
administrator/components/com_nivosliderpro/assets/nivopro.js
JavaScript
gpl-2.0
22,978
#ifndef _UMLNCRELATION_H #define _UMLNCRELATION_H #include "UmlBaseNcRelation.h" #include <qcstring.h> //This class manages 'relations' between non class objects // // You can modify it as you want (except the constructor) class UmlNcRelation : public UmlBaseNcRelation { public: UmlNcRelation(void * id, const QCString & n) : UmlBaseNcRelation(id, n) {}; virtual int orderWeight(); }; #endif
gregsmirnov/bouml
genplugouts/sort/cpp/UmlNcRelation.h
C
gpl-2.0
409
/* * Copyright (C) 2013-2019 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * 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. */ package org.n52.series.spi.geo; import org.locationtech.jts.geom.Geometry; import org.n52.io.crs.CRSUtils; import org.n52.io.request.IoParameters; import org.n52.io.response.dataset.StationOutput; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TransformationService { private static final Logger LOGGER = LoggerFactory.getLogger(TransformationService.class); /** * @param station * the station to transform * @param parameters * the query containing CRS and how to handle axes order */ protected void transformInline(StationOutput station, IoParameters parameters) { String crs = parameters.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return; } Geometry geometry = transform(station.getGeometry(), parameters); station.setValue(StationOutput.GEOMETRY, geometry, parameters, station::setGeometry); } public Geometry transform(Geometry geometry, IoParameters query) { String crs = query.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return geometry; } return transformGeometry(query, geometry, crs); } private Geometry transformGeometry(IoParameters query, Geometry geometry, String crs) throws RuntimeException { try { CRSUtils crsUtils = query.isForceXY() ? CRSUtils.createEpsgForcedXYAxisOrder() : CRSUtils.createEpsgStrictAxisOrder(); return geometry != null ? crsUtils.transformInnerToOuter(geometry, crs) : geometry; } catch (TransformException e) { throwRuntimeException(crs, e); } catch (FactoryException e) { LOGGER.debug("Couldn't create geometry factory", e); } return geometry; } private void throwRuntimeException(String crs, TransformException e) throws RuntimeException { throw new RuntimeException("Could not transform to requested CRS: " + crs, e); } }
ridoo/series-rest-api
spi/src/main/java/org/n52/series/spi/geo/TransformationService.java
Java
gpl-2.0
3,637
// This file is part of fityk program. Copyright 2001-2013 Marcin Wojdyr // Licence: GNU General Public License ver. 2+ /// wrapper around MPFIT (cmpfit) library, /// http://www.physics.wisc.edu/~craigm/idl/cmpfit.html /// which is Levenberg-Marquardt implementation based on MINPACK-1 #ifndef FITYK_MPFIT_H_ #define FITYK_MPFIT_H_ #include "fit.h" #include "cmpfit/mpfit.h" namespace fityk { /// Wrapper around CMPFIT class MPfit : public Fit { public: MPfit(Full* F, const char* fname) : Fit(F, fname) {} virtual double run_method(std::vector<realt>* best_a); // implementation (must be public to be called inside callback function) int calculate(int m, int npar, double *par, double *deviates, double **derivs); int on_iteration(); virtual std::vector<double> get_covariance_matrix(const std::vector<Data*>& datas); virtual std::vector<double> get_standard_errors(const std::vector<Data*>& datas); private: mp_config_struct mp_conf_; mp_result result_; int run_mpfit(const std::vector<Data*>& datas, const std::vector<realt>& parameters, const std::vector<bool>& param_usage, double *final_a=NULL); }; } // namespace fityk #endif
wojdyr/fityk
fityk/CMPfit.h
C
gpl-2.0
1,270
#include <stdio.h> #include <string.h> #include <stdlib.h> // prototypes declarations char** split(char *str, char *delimitators); int main(void) { char** result; char str[] = "1-0:0.0.1(132412515)\n1-0:0.2.3.4(654236517)\n"; result = split(str, "()\n"); for(size_t index = 0; *(result + index); index++) { printf("%s\n",*(result + index)); } free(result); return 0; } char** split(char *str, char* delimitators) { int count = 0; size_t index = 0; char **parse; char *tmp = str; char *token; char *last_delimitator; while(*tmp) { /****************************************** si *tmp contiene uno de los deliitadores strchr devolvera la direcccion de este sino devolvera una direccion nula *******************************************/ if(strchr(delimitators, *tmp) != NULL) { count++; last_delimitator = tmp; } tmp++; } //Espacio para datos ubicados luego del ultimo delimitador count += last_delimitator < (str + strlen(str) - 1); //Espacio para el caracter nulo del arreglo de punteros count++; parse = malloc(sizeof(char*) * count); token = strtok(str, delimitators); while(token != NULL) { *(parse + index++) = token; token = strtok(NULL, delimitators); } *(parse + index) = 0; return parse; }
marcelodavid/c_utilities
string/split.c
C
gpl-2.0
1,269
<?php /** * ECSHOP 控制台首頁 * ============================================================================ * 版權所有 2005-2010 上海商派網絡科技有限公司,並保留所有權利。 * 網站地址: http://www.ecshop.com; * ---------------------------------------------------------------------------- * 這不是一個自由軟件!您只能在不用於商業目的的前提下對程序代碼進行修改和 * 使用;不允許對程序代碼以任何形式任何目的的再發布。 * ============================================================================ * $Author: liuhui $ * $Id: index.php 17163 2010-05-20 10:13:23Z liuhui $ */ define('IN_ECS', true); require(dirname(__FILE__) . '/includes/init.php'); require_once(ROOT_PATH . '/includes/lib_order.php'); /*------------------------------------------------------ */ //-- 框架 /*------------------------------------------------------ */ if ($_REQUEST['act'] == '') { $smarty->assign('shop_url', urlencode($ecs->url())); $smarty->display('index.htm'); } /*------------------------------------------------------ */ //-- 頂部框架的內容 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'top') { // 獲得管理員設置的菜單 $lst = array(); $nav = $db->GetOne('SELECT nav_list FROM ' . $ecs->table('admin_user') . " WHERE user_id = '" . $_SESSION['admin_id'] . "'"); if (!empty($nav)) { $arr = explode(',', $nav); foreach ($arr AS $val) { $tmp = explode('|', $val); $lst[$tmp[1]] = $tmp[0]; } } // 獲得管理員設置的菜單 // 獲得管理員ID $smarty->assign('send_mail_on',$_CFG['send_mail_on']); $smarty->assign('nav_list', $lst); $smarty->assign('admin_id', $_SESSION['admin_id']); $smarty->assign('certi', $_CFG['certi']); $smarty->display('top.htm'); } /*------------------------------------------------------ */ //-- 計算器 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'calculator') { $smarty->display('calculator.htm'); } /*------------------------------------------------------ */ //-- 左邊的框架 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'menu') { include_once('includes/inc_menu.php'); // 權限對照表 include_once('includes/inc_priv.php'); foreach ($modules AS $key => $value) { ksort($modules[$key]); } ksort($modules); foreach ($modules AS $key => $val) { $menus[$key]['label'] = $_LANG[$key]; if (is_array($val)) { foreach ($val AS $k => $v) { if ( isset($purview[$k])) { if (is_array($purview[$k])) { $boole = false; foreach ($purview[$k] as $action) { $boole = $boole || admin_priv($action, '', false); } if (!$boole) { continue; } } else { if (! admin_priv($purview[$k], '', false)) { continue; } } } if ($k == 'ucenter_setup' && $_CFG['integrate_code'] != 'ucenter') { continue; } $menus[$key]['children'][$k]['label'] = $_LANG[$k]; $menus[$key]['children'][$k]['action'] = $v; } } else { $menus[$key]['action'] = $val; } // 如果children的子元素長度為0則刪除該組 if(empty($menus[$key]['children'])) { unset($menus[$key]); } } $smarty->assign('menus', $menus); $smarty->assign('no_help', $_LANG['no_help']); $smarty->assign('help_lang', $_CFG['lang']); $smarty->assign('charset', EC_CHARSET); $smarty->assign('admin_id', $_SESSION['admin_id']); $smarty->display('menu.htm'); } /*------------------------------------------------------ */ //-- 清除緩存 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'clear_cache') { clear_all_files(); sys_msg($_LANG['caches_cleared']); } /*------------------------------------------------------ */ //-- 主窗口,起始頁 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'main') { //開店嚮導第一步 if(isset($_SESSION['shop_guide']) && $_SESSION['shop_guide'] === true) { unset($_SESSION['shop_guide']);//銷毀session ecs_header("Location: ./index.php?act=first\n"); exit(); } $gd = gd_version(); /* 檢查文件目錄屬性 */ $warning = array(); if ($_CFG['shop_closed']) { $warning[] = $_LANG['shop_closed_tips']; } if (file_exists('../install')) { $warning[] = $_LANG['remove_install']; } if (file_exists('../upgrade')) { $warning[] = $_LANG['remove_upgrade']; } if (file_exists('../demo')) { $warning[] = $_LANG['remove_demo']; } $open_basedir = ini_get('open_basedir'); if (!empty($open_basedir)) { /* 如果 open_basedir 不為空,則檢查是否包含了 upload_tmp_dir */ $open_basedir = str_replace(array("\\", "\\\\"), array("/", "/"), $open_basedir); $upload_tmp_dir = ini_get('upload_tmp_dir'); if (empty($upload_tmp_dir)) { if (stristr(PHP_OS, 'win')) { $upload_tmp_dir = getenv('TEMP') ? getenv('TEMP') : getenv('TMP'); $upload_tmp_dir = str_replace(array("\\", "\\\\"), array("/", "/"), $upload_tmp_dir); } else { $upload_tmp_dir = getenv('TMPDIR') === false ? '/tmp' : getenv('TMPDIR'); } } if (!stristr($open_basedir, $upload_tmp_dir)) { $warning[] = sprintf($_LANG['temp_dir_cannt_read'], $upload_tmp_dir); } } $result = file_mode_info('../cert'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'cert', $_LANG['cert_cannt_write']); } $result = file_mode_info('../' . DATA_DIR); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'data', $_LANG['data_cannt_write']); } else { $result = file_mode_info('../' . DATA_DIR . '/afficheimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/afficheimg', $_LANG['afficheimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/brandlogo'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/brandlogo', $_LANG['brandlogo_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/cardimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/cardimg', $_LANG['cardimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/feedbackimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/feedbackimg', $_LANG['feedbackimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/packimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/packimg', $_LANG['packimg_cannt_write']); } } $result = file_mode_info('../images'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['images_cannt_write']); } else { $result = file_mode_info('../' . IMAGE_DIR . '/upload'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], IMAGE_DIR . '/upload', $_LANG['imagesupload_cannt_write']); } } $result = file_mode_info('../temp'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_cannt_write']); } $result = file_mode_info('../temp/backup'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_backup_cannt_write']); } if (!is_writeable('../' . DATA_DIR . '/order_print.html')) { $warning[] = $_LANG['order_print_canntwrite']; } clearstatcache(); $smarty->assign('warning_arr', $warning); /* 管理員留言信息 */ $sql = 'SELECT message_id, sender_id, receiver_id, sent_time, readed, deleted, title, message, user_name ' . 'FROM ' . $ecs->table('admin_message') . ' AS a, ' . $ecs->table('admin_user') . ' AS b ' . "WHERE a.sender_id = b.user_id AND a.receiver_id = '$_SESSION[admin_id]' AND ". "a.readed = 0 AND deleted = 0 ORDER BY a.sent_time DESC"; $admin_msg = $db->GetAll($sql); $smarty->assign('admin_msg', $admin_msg); /* 取得支持貨到付款和不支持貨到付款的支付方式 */ $ids = get_pay_ids(); /* 已完成的訂單 */ $order['finished'] = $db->GetOne('SELECT COUNT(*) FROM ' . $ecs->table('order_info'). " WHERE 1 " . order_query_sql('finished')); $status['finished'] = CS_FINISHED; /* 待發貨的訂單: */ $order['await_ship'] = $db->GetOne('SELECT COUNT(*)'. ' FROM ' .$ecs->table('order_info') . " WHERE 1 " . order_query_sql('await_ship')); $status['await_ship'] = CS_AWAIT_SHIP; /* 待付款的訂單: */ $order['await_pay'] = $db->GetOne('SELECT COUNT(*)'. ' FROM ' .$ecs->table('order_info') . " WHERE 1 " . order_query_sql('await_pay')); $status['await_pay'] = CS_AWAIT_PAY; /* “未確認”的訂單 */ $order['unconfirmed'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('order_info'). " WHERE 1 " . order_query_sql('unconfirmed')); $status['unconfirmed'] = OS_UNCONFIRMED; // $today_start = mktime(0,0,0,date('m'),date('d'),date('Y')); $order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' . ' FROM ' .$ecs->table('order_info')); $smarty->assign('order', $order); $smarty->assign('status', $status); /* 商品信息 */ $goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1'); $virtual_card['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_new = 1 AND is_real = 1'); $virtual_card['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_new = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_best = 1 AND is_real = 1'); $virtual_card['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_best = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_hot = 1 AND is_real = 1'); $virtual_card['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_hot = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $time = gmtime(); $goods['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND promote_price>0' . " AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real = 1"); $virtual_card['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND promote_price>0' . " AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real=0 AND extension_code='virtual_card'"); /* 缺貨商品 */ if ($_CFG['use_storage']) { $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real = 1'; $goods['warn'] = $db->GetOne($sql); $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real=0 AND extension_code=\'virtual_card\''; $virtual_card['warn'] = $db->GetOne($sql); } else { $goods['warn'] = 0; $virtual_card['warn'] = 0; } $smarty->assign('goods', $goods); $smarty->assign('virtual_card', $virtual_card); /* 訪問統計信息 */ $today = local_getdate(); $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('stats'). ' WHERE access_time > ' . (mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']) - date('Z')); $today_visit = $db->GetOne($sql); $smarty->assign('today_visit', $today_visit); $online_users = $sess->get_users_count(); $smarty->assign('online_users', $online_users); /* 最近反饋 */ $sql = "SELECT COUNT(f.msg_id) ". "FROM " . $ecs->table('feedback') . " AS f ". "LEFT JOIN " . $ecs->table('feedback') . " AS r ON r.parent_id=f.msg_id " . 'WHERE f.parent_id=0 AND ISNULL(r.msg_id) ' ; $smarty->assign('feedback_number', $db->GetOne($sql)); /* 未審核評論 */ $smarty->assign('comment_number', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('comment') . ' WHERE status = 0 AND parent_id = 0')); $mysql_ver = $db->version(); // 獲得 MySQL 版本 /* 系統信息 */ $sys_info['os'] = PHP_OS; $sys_info['ip'] = $_SERVER['SERVER_ADDR']; $sys_info['web_server'] = $_SERVER['SERVER_SOFTWARE']; $sys_info['php_ver'] = PHP_VERSION; $sys_info['mysql_ver'] = $mysql_ver; $sys_info['zlib'] = function_exists('gzclose') ? $_LANG['yes']:$_LANG['no']; $sys_info['safe_mode'] = (boolean) ini_get('safe_mode') ? $_LANG['yes']:$_LANG['no']; $sys_info['safe_mode_gid'] = (boolean) ini_get('safe_mode_gid') ? $_LANG['yes'] : $_LANG['no']; $sys_info['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : $_LANG['no_timezone']; $sys_info['socket'] = function_exists('fsockopen') ? $_LANG['yes'] : $_LANG['no']; if ($gd == 0) { $sys_info['gd'] = 'N/A'; } else { if ($gd == 1) { $sys_info['gd'] = 'GD1'; } else { $sys_info['gd'] = 'GD2'; } $sys_info['gd'] .= ' ('; /* 檢查系統支持的圖片類型 */ if ($gd && (imagetypes() & IMG_JPG) > 0) { $sys_info['gd'] .= ' JPEG'; } if ($gd && (imagetypes() & IMG_GIF) > 0) { $sys_info['gd'] .= ' GIF'; } if ($gd && (imagetypes() & IMG_PNG) > 0) { $sys_info['gd'] .= ' PNG'; } $sys_info['gd'] .= ')'; } /* IP庫版本 */ $sys_info['ip_version'] = ecs_geoip('255.255.255.0'); /* 允許上傳的最大文件大小 */ $sys_info['max_filesize'] = ini_get('upload_max_filesize'); $smarty->assign('sys_info', $sys_info); /* 缺貨登記 */ $smarty->assign('booking_goods', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('booking_goods') . ' WHERE is_dispose = 0')); /* 退款申請 */ $smarty->assign('new_repay', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('user_account') . ' WHERE process_type = ' . SURPLUS_RETURN . ' AND is_paid = 0 ')); assign_query_info(); $smarty->assign('ecs_version', VERSION); $smarty->assign('ecs_release', RELEASE); $smarty->assign('ecs_lang', $_CFG['lang']); $smarty->assign('ecs_charset', strtoupper(EC_CHARSET)); $smarty->assign('install_date', local_date($_CFG['date_format'], $_CFG['install_date'])); $smarty->display('start.htm'); } elseif ($_REQUEST['act'] == 'main_api') { require_once(ROOT_PATH . '/includes/lib_base.php'); $data = read_static_cache('api_str'); if($data === false || API_TIME < date('Y-m-d H:i:s',time()-43200)) { include_once(ROOT_PATH . 'includes/cls_transport.php'); $ecs_version = VERSION; $ecs_lang = $_CFG['lang']; $ecs_release = RELEASE; $php_ver = PHP_VERSION; $mysql_ver = $db->version(); $order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' . ' FROM ' .$ecs->table('order_info')); $ocount = $order['stats']['oCount']; $oamount = $order['stats']['oAmount']; $goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1'); $gcount = $goods['total']; $ecs_charset = strtoupper(EC_CHARSET); $ecs_user = $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('users')); $ecs_template = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'template\''); $style = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'stylename\''); if($style == '') { $style = '0'; } $ecs_style = $style; $shop_url = urlencode($ecs->url()); $patch_file = file_get_contents(ROOT_PATH.ADMIN_PATH."/patch_num"); $apiget = "ver= $ecs_version &lang= $ecs_lang &release= $ecs_release &php_ver= $php_ver &mysql_ver= $mysql_ver &ocount= $ocount &oamount= $oamount &gcount= $gcount &charset= $ecs_charset &usecount= $ecs_user &template= $ecs_template &style= $ecs_style &url= $shop_url &patch= $patch_file "; $t = new transport; $api_comment = $t->request('http://api.ecshop.com/checkver.php', $apiget); $api_str = $api_comment["body"]; echo $api_str; $f=ROOT_PATH . 'data/config.php'; file_put_contents($f,str_replace("'API_TIME', '".API_TIME."'","'API_TIME', '".date('Y-m-d H:i:s',time())."'",file_get_contents($f))); write_static_cache('api_str', $api_str); } else { echo $data; } } /*------------------------------------------------------ */ //-- 開店嚮導第一步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'first') { $smarty->assign('countries', get_regions()); $smarty->assign('provinces', get_regions(1, 1)); $smarty->assign('cities', get_regions(2, 2)); $sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_name'"; $shop_name = $db->getOne($sql); $smarty->assign('shop_name', $shop_name); $sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_title'"; $shop_title = $db->getOne($sql); $smarty->assign('shop_title', $shop_title); //獲取配送方式 // $modules = read_modules('../includes/modules/shipping'); $directory = ROOT_PATH . 'includes/modules/shipping'; $dir = @opendir($directory); $set_modules = true; $modules = array(); while (false !== ($file = @readdir($dir))) { if (preg_match("/^.*?\.php$/", $file)) { if ($file != 'express.php') { include_once($directory. '/' .$file); } } } @closedir($dir); unset($set_modules); foreach ($modules AS $key => $value) { ksort($modules[$key]); } ksort($modules); for ($i = 0; $i < count($modules); $i++) { $lang_file = ROOT_PATH.'languages/' .$_CFG['lang']. '/shipping/' .$modules[$i]['code']. '.php'; if (file_exists($lang_file)) { include_once($lang_file); } $modules[$i]['name'] = $_LANG[$modules[$i]['code']]; $modules[$i]['desc'] = $_LANG[$modules[$i]['desc']]; $modules[$i]['insure_fee'] = empty($modules[$i]['insure'])? 0 : $modules[$i]['insure']; $modules[$i]['cod'] = $modules[$i]['cod']; $modules[$i]['install'] = 0; } $smarty->assign('modules', $modules); unset($modules); //獲取支付方式 $modules = read_modules('../includes/modules/payment'); for ($i = 0; $i < count($modules); $i++) { $code = $modules[$i]['code']; $modules[$i]['name'] = $_LANG[$modules[$i]['code']]; if (!isset($modules[$i]['pay_fee'])) { $modules[$i]['pay_fee'] = 0; } $modules[$i]['desc'] = $_LANG[$modules[$i]['desc']]; } // $modules[$i]['install'] = '0'; $smarty->assign('modules_payment', $modules); assign_query_info(); $smarty->assign('ur_here', $_LANG['ur_config']); $smarty->display('setting_first.htm'); } /*------------------------------------------------------ */ //-- 開店嚮導第二步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'second') { admin_priv('shop_config'); $shop_name = empty($_POST['shop_name']) ? '' : $_POST['shop_name'] ; $shop_title = empty($_POST['shop_title']) ? '' : $_POST['shop_title'] ; $shop_country = empty($_POST['shop_country']) ? '' : intval($_POST['shop_country']); $shop_province = empty($_POST['shop_province']) ? '' : intval($_POST['shop_province']); $shop_city = empty($_POST['shop_city']) ? '' : intval($_POST['shop_city']); $shop_address = empty($_POST['shop_address']) ? '' : $_POST['shop_address'] ; $shipping = empty($_POST['shipping']) ? '' : $_POST['shipping']; $payment = empty($_POST['payment']) ? '' : $_POST['payment']; if(!empty($shop_name)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_name' WHERE code = 'shop_name'"; $db->query($sql); } if(!empty($shop_title)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_title' WHERE code = 'shop_title'"; $db->query($sql); } if(!empty($shop_address)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_address' WHERE code = 'shop_address'"; $db->query($sql); } if(!empty($shop_country)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_country' WHERE code='shop_country'"; $db->query($sql); } if(!empty($shop_province)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_province' WHERE code='shop_province'"; $db->query($sql); } if(!empty($shop_city)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_city' WHERE code='shop_city'"; $db->query($sql); } //設置配送方式 if(!empty($shipping)) { $shop_add = read_modules('../includes/modules/shipping'); foreach ($shop_add as $val) { $mod_shop[] = $val['code']; } $mod_shop = implode(',',$mod_shop); $set_modules = true; if(strpos($mod_shop,$shipping) === false) { exit; } else { include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping . '.php'); } $sql = "SELECT shipping_id FROM " .$ecs->table('shipping'). " WHERE shipping_code = '$shipping'"; $shipping_id = $db->GetOne($sql); if($shipping_id <= 0) { $insure = empty($modules[0]['insure']) ? 0 : $modules[0]['insure']; $sql = "INSERT INTO " . $ecs->table('shipping') . " (" . "shipping_code, shipping_name, shipping_desc, insure, support_cod, enabled" . ") VALUES (" . "'" . addslashes($modules[0]['code']). "', '" . addslashes($_LANG[$modules[0]['code']]) . "', '" . addslashes($_LANG[$modules[0]['desc']]) . "', '$insure', '" . intval($modules[0]['cod']) . "', 1)"; $db->query($sql); $shipping_id = $db->insert_Id(); } //設置配送區域 $area_name = empty($_POST['area_name']) ? '' : $_POST['area_name']; if(!empty($area_name)) { $sql = "SELECT shipping_area_id FROM " .$ecs->table("shipping_area"). " WHERE shipping_id='$shipping_id' AND shipping_area_name='$area_name'"; $area_id = $db->getOne($sql); if($area_id <= 0) { $config = array(); foreach ($modules[0]['configure'] AS $key => $val) { $config[$key]['name'] = $val['name']; $config[$key]['value'] = $val['value']; } $count = count($config); $config[$count]['name'] = 'free_money'; $config[$count]['value'] = 0; /* 如果支持貨到付款,則允許設置貨到付款支付費用 */ if ($modules[0]['cod']) { $count++; $config[$count]['name'] = 'pay_fee'; $config[$count]['value'] = make_semiangle(0); } $sql = "INSERT INTO " .$ecs->table('shipping_area'). " (shipping_area_name, shipping_id, configure) ". "VALUES" . " ('$area_name', '$shipping_id', '" .serialize($config). "')"; $db->query($sql); $area_id = $db->insert_Id(); } $region_id = empty($_POST['shipping_country']) ? 1 : intval($_POST['shipping_country']); $region_id = empty($_POST['shipping_province']) ? $region_id : intval($_POST['shipping_province']); $region_id = empty($_POST['shipping_city']) ? $region_id : intval($_POST['shipping_city']); $region_id = empty($_POST['shipping_district']) ? $region_id : intval($_POST['shipping_district']); /* 添加選定的城市和地區 */ $sql = "REPLACE INTO ".$ecs->table('area_region')." (shipping_area_id, region_id) VALUES ('$area_id', '$region_id')"; $db->query($sql); } } unset($modules); if(!empty($payment)) { /* 取相應插件信息 */ $set_modules = true; include_once(ROOT_PATH.'includes/modules/payment/' . $payment . '.php'); $pay_config = array(); if (isset($_REQUEST['cfg_value']) && is_array($_REQUEST['cfg_value'])) { for ($i = 0; $i < count($_POST['cfg_value']); $i++) { $pay_config[] = array('name' => trim($_POST['cfg_name'][$i]), 'type' => trim($_POST['cfg_type'][$i]), 'value' => trim($_POST['cfg_value'][$i]) ); } } $pay_config = serialize($pay_config); /* 安裝,檢查該支付方式是否曾經安裝過 */ $sql = "SELECT COUNT(*) FROM " . $ecs->table('payment') . " WHERE pay_code = '$payment'"; if ($db->GetOne($sql) > 0) { $sql = "UPDATE " . $ecs->table('payment') . " SET pay_config = '$pay_config'," . " enabled = '1' " . "WHERE pay_code = '$payment' LIMIT 1"; $db->query($sql); } else { // $modules = read_modules('../includes/modules/payment'); $payment_info = array(); $payment_info['name'] = $_LANG[$modules[0]['code']]; $payment_info['pay_fee'] = empty($modules[0]['pay_fee']) ? 0 : $modules[0]['pay_fee']; $payment_info['desc'] = $_LANG[$modules[0]['desc']]; $sql = "INSERT INTO " . $ecs->table('payment') . " (pay_code, pay_name, pay_desc, pay_config, is_cod, pay_fee, enabled, is_online)" . "VALUES ('$payment', '$payment_info[name]', '$payment_info[desc]', '$pay_config', '0', '$payment_info[pay_fee]', '1', '1')"; $db->query($sql); } } clear_all_files(); assign_query_info(); $smarty->assign('ur_here', $_LANG['ur_add']); $smarty->display('setting_second.htm'); } /*------------------------------------------------------ */ //-- 開店嚮導第三步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'third') { admin_priv('goods_manage'); $good_name = empty($_POST['good_name']) ? '' : $_POST['good_name']; $good_number = empty($_POST['good_number']) ? '' : $_POST['good_number']; $good_category = empty($_POST['good_category']) ? '' : $_POST['good_category']; $good_brand = empty($_POST['good_brand']) ? '' : $_POST['good_brand']; $good_price = empty($_POST['good_price']) ? 0 : $_POST['good_price']; $good_name = empty($_POST['good_name']) ? '' : $_POST['good_name']; $is_best = empty($_POST['is_best']) ? 0 : 1; $is_new = empty($_POST['is_new']) ? 0 : 1; $is_hot = empty($_POST['is_hot']) ? 0 :1; $good_brief = empty($_POST['good_brief']) ? '' : $_POST['good_brief']; $market_price = $good_price * 1.2; if(!empty($good_category)) { if (cat_exists($good_category, 0)) { /* 同級別下不能有重複的分類名稱 */ $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)'); sys_msg($_LANG['catname_exist'], 0, $link); } } if(!empty($good_brand)) { if (brand_exists($good_brand)) { /* 同級別下不能有重複的品牌名稱 */ $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)'); sys_msg($_LANG['brand_name_exist'], 0, $link); } } $brand_id = 0; if(!empty($good_brand)) { $sql = 'INSERT INTO ' . $ecs->table('brand') . " (brand_name, is_show)" . " values('" . $good_brand . "', '1')"; $db->query($sql); $brand_id = $db->insert_Id(); } if(!empty($good_category)) { $sql = 'INSERT INTO ' . $ecs->table('category') . " (cat_name, parent_id, is_show)" . " values('" . $good_category . "', '0', '1')"; $db->query($sql); $cat_id = $db->insert_Id(); //貨號 require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_goods.php'); $max_id = $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$ecs->table('goods')); $goods_sn = generate_goods_sn($max_id); include_once(ROOT_PATH . 'includes/cls_image.php'); $image = new cls_image($_CFG['bgcolor']); if(!empty($good_name)) { /* 檢查圖片:如果有錯誤,檢查尺寸是否超過最大值;否則,檢查文件類型 */ if (isset($_FILES['goods_img']['error'])) // php 4.2 版本才支持 error { // 最大上傳文件大小 $php_maxsize = ini_get('upload_max_filesize'); $htm_maxsize = '2M'; // 商品圖片 if ($_FILES['goods_img']['error'] == 0) { if (!$image->check_img_type($_FILES['goods_img']['type'])) { sys_msg($_LANG['invalid_goods_img'], 1, array(), false); } } elseif ($_FILES['goods_img']['error'] == 1) { sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false); } elseif ($_FILES['goods_img']['error'] == 2) { sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false); } } /* 4。1版本 */ else { // 商品圖片 if ($_FILES['goods_img']['tmp_name'] != 'none') { if (!$image->check_img_type($_FILES['goods_img']['type'])) { sys_msg($_LANG['invalid_goods_img'], 1, array(), false); } } } $goods_img = ''; // 初始化商品圖片 $goods_thumb = ''; // 初始化商品縮略圖 $original_img = ''; // 初始化原始圖片 $old_original_img = ''; // 初始化原始圖片舊圖 // 如果上傳了商品圖片,相應處理 if ($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none') { $original_img = $image->upload_image($_FILES['goods_img']); // 原始圖片 if ($original_img === false) { sys_msg($image->error_msg(), 1, array(), false); } $goods_img = $original_img; // 商品圖片 /* 複製一份相冊圖片 */ $img = $original_img; // 相冊圖片 $pos = strpos(basename($img), '.'); $newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $newname)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $img = $newname; $gallery_img = $img; $gallery_thumb = $img; // 如果系統支持GD,縮放商品圖片,且給商品圖片和相冊圖片加水印 if ($image->gd_version() > 0 && $image->check_img_function($_FILES['goods_img']['type'])) { // 如果設置大小不為0,縮放圖片 if ($_CFG['image_width'] != 0 || $_CFG['image_height'] != 0) { $goods_img = $image->make_thumb('../'. $goods_img , $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']); if ($goods_img === false) { sys_msg($image->error_msg(), 1, array(), false); } } $newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $newname)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $gallery_img = $newname; // 加水印 if (intval($_CFG['watermark_place']) > 0 && !empty($GLOBALS['_CFG']['watermark'])) { if ($image->add_watermark('../'.$goods_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) { sys_msg($image->error_msg(), 1, array(), false); } if ($image->add_watermark('../'. $gallery_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) { sys_msg($image->error_msg(), 1, array(), false); } } // 相冊縮略圖 if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) { $gallery_thumb = $image->make_thumb('../' . $img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); if ($gallery_thumb === false) { sys_msg($image->error_msg(), 1, array(), false); } } } else { /* 複製一份原圖 */ $pos = strpos(basename($img), '.'); $gallery_img = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $gallery_img)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $gallery_thumb = ''; } } // 未上傳,如果自動選擇生成,且上傳了商品圖片,生成所略圖 if (!empty($original_img)) { // 如果設置縮略圖大小不為0,生成縮略圖 if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) { $goods_thumb = $image->make_thumb('../' . $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); if ($goods_thumb === false) { sys_msg($image->error_msg(), 1, array(), false); } } else { $goods_thumb = $original_img; } } $sql = 'INSERT INTO ' . $ecs->table('goods') . "(goods_name, goods_sn, goods_number, cat_id, brand_id, goods_brief, shop_price, market_price, goods_img, goods_thumb, original_img,add_time, last_update, is_best, is_new, is_hot)" . "VALUES('$good_name', '$goods_sn', '$good_number', '$cat_id', '$brand_id', '$good_brief', '$good_price'," . " '$market_price', '$goods_img', '$goods_thumb', '$original_img','" . gmtime() . "', '". gmtime() . "', '$is_best', '$is_new', '$is_hot')"; $db->query($sql); $good_id = $db->insert_id(); /* 如果有圖片,把商品圖片加入圖片相冊 */ if (isset($img)) { $sql = "INSERT INTO " . $ecs->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " . "VALUES ('$good_id', '$gallery_img', '', '$gallery_thumb', '$img')"; $db->query($sql); } } } assign_query_info(); // $smarty->assign('ur_here', '開店嚮導-添加商品'); $smarty->display('setting_third.htm'); } /*------------------------------------------------------ */ //-- 關於 ECSHOP /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'about_us') { assign_query_info(); $smarty->display('about_us.htm'); } /*------------------------------------------------------ */ //-- 拖動的幀 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drag') { $smarty->display('drag.htm');; } /*------------------------------------------------------ */ //-- 檢查訂單 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'check_order') { if (empty($_SESSION['last_check'])) { $_SESSION['last_check'] = gmtime(); make_json_result('', '', array('new_orders' => 0, 'new_paid' => 0)); } /* 新訂單 */ $sql = 'SELECT COUNT(*) FROM ' . $ecs->table('order_info'). " WHERE add_time >= '$_SESSION[last_check]'"; $arr['new_orders'] = $db->getOne($sql); /* 新付款的訂單 */ $sql = 'SELECT COUNT(*) FROM '.$ecs->table('order_info'). ' WHERE pay_time >= ' . $_SESSION['last_check']; $arr['new_paid'] = $db->getOne($sql); $_SESSION['last_check'] = gmtime(); if (!(is_numeric($arr['new_orders']) && is_numeric($arr['new_paid']))) { make_json_error($db->error()); } else { make_json_result('', '', $arr); } } /*------------------------------------------------------ */ //-- Totolist操作 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'save_todolist') { $content = json_str_iconv($_POST["content"]); $sql = "UPDATE" .$GLOBALS['ecs']->table('admin_user'). " SET todolist='" . $content . "' WHERE user_id = " . $_SESSION['admin_id']; $GLOBALS['db']->query($sql); } elseif ($_REQUEST['act'] == 'get_todolist') { $sql = "SELECT todolist FROM " .$GLOBALS['ecs']->table('admin_user'). " WHERE user_id = " . $_SESSION['admin_id']; $content = $GLOBALS['db']->getOne($sql); echo $content; } // 郵件群發處理 elseif ($_REQUEST['act'] == 'send_mail') { if ($_CFG['send_mail_on'] == 'off') { make_json_result('', $_LANG['send_mail_off'], 0); exit(); } $sql = "SELECT * FROM " . $ecs->table('email_sendlist') . " ORDER BY pri DESC, last_send ASC LIMIT 1"; $row = $db->getRow($sql); //發送列表為空 if (empty($row['id'])) { make_json_result('', $_LANG['mailsend_null'], 0); } //發送列表不為空,郵件地址為空 if (!empty($row['id']) && empty($row['email'])) { $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', $_LANG['mailsend_skip'], array('count' => $count, 'goon' => 1)); } //查詢相關模板 $sql = "SELECT * FROM " . $ecs->table('mail_templates') . " WHERE template_id = '$row[template_id]'"; $rt = $db->getRow($sql); //如果是模板,則將已存入email_sendlist的內容作為郵件內容 //否則即是雜質,將mail_templates調出的內容作為郵件內容 if ($rt['type'] == 'template') { $rt['template_content'] = $row['email_content']; } if ($rt['template_id'] && $rt['template_content']) { if (send_mail('', $row['email'], $rt['template_subject'], $rt['template_content'], $rt['is_html'])) { //發送成功 //從列表中刪除 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); //剩餘列表數 $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); if($count > 0) { $msg = sprintf($_LANG['mailsend_ok'],$row['email'],$count); } else { $msg = sprintf($_LANG['mailsend_finished'],$row['email']); } make_json_result('', $msg, array('count' => $count)); } else { //發送出錯 if ($row['error'] < 3) { $time = time(); $sql = "UPDATE " . $ecs->table('email_sendlist') . " SET error = error + 1, pri = 0, last_send = '$time' WHERE id = '$row[id]'"; } else { //將出錯超次的紀錄刪除 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; } $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count)); } } else { //無效的郵件隊列 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count)); } } /*------------------------------------------------------ */ //-- license操作 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'license') { $is_ajax = $_GET['is_ajax']; if (isset($is_ajax) && $is_ajax) { // license 檢查 include_once(ROOT_PATH . 'includes/cls_transport.php'); include_once(ROOT_PATH . 'includes/cls_json.php'); include_once(ROOT_PATH . 'includes/lib_main.php'); include_once(ROOT_PATH . 'includes/lib_license.php'); $license = license_check(); switch ($license['flag']) { case 'login_succ': if (isset($license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '') { make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth'])); } else { make_json_error(0); } break; case 'login_fail': case 'login_ping_fail': make_json_error(0); break; case 'reg_succ': $_license = license_check(); switch ($_license['flag']) { case 'login_succ': if (isset($_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '') { make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth'])); } else { make_json_error(0); } break; case 'login_fail': case 'login_ping_fail': make_json_error(0); break; } break; case 'reg_fail': case 'reg_ping_fail': make_json_error(0); break; } } else { make_json_error(0); } } /** * license check * @return bool */ function license_check() { // return 返回數組 $return_array = array(); // 取出網店 license $license = get_shop_license(); // 檢測網店 license if (!empty($license['certificate_id']) && !empty($license['token']) && !empty($license['certi'])) { // license(登錄) $return_array = license_login(); } else { // license(註冊) $return_array = license_reg(); } return $return_array; } ?>
Shallmay14/Qiandynasty
shop/admin/index.php
PHP
gpl-2.0
48,360
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, [email protected] * * 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. */ package edu.ku.brc.af.ui.forms.persist; import static edu.ku.brc.helpers.XMLHelper.getAttr; import static edu.ku.brc.ui.UIHelper.createDuplicateJGoodiesDef; import static edu.ku.brc.ui.UIRegistry.getResourceString; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Vector; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ScrollPaneConstants; import javax.swing.table.DefaultTableModel; import org.apache.commons.betwixt.XMLIntrospector; import org.apache.commons.betwixt.io.BeanWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dom4j.Element; import org.dom4j.Node; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import edu.ku.brc.af.core.db.DBFieldInfo; import edu.ku.brc.af.core.db.DBRelationshipInfo; import edu.ku.brc.af.core.db.DBTableChildIFace; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.db.DBTableInfo; import edu.ku.brc.af.prefs.AppPreferences; import edu.ku.brc.af.ui.forms.FormDataObjIFace; import edu.ku.brc.af.ui.forms.FormHelper; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterIFace; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr; import edu.ku.brc.af.ui.forms.validation.TypeSearchForQueryFactory; import edu.ku.brc.ui.CustomFrame; import edu.ku.brc.ui.UIHelper; import edu.ku.brc.ui.UIRegistry; import edu.ku.brc.helpers.XMLHelper; /** * Factory that creates Views from ViewSet files. This class uses the singleton ViewSetMgr to verify the View Set Name is unique. * If it is not unique than it throws an exception.<br> In this case a "form" is really the definition of a form. The form's object hierarchy * is used to creates the forms using Swing UI objects. The classes will also be used by the forms editor. * @code_status Beta ** * @author rods */ public class ViewLoader { public static final int DEFAULT_ROWS = 4; public static final int DEFAULT_COLS = 10; public static final int DEFAULT_SUBVIEW_ROWS = 5; // Statics private static final Logger log = Logger.getLogger(ViewLoader.class); private static final ViewLoader instance = new ViewLoader(); private static final String ID = "id"; private static final String NAME = "name"; private static final String TYPE = "type"; private static final String LABEL = "label"; private static final String DESC = "desc"; private static final String TITLE = "title"; private static final String CLASSNAME = "class"; private static final String GETTABLE = "gettable"; private static final String SETTABLE = "settable"; private static final String INITIALIZE = "initialize"; private static final String DSPUITYPE = "dspuitype"; private static final String VALIDATION = "validation"; private static final String ISREQUIRED = "isrequired"; private static final String RESOURCELABELS = "useresourcelabels"; // Data Members protected boolean doingResourceLabels = false; protected String viewSetName = null; // Members needed for verification protected static boolean doFieldVerification = true; protected static boolean isTreeClass = false; protected static DBTableInfo fldVerTableInfo = null; protected static FormViewDef fldVerFormViewDef = null; protected static String colDefType = null; protected static CustomFrame verifyDlg = null; protected FieldVerifyTableModel fldVerTableModel = null; // Debug //protected static ViewDef gViewDef = null; static { doFieldVerification = AppPreferences.getLocalPrefs().getBoolean("verify_field_names", false); } /** * Default Constructor * */ protected ViewLoader() { // do nothing } /** * Creates the view. * @param element the element to build the View from * @param altViewsViewDefName the hashtable to track the AltView's ViewDefName * @return the View * @throws Exception */ protected static ViewIFace createView(final Element element, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { String name = element.attributeValue(NAME); String objTitle = getAttr(element, "objtitle", null); String className = element.attributeValue(CLASSNAME); String desc = getDesc(element); String businessRules = getAttr(element, "busrules", null); boolean isInternal = getAttr(element, "isinternal", true); DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(className); if (ti != null && StringUtils.isEmpty(objTitle)) { objTitle = ti.getTitle(); } View view = new View(instance.viewSetName, name, objTitle, className, businessRules != null ? businessRules.trim() : null, getAttr(element, "usedefbusrule", true), isInternal, desc); // Later we should get this from a properties file. if (ti != null) { view.setTitle(ti.getTitle()); } /*if (!isInternal) { System.err.println(StringUtils.replace(name, " ", "_")+"="+UIHelper.makeNamePretty(name)); }*/ Element altviews = (Element)element.selectSingleNode("altviews"); if (altviews != null) { AltViewIFace defaultAltView = null; AltView.CreationMode defaultMode = AltView.parseMode(getAttr(altviews, "mode", ""), AltViewIFace.CreationMode.VIEW); String selectorName = altviews.attributeValue("selector"); view.setDefaultMode(defaultMode); view.setSelectorName(selectorName); Hashtable<String, Boolean> nameCheckHash = new Hashtable<String, Boolean>(); // iterate through child elements for ( Iterator<?> i = altviews.elementIterator( "altview" ); i.hasNext(); ) { Element altElement = (Element) i.next(); AltView.CreationMode mode = AltView.parseMode(getAttr(altElement, "mode", ""), AltViewIFace.CreationMode.VIEW); String altName = altElement.attributeValue(NAME); String viewDefName = altElement.attributeValue("viewdef"); String title = altElement.attributeValue(TITLE); boolean isValidated = getAttr(altElement, "validated", mode == AltViewIFace.CreationMode.EDIT); boolean isDefault = getAttr(altElement, "default", false); // Make sure we only have one default view if (defaultAltView != null && isDefault) { isDefault = false; } // Check to make sure all the AlViews have different names. Boolean nameExists = nameCheckHash.get(altName); if (nameExists == null) // no need to check the boolean { AltView altView = new AltView(view, altName, title, mode, isValidated, isDefault, null); // setting a null viewdef altViewsViewDefName.put(altView, viewDefName); if (StringUtils.isNotEmpty(selectorName)) { altView.setSelectorName(selectorName); String selectorValue = altElement.attributeValue("selector_value"); if (StringUtils.isNotEmpty(selectorValue)) { altView.setSelectorValue(selectorValue); } else { FormDevHelper.appendFormDevError("Selector Value is missing for viewDefName["+viewDefName+"] altName["+altName+"]"); } } if (defaultAltView == null && isDefault) { defaultAltView = altView; } view.addAltView(altView); nameCheckHash.put(altName, true); } else { log.error("The altView name["+altName+"] already exists!"); } nameCheckHash.clear(); // why not? } // No default Alt View was indicated, so choose the first one (if there is one) if (defaultAltView == null && view.getAltViews() != null && view.getAltViews().size() > 0) { view.getAltViews().get(0).setDefault(true); } } return view; } /** * Creates a ViewDef * @param element the element to build the ViewDef from * @return a viewdef * @throws Exception */ private static ViewDef createViewDef(final Element element) throws Exception { String name = element.attributeValue(NAME); String className = element.attributeValue(CLASSNAME); String gettableClassName = element.attributeValue(GETTABLE); String settableClassName = element.attributeValue(SETTABLE); String desc = getDesc(element); String resLabels = getAttr(element, RESOURCELABELS, "false"); boolean useResourceLabels = resLabels.equals("true"); if (isEmpty(name)) { FormDevHelper.appendFormDevError("Name is null for element["+element.asXML()+"]"); return null; } if (isEmpty(className)) { FormDevHelper.appendFormDevError("className is null. name["+name+"] for element["+element.asXML()+"]"); return null; } if (isEmpty(gettableClassName)) { FormDevHelper.appendFormDevError("gettableClassName Name is null.name["+name+"] classname["+className+"]"); return null; } DBTableInfo tableinfo = DBTableIdMgr.getInstance().getByClassName(className); ViewDef.ViewType type = null; try { type = ViewDefIFace.ViewType.valueOf(element.attributeValue(TYPE)); } catch (Exception ex) { String msg = "view["+name+"] has illegal type["+element.attributeValue(TYPE)+"]"; log.error(msg, ex); FormDevHelper.appendFormDevError(msg, ex); return null; } ViewDef viewDef = null;//new ViewDef(type, name, className, gettableClassName, settableClassName, desc); switch (type) { case rstable: case formtable : case form : viewDef = createFormViewDef(element, type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, tableinfo); break; case table : //view = createTableView(element, id, name, className, gettableClassName, settableClassName, // desc, instance.doingResourceLabels, isValidated); break; case field : //view = createFormView(FormView.ViewType.field, element, id, name, gettableClassName, settableClassName, // className, desc, instance.doingResourceLabels, isValidated); break; case iconview: viewDef = createIconViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); break; } return viewDef; } /** * Gets the optional description text * @param element the parent element of the desc node * @return the string of the text or null */ protected static String getDesc(final Element element) { String desc = null; Element descElement = (Element)element.selectSingleNode(DESC); if (descElement != null) { desc = descElement.getTextTrim(); } return desc; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param views the list to be filled * @throws Exception for duplicate view set names or if a Form ID is not unique */ public static String getViews(final Element doc, final Hashtable<String, ViewIFace> views, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { instance.viewSetName = doc.attributeValue(NAME); /* System.err.println("#################################################"); System.err.println("# "+instance.viewSetName); System.err.println("#################################################"); */ Element viewsElement = (Element)doc.selectSingleNode("views"); if (viewsElement != null) { for ( Iterator<?> i = viewsElement.elementIterator( "view" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewIFace view = createView(element, altViewsViewDefName); if (view != null) { if (views.get(view.getName()) == null) { views.put(view.getName(), view); } else { String msg = "View Set ["+instance.viewSetName+"] ["+view.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } return instance.viewSetName; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param viewDefs the list to be filled * @param doMapDefinitions tells it to map and clone the definitions for formtables (use false for the FormEditor) * @return the viewset name * @throws Exception for duplicate view set names or if a ViewDef name is not unique */ public static String getViewDefs(final Element doc, final Hashtable<String, ViewDefIFace> viewDefs, @SuppressWarnings("unused") final Hashtable<String, ViewIFace> views, final boolean doMapDefinitions) throws Exception { colDefType = AppPreferences.getLocalPrefs().get("ui.formatting.formtype", UIHelper.getOSTypeAsStr()); instance.viewSetName = doc.attributeValue(NAME); Element viewDefsElement = (Element)doc.selectSingleNode("viewdefs"); if (viewDefsElement != null) { for ( Iterator<?> i = viewDefsElement.elementIterator( "viewdef" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewDef viewDef = createViewDef(element); if (viewDef != null) { if (viewDefs.get(viewDef.getName()) == null) { viewDefs.put(viewDef.getName(), viewDef); } else { String msg = "View Set ["+instance.viewSetName+"] the View Def Name ["+viewDef.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } if (doMapDefinitions) { mapDefinitionViewDefs(viewDefs); } } return instance.viewSetName; } /** * Re-maps and clones the definitions. * @param viewDefs the hash table to be mapped * @throws Exception */ public static void mapDefinitionViewDefs(final Hashtable<String, ViewDefIFace> viewDefs) throws Exception { // Now that all the definitions have been read in // cycle thru and have all the tableform objects clone there definitions for (ViewDefIFace viewDef : new Vector<ViewDefIFace>(viewDefs.values())) { if (viewDef.getType() == ViewDefIFace.ViewType.formtable) { String viewDefName = ((FormViewDefIFace)viewDef).getDefinitionName(); if (viewDefName != null) { //log.debug(viewDefName); ViewDefIFace actualDef = viewDefs.get(viewDefName); if (actualDef != null) { viewDefs.remove(viewDef.getName()); actualDef = (ViewDef)actualDef.clone(); actualDef.setType(ViewDefIFace.ViewType.formtable); actualDef.setName(viewDef.getName()); viewDefs.put(actualDef.getName(), actualDef); } else { String msg = "Couldn't find the ViewDef for formtable definition name["+((FormViewDefIFace)viewDef).getDefinitionName()+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } } /** * Processes all the AltViews * @param aFormView the form they should be associated with * @param aElement the element to process */ public static Hashtable<String, String> getEnableRules(final Element element) { Hashtable<String, String> rulesList = new Hashtable<String, String>(); if (element != null) { Element enableRules = (Element)element.selectSingleNode("enableRules"); if (enableRules != null) { // iterate through child elements of root with element name "foo" for ( Iterator<?> i = enableRules.elementIterator( "rule" ); i.hasNext(); ) { Element ruleElement = (Element) i.next(); String id = getAttr(ruleElement, ID, ""); if (isNotEmpty(id)) { rulesList.put(id, ruleElement.getTextTrim()); } else { String msg = "The name is missing for rule["+ruleElement.getTextTrim()+"] is missing."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else { log.error("View Set ["+instance.viewSetName+"] element ["+element+"] is null."); } return rulesList; } /** * Gets the string (or creates one) from a columnDef * @param element the DOM element to process * @param attrName the name of the element to go get all the elements (strings) from * @param numRows the number of rows * @param item * @return the String representing the column definition for JGoodies */ protected static String createDef(final Element element, final String attrName, final int numRows, final FormViewDef.JGDefItem item) { Element cellDef = null; if (attrName.equals("columnDef")) { // For columnDef(s) we can mark one or more as being platform specific // but if we can't find a default one (no 'os' defined) // then we ultimately pick the first one. List<?> list = element.selectNodes(attrName); if (list.size() == 1) { cellDef = (Element)list.get(0); // pick the first one if there is only one. } else { String osTypeStr = UIHelper.getOSTypeAsStr(); Element defCD = null; Element defOSCD = null; Element ovrOSCD = null; for (Object obj : list) { Element ce = (Element)obj; String osType = getAttr(ce, "os", null); if (osType == null) { defCD = ce; // ok we found the default one } else { if (osType.equals(osTypeStr)) { defOSCD = ce; // we found the matching our OS } if (colDefType != null && osType.equals(colDefType)) { ovrOSCD = ce; // we found the one matching prefs } } } if (ovrOSCD != null) { cellDef = ovrOSCD; } else if (defOSCD != null) { cellDef = defOSCD; } else if (defCD != null) { cellDef = defCD; } else { // ok, we couldn't find one for our platform, so use the default // or pick the first one. cellDef = (Element)list.get(0); } } } else { // this is for rowDef cellDef = (Element)element.selectSingleNode(attrName); } if (cellDef != null) { String cellText = cellDef.getText(); String cellStr = getAttr(cellDef, "cell", null); String sepStr = getAttr(cellDef, "sep", null); item.setDefStr(cellText); item.setCellDefStr(cellStr); item.setSepDefStr(sepStr); if (StringUtils.isNotEmpty(cellStr) && StringUtils.isNotEmpty(sepStr)) { boolean auto = getAttr(cellDef, "auto", false); item.setAuto(auto); if (auto) { String autoStr = createDuplicateJGoodiesDef(cellStr, sepStr, numRows) + (StringUtils.isNotEmpty(cellText) ? ("," + cellText) : ""); item.setDefStr(autoStr); return autoStr; } // else FormDevHelper.appendFormDevError("Element ["+element.getName()+"] Cell or Sep is null for 'dup' or 'auto 'on column def."); return ""; } // else item.setAuto(false); return cellText; } // else String msg = "Element ["+element.getName()+"] must have a columnDef"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } /** * Returns a resource string if it is suppose to * @param label the label or the label key * @return Returns a resource string if it is suppose to */ protected static String getResourceLabel(final String label) { if (isNotEmpty(label) && StringUtils.deleteWhitespace(label).length() > 0) { return instance.doingResourceLabels ? getResourceString(label) : label; } // else return ""; } /** * Returns a Label from the cell and gets the resource string for it if necessary * @param cellElement the cell * @param labelId the Id of the resource or the string * @return the localized string (if necessary) */ protected static String getLabel(final Element cellElement) { String lbl = getAttr(cellElement, LABEL, null); if (lbl == null || lbl.equals("##")) { return "##"; } return getResourceLabel(lbl); } /** * Processes all the rows * @param element the parent DOM element of the rows * @param cellRows the list the rows are to be added to */ protected static void processRows(final Element element, final List<FormRowIFace> cellRows, final DBTableInfo tableinfo) { Element rowsElement = (Element)element.selectSingleNode("rows"); if (rowsElement != null) { byte rowNumber = 0; for ( Iterator<?> i = rowsElement.elementIterator( "row" ); i.hasNext(); ) { Element rowElement = (Element) i.next(); FormRow formRow = new FormRow(); formRow.setRowNumber(rowNumber); for ( Iterator<?> cellIter = rowElement.elementIterator( "cell" ); cellIter.hasNext(); ) { Element cellElement = (Element)cellIter.next(); String cellId = getAttr(cellElement, ID, ""); String cellName = getAttr(cellElement, NAME, cellId); // let the name default to the id if it doesn't have a name int colspan = getAttr(cellElement, "colspan", 1); int rowspan = getAttr(cellElement, "rowspan", 1); /*boolean isReq = getAttr(cellElement, ISREQUIRED, false); if (isReq) { System.err.println(String.format("%s\t%s\t%s\t%s", gViewDef.getName(), cellId, cellName, tableinfo != null ? tableinfo.getTitle() : "N/A")); }*/ FormCell.CellType cellType = null; FormCellIFace cell = null; try { cellType = FormCellIFace.CellType.valueOf(cellElement.attributeValue(TYPE)); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] Type[%s]", cellName, cellId, cellElement.attributeValue(TYPE))); return; } if (doFieldVerification && fldVerTableInfo != null && cellType == FormCellIFace.CellType.field && StringUtils.isNotEmpty(cellId) && !cellName.equals("this")) { processFieldVerify(cellName, cellId, rowNumber); } switch (cellType) { case label: { cell = formRow.addCell(new FormCellLabel(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "labelfor", ""), getAttr(cellElement, "icon", null), getAttr(cellElement, "recordobj", false), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case separator: { cell = formRow.addCell(new FormCellSeparator(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "collapse", ""), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case field: { String uitypeStr = getAttr(cellElement, "uitype", ""); String format = getAttr(cellElement, "format", ""); String formatName = getAttr(cellElement, "formatname", ""); String uiFieldFormatterName = getAttr(cellElement, "uifieldformatter", ""); int cols = getAttr(cellElement, "cols", DEFAULT_COLS); // XXX PREF for default width of text field int rows = getAttr(cellElement, "rows", DEFAULT_ROWS); // XXX PREF for default heightof text area String validationType = getAttr(cellElement, "valtype", "Changed"); String validationRule = getAttr(cellElement, VALIDATION, ""); String initialize = getAttr(cellElement, INITIALIZE, ""); boolean isRequired = getAttr(cellElement, ISREQUIRED, false); String pickListName = getAttr(cellElement, "picklist", ""); if (isNotEmpty(format) && isNotEmpty(formatName)) { String msg = "Both format and formatname cannot both be set! ["+cellName+"] ignoring format"; log.error(msg); FormDevHelper.appendFormDevError(msg); format = ""; } Properties properties = UIHelper.parseProperties(initialize); if (isEmpty(uitypeStr)) { // XXX DEBUG ONLY PLease REMOVE LATER //log.debug("***************************************************************************"); //log.debug("***** Cell Id["+cellId+"] Name["+cellName+"] uitype is empty and should be 'text'. (Please Fix!)"); //log.debug("***************************************************************************"); uitypeStr = "text"; } // THis switch is used to get the "display type" and // set up other vars needed for creating the controls FormCellFieldIFace.FieldType uitype = null; try { uitype = FormCellFieldIFace.FieldType.valueOf(uitypeStr); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] uitype[%s] is in error", cellName, cellId, uitypeStr)); uitype = FormCellFieldIFace.FieldType.text; // default to text } String dspUITypeStr = null; switch (uitype) { case textarea: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextarea"); break; case textareabrief: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textareabrief"); break; case querycbx: { dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textfieldinfo"); String fmtName = TypeSearchForQueryFactory.getInstance().getDataObjFormatterName(properties.getProperty("name")); if (isEmpty(formatName) && isNotEmpty(fmtName)) { formatName = fmtName; } break; } case formattedtext: { validationRule = getAttr(cellElement, VALIDATION, "formatted"); // XXX Is this OK? dspUITypeStr = getAttr(cellElement, DSPUITYPE, "formattedtext"); //------------------------------------------------------- // This part should be moved to the ViewFactory // because it is the only part that need the Schema Information //------------------------------------------------------- if (isNotEmpty(uiFieldFormatterName)) { UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName); if (uiFormatter == null) { String msg = "Couldn't find formatter["+uiFieldFormatterName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } else // ok now check the schema for the UI formatter { if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (fieldInfo.getFormatter() != null) { uiFieldFormatterName = fieldInfo.getFormatter().getName(); } else if (fieldInfo.getDataClass().isAssignableFrom(Date.class) || fieldInfo.getDataClass().isAssignableFrom(Calendar.class)) { String msg = "Missing Date Formatter for ["+cellName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); uiFieldFormatterName = "Date"; UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName); if (uiFormatter == null) { uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } else { uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } } } break; } case url: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); break; case list: case image: case tristate: case checkbox: case password: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); break; case plugin: case button: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); String ttl = properties.getProperty(TITLE); if (ttl != null) { properties.put(TITLE, getResourceLabel(ttl)); } break; case spinner: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); properties = UIHelper.parseProperties(initialize); break; case combobox: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textpl"); if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (StringUtils.isNotEmpty(pickListName)) { fieldInfo.setPickListName(pickListName); } else { pickListName = fieldInfo.getPickListName(); } } } break; default: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); break; } //switch FormCellFieldIFace.FieldType dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); try { dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] dspuitype[%s] is in error", cellName, cellId, dspUIType)); uitype = FormCellFieldIFace.FieldType.label; // default to text } // check to see see if the validation is a node in the cell if (isEmpty(validationRule)) { Element valNode = (Element)cellElement.selectSingleNode(VALIDATION); if (valNode != null) { String str = valNode.getTextTrim(); if (isNotEmpty(str)) { validationRule = str; } } } boolean isEncrypted = getAttr(cellElement, "isencrypted", false); boolean isReadOnly = uitype == FormCellFieldIFace.FieldType.dsptextfield || uitype == FormCellFieldIFace.FieldType.dsptextarea || uitype == FormCellFieldIFace.FieldType.label; FormCellField field = new FormCellField(FormCellIFace.CellType.field, cellId, cellName, uitype, dspUIType, format, formatName, uiFieldFormatterName, isRequired, cols, rows, colspan, rowspan, validationType, validationRule, isEncrypted); String labelStr = uitype == FormCellFieldIFace.FieldType.checkbox ? getLabel(cellElement) : getAttr(cellElement, "label", ""); field.setLabel(labelStr); field.setReadOnly(getAttr(cellElement, "readonly", isReadOnly)); field.setDefaultValue(getAttr(cellElement, "default", "")); field.setPickListName(pickListName); field.setChangeListenerOnly(getAttr(cellElement, "changesonly", true) && !isRequired); field.setProperties(properties); cell = formRow.addCell(field); break; } case command: { cell = formRow.addCell(new FormCellCommand(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "commandtype", ""), getAttr(cellElement, "action", ""))); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case panel: { FormCellPanel cellPanel = new FormCellPanel(cellId, cellName, getAttr(cellElement, "paneltype", ""), getAttr(cellElement, "coldef", "p"), getAttr(cellElement, "rowdef", "p"), colspan, rowspan); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cellPanel.setProperties(UIHelper.parseProperties(initialize)); } processRows(cellElement, cellPanel.getRows(), tableinfo); fixLabels(cellPanel.getName(), cellPanel.getRows(), tableinfo); cell = formRow.addCell(cellPanel); break; } case subview: { Properties properties = UIHelper.parseProperties(getAttr(cellElement, INITIALIZE, null)); String svViewSetName = cellElement.attributeValue("viewsetname"); if (isEmpty(svViewSetName)) { svViewSetName = null; } if (instance.doingResourceLabels && properties != null) { String title = properties.getProperty(TITLE); if (title != null) { properties.setProperty(TITLE, UIRegistry.getResourceString(title)); } } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, svViewSetName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), getAttr(cellElement, "defaulttype", null), getAttr(cellElement, "rows", DEFAULT_SUBVIEW_ROWS), colspan, rowspan, getAttr(cellElement, "single", false))); cell.setProperties(properties); break; } case iconview: { String vsName = cellElement.attributeValue("viewsetname"); if (isEmpty(vsName)) { vsName = instance.viewSetName; } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, vsName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), colspan, rowspan)); break; } case statusbar: { cell = formRow.addCell(new FormCell(FormCellIFace.CellType.statusbar, cellId, cellName, colspan, rowspan)); break; } default: { // what is this? log.error("Encountered unknown cell type"); continue; } } // switch cell.setIgnoreSetGet(getAttr(cellElement, "ignore", false)); } cellRows.add(formRow); rowNumber++; } } } /** * @param cellName * @param cellId * @param rowNumber */ private static void processFieldVerify(final String cellName, final String cellId, final int rowNumber) { try { boolean isOK = false; if (StringUtils.contains(cellName, '.')) { DBTableInfo tblInfo = fldVerTableInfo; String[] fieldNames = StringUtils.split(cellName, "."); for (int i=0;i<fieldNames.length-1;i++) { String type = null; DBTableChildIFace child = tblInfo.getItemByName(fieldNames[i]); if (child instanceof DBFieldInfo) { DBFieldInfo fldInfo = (DBFieldInfo)child; type = fldInfo.getType(); if (type != null) { DBTableInfo tInfo = DBTableIdMgr.getInstance().getByClassName(type); tblInfo = tInfo != null ? tInfo : tblInfo; } isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } else if (child instanceof DBRelationshipInfo) { DBRelationshipInfo relInfo = (DBRelationshipInfo)child; type = relInfo.getDataClass().getName(); if (type != null) { tblInfo = DBTableIdMgr.getInstance().getByClassName(type); } } //System.out.println(type); } if (tblInfo != null) { isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } } else { isOK = fldVerTableInfo.getItemByName(cellName) != null; } if (!isOK) { String msg = " ViewSet["+instance.viewSetName+"]\n ViewDef["+fldVerFormViewDef.getName()+"]\n The cell name ["+cellName+"] for cell with Id ["+cellId+"] is not a field\n in Data Object["+fldVerTableInfo.getName()+"]\n on Row ["+rowNumber+"]"; if (!isTreeClass) { instance.fldVerTableModel.addRow(instance.viewSetName, fldVerFormViewDef.getName(), cellId, cellName, Integer.toString(rowNumber)); } log.error(msg); } } catch (Exception ex) { log.error(ex); } } /** * @param element the DOM element for building the form * @param type the type of form to be built * @param id the id of the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @param tableinfo table info * @return a form view of type "form" */ protected static FormViewDef createFormViewDef(final Element element, final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels, final DBTableInfo tableinfo) { FormViewDef formViewDef = new FormViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, XMLHelper.getAttr(element, "editableDlg", true)); fldVerTableInfo = null; if (type != ViewDefIFace.ViewType.formtable) { if (doFieldVerification) { if (instance.fldVerTableModel == null) { instance.createFieldVerTableModel(); } try { //log.debug(className); Class<?> classObj = Class.forName(className); if (FormDataObjIFace.class.isAssignableFrom(classObj)) { fldVerTableInfo = DBTableIdMgr.getInstance().getByClassName(className); isTreeClass = fldVerTableInfo != null && fldVerTableInfo.getFieldByName("highestChildNodeNumber") != null; fldVerFormViewDef = formViewDef; } } catch (ClassNotFoundException ex) { String msg = "ClassNotFoundException["+className+"] Name["+name+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, comments, ex); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, ex); } } List<FormRowIFace> rows = formViewDef.getRows(); instance.doingResourceLabels = useResourceLabels; //gViewDef = formViewDef; processRows(element, rows, tableinfo); instance.doingResourceLabels = false; createDef(element, "columnDef", rows.size(), formViewDef.getColumnDefItem()); createDef(element, "rowDef", rows.size(), formViewDef.getRowDefItem()); formViewDef.setEnableRules(getEnableRules(element)); fixLabels(formViewDef.getName(), rows, tableinfo); } else { Node defNode = element.selectSingleNode("definition"); if (defNode != null) { String defName = defNode.getText(); if (StringUtils.isNotEmpty(defName)) { formViewDef.setDefinitionName(defName); return formViewDef; } } String msg = "formtable is missing or has empty <defintion> node"; log.error(msg); FormDevHelper.appendFormDevError(msg); return null; } return formViewDef; } /** * @param fieldName * @param tableInfo * @return */ protected static String getTitleFromFieldName(final String fieldName, final DBTableInfo tableInfo) { DBTableChildIFace derivedCI = null; if (fieldName.indexOf(".") > -1) { derivedCI = FormHelper.getChildInfoFromPath(fieldName, tableInfo); if (derivedCI == null) { String msg = "The name 'path' ["+fieldName+"] was not valid in ViewSet ["+instance.viewSetName+"]"; FormDevHelper.appendFormDevError(msg); log.error(msg); return ""; } } DBTableChildIFace tblChild = derivedCI != null ? derivedCI : tableInfo.getItemByName(fieldName); if (tblChild == null) { String msg = "The Field Name ["+fieldName+"] was not in the Table ["+tableInfo.getTitle()+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } return tblChild.getTitle(); } /** * @param rows * @param tableInfo */ protected static void fixLabels(final String name, final List<FormRowIFace> rows, final DBTableInfo tableInfo) { if (tableInfo == null) { return; } Hashtable<String, String> fldIdMap = new Hashtable<String, String>(); for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.field || cell.getType() == FormCellIFace.CellType.subview) { fldIdMap.put(cell.getIdent(), cell.getName()); }/* else { System.err.println("Skipping ["+cell.getIdent()+"] " + cell.getType()); }*/ } } for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.label) { FormCellLabelIFace lblCell = (FormCellLabelIFace)cell; String label = lblCell.getLabel(); if (label.length() == 0 || label.equals("##")) { String idFor = lblCell.getLabelFor(); if (StringUtils.isNotEmpty(idFor)) { String fieldName = fldIdMap.get(idFor); if (StringUtils.isNotEmpty(fieldName)) { if (!fieldName.equals("this")) { //FormCellFieldIFace fcf = get lblCell.setLabel(getTitleFromFieldName(fieldName, tableInfo)); } } else { String msg = "Setting Label - Form control with id["+idFor+"] is not in ViewDef or Panel ["+name+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else if (cell.getType() == FormCellIFace.CellType.field && cell instanceof FormCellFieldIFace && ((((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.checkbox) || (((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.tristate))) { FormCellFieldIFace fcf = (FormCellFieldIFace)cell; if (fcf.getLabel().equals("##")) { fcf.setLabel(getTitleFromFieldName(cell.getName(), tableInfo)); } } } } } /** * @param type the type of form to be built * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "form" */ protected static ViewDef createIconViewDef(final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { ViewDef formView = new ViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); //formView.setEnableRules(getEnableRules(element)); return formView; } /** * Creates a Table Form View * @param typeName the type of form to be built * @param element the DOM element for building the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "table" */ protected static TableViewDefIFace createTableView(final Element element, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { TableViewDefIFace tableView = new TableViewDef( name, className, gettableClassName, settableClassName, desc, useResourceLabels); //tableView.setResourceLabels(resLabels); Element columns = (Element)element.selectSingleNode("columns"); if (columns != null) { for ( Iterator<?> i = columns.elementIterator( "column" ); i.hasNext(); ) { Element colElement = (Element) i.next(); FormColumn column = new FormColumn(colElement.attributeValue(NAME), colElement.attributeValue(LABEL), getAttr(colElement, "dataobjformatter", null), getAttr(colElement, "format", null) ); tableView.addColumn(column); } } return tableView; } /** * Save out a viewSet to a file * @param viewSet the viewSet to save * @param filename the filename (full path) as to where to save it */ public static void save(final ViewSet viewSet, final String filename) { try { Vector<ViewSet> viewsets = new Vector<ViewSet>(); viewsets.add(viewSet); File file = new File(filename); FileWriter fw = new FileWriter(file); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); BeanWriter beanWriter = new BeanWriter(fw); XMLIntrospector introspector = beanWriter.getXMLIntrospector(); introspector.getConfiguration().setWrapCollectionsInElement(false); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.setWriteEmptyElements(false); beanWriter.enablePrettyPrint(); beanWriter.write(viewSet); fw.close(); } catch(Exception ex) { log.error("error writing views", ex); } } //-------------------------------------------------------------------------------------------- //-- Field Verify Methods, Classes, Helpers //-------------------------------------------------------------------------------------------- public void createFieldVerTableModel() { fldVerTableModel = new FieldVerifyTableModel(); } /** * @return the doFieldVerification */ public static boolean isDoFieldVerification() { return doFieldVerification; } /** * @param doFieldVerification the doFieldVerification to set */ public static void setDoFieldVerification(boolean doFieldVerification) { ViewLoader.doFieldVerification = doFieldVerification; } public static void clearFieldVerInfo() { if (instance.fldVerTableModel != null) { instance.fldVerTableModel.clear(); } } /** * Di */ public static void displayFieldVerInfo() { if (verifyDlg != null) { verifyDlg.setVisible(false); verifyDlg.dispose(); verifyDlg = null; } System.err.println("------------- "+(instance.fldVerTableModel != null ? instance.fldVerTableModel.getRowCount() : "null")); if (instance.fldVerTableModel != null && instance.fldVerTableModel.getRowCount() > 0) { JLabel lbl = UIHelper.createLabel("<html><i>(Some of fields are special buttons or labal names. Review them to make sure you have not <br>mis-named any of the fields you are working with.)"); final JTable table = new JTable(instance.fldVerTableModel); UIHelper.calcColumnWidths(table); CellConstraints cc = new CellConstraints(); JScrollPane sp = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,4px,p")); pb.add(sp, cc.xy(1, 1)); pb.add(lbl, cc.xy(1, 3)); pb.setDefaultDialogBorder(); verifyDlg = new CustomFrame("Field Names on Form, but not in Database : "+instance.fldVerTableModel.getRowCount(), CustomFrame.OK_BTN, pb.getPanel()) { @Override protected void okButtonPressed() { super.okButtonPressed(); table.setModel(new DefaultTableModel()); dispose(); verifyDlg = null; } }; verifyDlg.setOkLabel(getResourceString("CLOSE")); verifyDlg.createUI(); verifyDlg.setVisible(true); } } class FieldVerifyTableModel extends DefaultTableModel { protected Vector<List<String>> rowData = new Vector<List<String>>(); protected String[] colNames = {"ViewSet", "View Def", "Cell Id", "Cell Name", "Row"}; protected Hashtable<String, Boolean> nameHash = new Hashtable<String, Boolean>(); public FieldVerifyTableModel() { super(); } public void clear() { for (List<String> list : rowData) { list.clear(); } rowData.clear(); nameHash.clear(); } public void addRow(final String viewSet, final String viewDef, final String cellId, final String cellName, final String rowInx) { String key = viewSet + viewDef + cellId; if (nameHash.get(key) == null) { List<String> row = new ArrayList<String>(5); row.add(viewSet); row.add(viewDef); row.add(cellId); row.add(cellName); row.add(rowInx); rowData.add(row); nameHash.put(key, true); } } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnCount() */ @Override public int getColumnCount() { return colNames.length; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnName(int) */ @Override public String getColumnName(int column) { return colNames[column]; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getRowCount() */ @Override public int getRowCount() { return rowData == null ? 0 : rowData.size(); } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getValueAt(int, int) */ @Override public Object getValueAt(int row, int column) { List<String> rowList = rowData.get(row); return rowList.get(column); } } }
specify/specify6
src/edu/ku/brc/af/ui/forms/persist/ViewLoader.java
Java
gpl-2.0
72,771
#!/bin/bash RRD=/data/mirror/rrd PNG=/data/mirror/www/size for file in $RRD/*; do tree=`basename $file` tree=${tree/.rrd/} rrdtool graph $PNG/$tree-week.png --imgformat PNG \ --end now --start end-1w \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null rrdtool graph $PNG/$tree-month.png --imgformat PNG \ --end now --start end-1m \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null rrdtool graph $PNG/$tree-year.png --imgformat PNG \ --end now --start end-1y \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null done
osuosl/osuosl-mirror-sync
mirror-stats/mirror-size-graph.sh
Shell
gpl-2.0
746
/* Copyright: © 2011 Thomas Stein, CodeLounge.de <mailto:[email protected]> <http://www.codelounge.de/> Released under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License, along with this software. In the main directory, see: licence.txt If not, see: <http://www.gnu.org/licenses/>. */ /* * MBP - Mobile boilerplate helper functions */ (function(document){ window.MBP = window.MBP || {}; // Fix for iPhone viewport scale bug // http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/ MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'); MBP.ua = navigator.userAgent; MBP.scaleFix = function () { if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) { MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"; document.addEventListener("gesturestart", MBP.gestureStart, false); } }; MBP.gestureStart = function () { MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"; }; // Hide URL Bar for iOS // http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/ MBP.hideUrlBar = function () { /iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000), /iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000); }; }); jQuery( function() { $("a.facebox").fancybox(); //$("a.fancybox").prettyPhoto({ // social_tools: false //}); jQuery('.entenlogo').click(function() { $('.entenlogo').hide(); }); var current_url = $(location).attr('href'); //console.log($(location).attr('href')); jQuery('body').bind( 'taphold', function( e ) { //$('#next_post_link').attr('refresh'); //$('#previous_post_link').attr('refresh'); $('#page').page('refresh'); var next_url = $('#next_post_link').attr('href'); var previous_url = $('#previous_post_link').attr('href'); console.log(next_url + ' --- ' + previous_url); e.stopImmediatePropagation(); return false; } ); jQuery('body').bind( 'swipeleft', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Left: " + next_url + ' --- ' + previous_url); if (undefined != previous_url) { //$.mobile.changePage( previous_url,"slide", true); $.mobile.changePage( previous_url, { transition: "slide", reverse: false, changeHash: true }); e.stopImmediatePropagation(); return false; } } ); jQuery('body').bind( 'swiperight', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Right: " + next_url + ' --- ' + previous_url); if (undefined != next_url) { //$.mobile.changePage( next_url, "slide", true); $.mobile.changePage( next_url, { transition: "slide", reverse: true, changeHash: true }); e.stopImmediatePropagation(); return false; } } ); } );
codelounge/codelounge-exposure-theme
js/exposure.js
JavaScript
gpl-2.0
3,408
#include "tacticattacker.h" TacticAttacker::TacticAttacker(WorldModel *worldmodel, QObject *parent) : Tactic("TacticAttacker", worldmodel, parent) { everyOneInTheirPos = false; maxDistance = sqrt(pow(Field::MaxX*2,2)+pow(Field::MaxY*2,2)); } RobotCommand TacticAttacker::getCommand() { RobotCommand rc; if(!wm->ourRobot[id].isValid) return rc; if(wm->ourRobot[id].Status == AgentStatus::FollowingBall) { rc.maxSpeed = 2; tANDp target = findTarget(); // OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed,3); if( p.readyToShoot ) // rc.kickspeedx = detectKickSpeed(kickType::Shoot, p.shootSensor); { rc.kickspeedz = detectChipSpeed(/*kickType::Shoot, */p.shootSensor); } rc.fin_pos = p.pos; rc.useNav = p.useNav; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Kicking) { // if(wm->gs == STATE_Indirect_Free_kick_Our) // { // rc = KickTheBallIndirect(); // } // else if(wm->gs == STATE_Free_kick_Our) // { // rc = KickTheBallDirect(); // } // else if(wm->gs == STATE_Start) // { // rc = StartTheGame(); // } if(wm->gs == STATE_Start) { rc = StartTheGame(); } else { rc = KickTheBallIndirect(); } rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Chiping) { rc = ChipTheBallIndirect(); rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::RecievingPass) { rc.fin_pos = idlePosition; rc.maxSpeed = 2.5; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::BlockingRobot) { AngleDeg desiredDeg = (wm->oppRobot[playerToKeep].pos.loc-Field::ourGoalCenter).dir(); Position final; final.loc.x = wm->oppRobot[playerToKeep].pos.loc.x - (300*cos(desiredDeg.radian())); final.loc.y = wm->oppRobot[playerToKeep].pos.loc.y - (300*sin(desiredDeg.radian())); final.dir = desiredDeg.radian(); if( wm->gs == GameStateType::STATE_Free_kick_Opp || wm->gs == GameStateType::STATE_Indirect_Free_kick_Opp) { if( wm->kn->IsInsideSecureArea(final.loc,wm->ball.pos.loc) ) { Vector2D fstInt,secInt; Circle2D secArea(wm->ball.pos.loc,ALLOW_NEAR_BALL_RANGE); Line2D connectedLine(wm->ball.pos.loc,Field::ourGoalCenter); int numberOfIntersections = secArea.intersection(connectedLine,&fstInt,&secInt); rc.fin_pos.dir = (wm->oppRobot[playerToKeep].pos.loc - Field::ourGoalCenter).dir().radian(); if( numberOfIntersections == 2 ) { if( (fstInt-final.loc).length() > (secInt-final.loc).length() ) rc.fin_pos.loc = secInt; else rc.fin_pos.loc = fstInt; } else if( numberOfIntersections == 1 ) { rc.fin_pos.loc = fstInt; } else rc.fin_pos = wm->ourRobot[this->id].pos; } else { rc.fin_pos = final; } } else { rc.fin_pos = final; } if( wm->opp_vel > 3 ) rc.maxSpeed = 3; else rc.maxSpeed = wm->opp_vel; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Idle) { rc.fin_pos = idlePosition; rc.maxSpeed = 2; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; if( wm->gs == STATE_Stop ) return rc; } if( wm->kn->IsInsideGolieArea(rc.fin_pos.loc) ) { Circle2D attackerCircles(Field::ourGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc,wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } if( wm->kn->IsInsideOppGolieArea(rc.fin_pos.loc) && !wm->cmgs.ourPenaltyKick() /*&& wm->defenceMode*/) { Circle2D attackerCircles(Field::oppGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc, wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } return rc; } RobotCommand TacticAttacker::goBehindBall() { RobotCommand rc; canKick=false; rc.maxSpeed = 1; float deg=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 30, 180)) { rc.fin_pos.loc= {wm->ball.pos.loc.x-110*cos(deg),wm->ball.pos.loc.y-110*sin(deg)}; rc.fin_pos.dir=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); } if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 20, 2)) { //double test=findBestPoint(); //rc.fin_pos.dir=test; } rc.fin_pos.loc= {wm->ball.pos.loc.x-100*cos(deg),wm->ball.pos.loc.y-100*sin(deg)}; if(wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 10, 4)) { canKick=true; } return rc; } RobotCommand TacticAttacker::KickTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Line2D b2g(target,Field::oppGoalCenter); Circle2D cir(target,300); Vector2D goal,first,second; int numOfPoints = cir.intersection(b2g,&first,&second); // if( numOfPoints == 2) // { // if( first.x > target.x ) // goal = first; // else if( second.x > target.x ) // goal = second; // else // goal = target; // } // else if( numOfPoints == 1) // goal = first; // else goal = target; wm->passPoints.clear(); wm->passPoints.push_back(goal); OperatingPosition kickPoint = BallControl(goal,100,this->id,rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; qDebug()<<"readyToShoot : "<<kickPoint.readyToShoot<<" , everyOneInTheirPos : "<<everyOneInTheirPos; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedx = detectKickSpeed(freeKickType, kickPoint.shootSensor); // Line2D ball2Target(wm->ball.pos.loc,goal); // QList<int> activeOpp = wm->kn->ActiveOppAgents(); // bool wayIsClear = true; // for(int i=0;i<activeOpp.size();i++) // { // double distance = ball2Target.dist(wm->oppRobot[activeOpp.at(i)].pos.loc); // if( distance < ROBOT_RADIUS+BALL_RADIUS ) // { // wayIsClear = false; // break; // } // } // if( wayIsClear ) // { // rc.kickspeedx = 255;// detectKickSpeed(goal); // qDebug()<<"Kickk..."; // } // else // { // rc.kickspeedx = 3;//255;// detectKickSpeed(goal); // rc.kickspeedz = 3; // qDebug()<<"CHIP..."; // } } return rc; } RobotCommand TacticAttacker::KickTheBallDirect() { RobotCommand rc; rc.maxSpeed = 0.5; tANDp target = findTarget(); OperatingPosition kickPoint = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; if( kickPoint.readyToShoot ) { rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } rc.useNav = kickPoint.useNav; return rc; } RobotCommand TacticAttacker::StartTheGame() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target(Field::oppGoalCenter.x,Field::oppGoalCenter.y); OperatingPosition kickPoint = BallControl(target, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot ) { //rc.kickspeedz = 2.5;//50; rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } return rc; } RobotCommand TacticAttacker::ChipTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Vector2D goal(target.x,target.y); OperatingPosition kickPoint = BallControl(goal, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedz = detectChipSpeed(kickPoint.shootSensor); qDebug()<<"Chip..."; } return rc; } int TacticAttacker::findBestPlayerForPass() { QList<int> ourAgents = wm->kn->findAttackers(); ourAgents.removeOne(this->id); QList<int> freeAgents , busyAgents; while( !ourAgents.isEmpty() ) { int index = ourAgents.takeFirst(); if(isFree(index)) freeAgents.append(index); else busyAgents.append(index); } QList<double> weights; for(int i=0;i<freeAgents.size();i++) { double weight = -1000000; if( wm->ourRobot[freeAgents.at(i)].isValid ) { double dist = 1 - ((wm->ball.pos.loc - wm->ourRobot[freeAgents.at(i)].pos.loc).length()/maxDistance); double prob = wm->kn->scoringChance(wm->ourRobot[freeAgents.at(i)].pos.loc) / 100; weight = (20 * prob) + (10*dist); } weights.append(weight); } int index = -1; double max = -10000; for(int i=0;i<weights.size();i++) { if( max < weights.at(i) ) { max = weights.at(i); index = freeAgents.at(i); } } return index; } void TacticAttacker::isKicker() { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = true; } void TacticAttacker::isChiper() { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = true; } void TacticAttacker::isKicker(int recieverID) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = wm->ourRobot[recieverID].pos.loc; } void TacticAttacker::isKicker(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = pos; } void TacticAttacker::isChiper(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = false; this->receiverPos = pos; } void TacticAttacker::setGameOnPositions(Position pos) { setIdlePosition(pos); } void TacticAttacker::setGameOnPositions(Vector2D pos) { Position position = wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter); setIdlePosition(position); } void TacticAttacker::setIdlePosition(Position pos) { this->idlePosition = pos; } void TacticAttacker::setIdlePosition(Vector2D pos) { this->idlePosition.loc = pos; this->idlePosition.dir = ( wm->ball.pos.loc - pos).dir().radian(); } void TacticAttacker::youHavePermissionForKick() { everyOneInTheirPos = true; if( findReciever ) { int indexOfReciever = findBestPlayerForPass(); if( indexOfReciever != -1 ) receiverPos = wm->ourRobot[indexOfReciever].pos.loc; } } void TacticAttacker::setFreeKickType(kickType type) { this->freeKickType = type; } bool TacticAttacker::isFree(int index) { QList<int> oppAgents = wm->kn->ActiveOppAgents(); while( !oppAgents.isEmpty() ) { int indexOPP = oppAgents.takeFirst(); if( (wm->ourRobot[index].pos.loc-wm->oppRobot[indexOPP].pos.loc).length() < DangerDist && fabs((wm->ourRobot[index].vel.loc - wm->oppRobot[indexOPP].vel.loc).length())<0.3 ) { return false; } } return true; }
mohsen-raoufi/Guidance
src/ai/tactic/tacticattacker.cpp
C++
gpl-2.0
13,212